Search completed in 0.96 seconds.
Link prefetching FAQ - HTTP
what is link pre
fetching?
... link pre
fetching is a browser mechanism, which utilizes browser idle time to download or pre
fetch documents that the user might visit in the near future.
... a web page provides a set of pre
fetching hints to the browser, and after the browser is finished loading the page, it begins silently pre
fetching specified documents and stores them in its cache.
...And 53 more matches
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.
...
fetch provides a better alternative that can be easily used by other technologies such as service workers.
...And 32 more matches
Fetching data from the server - Learn web development
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.
... this is achieved by using apis like xmlhttprequest or — more recently — the
fetch api.
...And 29 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.
... 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).
...And 14 more matches
Fetch API - Web APIs
the
fetch api provides an interface for
fetching resources (including across the network).
... concepts and usage
fetch provides a generic definition of request and response objects (and other things involved with network requests).
... for making a request and
fetching a resource, use the windoworworkerglobalscope.
fetch() method.
...And 12 more matches
X-DNS-Prefetch-Control - HTTP
the x-dns-pre
fetch-control http response header controls dns pre
fetching, 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 pre
fetching is performed in the background, so that the dns is likely to have been resolved by the time the referenced items are needed.
... header type response header forbidden header name no syntax x-dns-pre
fetch-control: on x-dns-pre
fetch-control: off directives on enables dns pre
fetching.
...And 12 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.
...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".
... you can only return response objects of type "opaqueredirect" if the
fetchevent.request object's mode is "manual".
...And 11 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.
...And 11 more matches
Using dns-prefetch - Web Performance
dns-pre
fetch is an attempt to resolve domain names before resources get requested.
... why use dns-pre
fetch?
... dns-pre
fetch helps developers mask dns resolution latency.
...And 10 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).
...And 6 more matches
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.
...the serviceworkerglobalscope.on
fetch event handler listens for the
fetch event.
...And 4 more matches
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
pre
fetching 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.
... dns pre
fetching 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 pre
fetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time.
...And 3 more matches
Fetch basic concepts - Web APIs
the
fetch api provides an interface for
fetching resources (including across the network).
...this article explains some of the basic concepts of the
fetch api.
...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.
...And 3 more matches
ServiceWorkerGlobalScope.onfetch - Web APIs
the on
fetch property of the serviceworkerglobalscope interface is an event handler fired whenever a
fetch event occurs (usually when the windoworworkerglobalscope.
fetch() method is called.) syntax serviceworkerglobalscope.on
fetch = function(
fetchevent) { ...
... }; example this code snippet is from the service worker pre
fetch sample (see pre
fetch example live.) the serviceworkerglobalscope.on
fetch event handler listens for the
fetch event.
...if no match is found, the code
fetches a response from the network.
...And 3 more matches
FetchEvent() - Web APIs
the
fetchevent() constructor creates a new
fetchevent object.
... syntax var
fetchevent = new
fetchevent(type, init); parameters type a domstring object specifying which event the object represents.
... this is always
fetch for
fetch events.
...And 2 more matches
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.
...And 2 more matches
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.
...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.
...And 2 more matches
PerformanceResourceTiming.fetchStart - Web APIs
the
fetchstart read-only property represents a timestamp immediately before the browser starts to
fetch the resource.
... if there are http redirects the property returns the time immediately before the user agent starts to
fetch the final resource in the redirection.
... syntax resource.
fetchstart; return value a domhighrestimestamp immediately before the browser starts to
fetch the resource.
...And 2 more matches
CSP: prefetch-src - HTTP
the http content-security-policy (csp) pre
fetch-src directive specifies valid resources that may be pre
fetched or prerendered.
... csp version 3 directive type
fetch directive default-src fallback yes.
... syntax one or more sources can be allowed for the pre
fetch-src policy: content-security-policy: pre
fetch-src <source>; content-security-policy: pre
fetch-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.
...And 2 more matches
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.
... 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.client - Web APIs
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().
... syntax var myclient =
fetchevent.client; value a client object.
... example self.addeventlistener('
fetch', function(event) { console.log(event.client); }); ...
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.
... additionally, if the
fetch isn't a navigation, replacesclientid will be an empty string.
... 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.
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.
... 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.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
the htmlcanvaselement.moz
fetchasstream() internal method used to create a new input stream that, when ready, would provide the contents of the canvas as image data.
... syntax void canvas.moz
fetchasstream(callback, type); parameters callback an nsiinputstreamcallback.
... examples save to disk with moz
fetchasstream (chrome context only) this technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico.
... { alert('succesfully made'); } }; } var mfascallback = function(iconname) { return function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputstream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asynccopy(instream, outstream, netutilcallback()); } } canvas.moz
fetchasstream(mfascallback('myicon'), 'image/vnd.microsoft.icon'); specifications not part of any specification.
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.
...
fetch metadata request headers provide the server with additional information about where the request originated from, enabling it to ignore potentially malicious requests.
... the following are
fetch metadata request headers: sec-
fetch-site sec-
fetch-mode sec-
fetch-user sec-
fetch-dest ...
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.
... 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.
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.
... syntax var reloaded =
fetchevent.isreload value a boolean.
... example self.addeventlistener('
fetch', function(event) { event.respondwith( if (event.isreload) { //return something } else { //return something else }; ); }); ...
Link types: dns-prefetch - HTML: Hypertext Markup Language
the dns-pre
fetch 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-pre
fetch for more details.
... specifications specification status comment html living standardthe definition of 'dns-pre
fetch' in that specification.
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.
... header type
fetch metadata request header forbidden header name yes, since it has prefix sec- cors-safelisted request header syntax sec-
fetch-dest: audio sec-
fetch-dest: audioworklet sec-
fetch-dest: document sec-
fetch-dest: embed sec-
fetch-dest: empty sec-
fetch-dest: font sec-
fetch-dest: image sec-
fetch-dest: manifest sec-
fetch-dest: nested-document sec-
fetch-dest: object sec-
fetch-dest: paintworklet sec-
fetch-dest: report sec-
fetch-dest: script sec-
fetch-dest: serviceworker sec-
fetch-dest: sharedworker sec-
fetch-dest: style sec-
fetch-dest: track sec-
fetch-dest: video sec-
fetch-dest: worker sec-
fetch-dest: xslt sec-
fetch-dest: audioworklet sec-
fetch-dest: audioworklet values audio audioworklet document embed empty font image...
... manifest object paintworklet report script serviceworker sharedworker style track video worker xslt nested-document examples todo specifications specification title
fetch metadata request headers the sec-
fetch-dest http request header ...
Sec-Fetch-Site - HTTP
the sec-
fetch-site
fetch metadata header indicates the relationship between a request initiator's origin and the origin of the resource.
... header type
fetch metadata request header forbidden header name yes, since it has prefix sec- cors-safelisted response header cors-safelisted request header syntax sec-
fetch-site: cross-site sec-
fetch-site: same-origin sec-
fetch-site: same-site sec-
fetch-site: none values cross-site same-origin same-site none this request does not relate to any context like site, origin, or frame.
... examples todo specifications specification title
fetch metadata request headers the sec-
fetch-site http request header ...
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.
... examples todo specifications specification title
fetch metadata request headers the sec-
fetch-user http request header ...
PerformanceTiming.fetchStart - Web APIs
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.
... syntax time = performance.timing.
fetchstart; specifications specification status comment navigation timingthe definition of 'performancetiming.
fetchstart' in that specification.
Link types: prefetch - HTML: Hypertext Markup Language
the pre
fetch 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 'pre
fetch' in that specification.
Sec-Fetch-Mode - HTTP
the sec-
fetch-mode
fetch metadata header indicates the request's mode.
... header type
fetch metadata request header forbidden header name yes, since it has prefix sec- cors-safelisted request header syntax sec-
fetch-mode: cors sec-
fetch-mode: navigate sec-
fetch-mode: nested-navigate sec-
fetch-mode: no-cors sec-
fetch-mode: same-origin sec-
fetch-mode: websocket values cors navigate nested-navigate no-cors same-origin websocket examples todo specifications specification title
fetch metadata request headers the sec-
fetch-mode http request header ...
Index - Web APIs
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.
...And 130 more matches
Graceful asynchronous programming with Promises - Learn web development
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.
... first of all, download our simple html template and the sample image file that we'll
fetch.
... 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.
...And 23 more matches
Making asynchronous programming easier with async and await - Learn web development
rewriting promise code with async/await let's look back at a simple
fetch example that we saw in the previous article:
fetch('coffee.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 my
fetch() { let response = await
fetch('coffee.jpg'); if (!response.ok) { throw new error(`http error!
... status: ${response.status}`); } else { let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } } my
fetch() .catch(e => { console.log('there has been a problem with your
fetch operation: ' + e.message); }); it makes code much simpler and easier to understand — no more .then() blocks everywhere!
...And 15 more matches
Introducing asynchronous JavaScript - Learn web development
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.
...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.
...And 14 more matches
Using readable streams - Web APIs
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).
... 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.
...And 13 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
link not allowed not allowed dns-pre
fetch 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.
... 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.
...And 13 more matches
Using Service Workers - Web APIs
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().
...(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 on
fetch rather than the xmlhttprequest api.
...this is easily done with the
fetch event.
...And 11 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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).
... 143
fetch directive csp, http, security csp
fetch directives are used in a content-security-policy header and control locations from which certain resource types may be loaded.
... 144
fetch metadata request header
fetch metadata request headers, glossary a
fetch metadata request header is a http request header that provides additional information about the context the request originated from.
...And 10 more matches
PerformanceResourceTiming - Web APIs
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.
...And 10 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
the preload value of the <link> element's rel attribute lets you declare
fetch requests in the html's <head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in.
...
fetch: resource to be accessed by a
fetch or xhr request, such as an arraybuffer or json file.
...also note that the full list of values the as attribute can take is governed by the
fetch spec — see request destinations.
...And 9 more matches
Cache - Web APIs
this is functionally equivalent to calling
fetch(), then using put() to add the results to the cache.
...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.
...And 8 more matches
Using the Resource Timing API - Web APIs
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.
...And 8 more matches
ServiceWorkerGlobalScope - Web APIs
an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.on
fetch 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.
...
fetch occurs when a
fetch() is called.
...And 8 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
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.
... as this attribute is only used when rel="preload" or rel="pre
fetch" has been set on the <link> element.
...And 8 more matches
HTTP Index - HTTP
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.
... 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.
... 43 http caching caching, guide, http the performance of web sites and applications can be significantly improved by reusing previously
fetched resources.
...And 8 more matches
An overview of HTTP - HTTP
http is a protocol which allows the
fetching of resources, such as html documents.
...a complete document is reconstructed from the different sub-documents
fetched, for instance text, layout description, images, videos, scripts, and more.
...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.
...And 8 more matches
Client-side storage - Learn web development
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.
...if not, the video name is passed to the
fetchvideofromnetwork() function to ...
... you guessed it —
fetch the video from the network.
...And 7 more matches
Handling common JavaScript problems - Learn web development
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.
...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).
... let's work through an exercise — in this example we will use a
fetch polyfill to provide support for the
fetch api in older browsers; however we also need to use the es6-promise polyfill, as
fetch makes heavy use of promises, and browsers that don't support them will still be in trouble.
...And 7 more matches
Request.cache - Web APIs
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.
...
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 7 more matches
Loading and running WebAssembly code - WebAssembly
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.
... 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.
...And 7 more matches
Third-party APIs - Learn web development
searchform.addeventlistener('submit', submitsearch); now add the submitsearch() and
fetchresults() function definitions, below the previous line: function submitsearch(e) { pagenumber = 0;
fetchresults(e); } function
fetchresults(e) { // use preventdefault() to stop the form submitting e.preventdefault(); // assemble the full url url = baseurl + '?api-key=' + key + '&page=' + pagenumber + '&q=' + searchterm.value + '&fq=document_type:("article")'; if(startdate.valu...
...e !== '') { url += '&begin_date=' + startdate.value; }; if(enddate.value !== '') { url += '&end_date=' + enddate.value; }; } submitsearch() sets the page number back to 0 to begin with, then calls
fetchresults().
...we'll do this using the
fetch api.
...And 6 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
for example, xmlhttprequest and the
fetch api follow the same-origin policy.
...modern browsers use cors in apis such as xmlhttprequest or
fetch to mitigate the risks of cross-origin http requests.
... this cross-origin sharing standard can enable cross-site http requests for: invocations of the xmlhttprequest or
fetch apis, as discussed above.
...And 6 more matches
mozIAsyncFavicons
method overview void getfaviconurlforpage(in nsiuri apageuri, in nsifavicondatacallback acallback); void getfavicondataforpage(in nsiuri apageuri, in nsifavicondatacallback acallback); void setand
fetchfaviconforpage(in nsiuri apageuri, in nsiuri afaviconuri, in boolean aforcereload, in unsigned long afaviconloadtype, [optional] in nsifavicondatacallback acallback); void replacefavicondata(in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, [optional] in prtime aexpiration); void replacefavic...
...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.
... setand
fetchfaviconforpage() 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.
...And 5 more matches
AbortController.abort() - Web APIs
a
fetch 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.
...And 5 more matches
SubtleCrypto.sign() - Web APIs
rsassa-pkcs1-v1_5 this code
fetches the contents of a text box, encodes it for signing, and signs it with a private key.
... /*
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 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.
...And 5 more matches
SubtleCrypto.verify() - Web APIs
/*
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.
... /*
fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation.
...And 5 more matches
Link types - HTML: Hypertext Markup Language
<link> <a>, <area>, <form> dns-pre
fetch 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> 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> pre
fetch suggests that the browser
fetch the linked resource in advance, as it is likely to be requested by the user.
...And 5 more matches
Navigation and resource timings - Web Performance
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.
...if there is no previous document, this value will be the same as performancetiming.
fetchstart.
...if a persistent connection is used, the value will be the same as performancetiming.
fetchstart.
...And 5 more matches
AbortController - Web APIs
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.
... when the
fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below).
...And 4 more matches
AbortSignal - Web APIs
the abortsignal interface represents a signal object that allows you to communicate with a dom request (such as a
fetch) and abort it if required via an abortcontroller object.
... examples in the following snippet, we aim to download a video using the
fetch api.
... when the
fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below).
...And 4 more matches
Cache.match() - Web APIs
a catch() clause is triggered when the call to
fetch() throws an exception.
...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().
...And 4 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else {
fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("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 whi...
... element.addeventlistener("load", () => console.log("loaded data")); console.log("
fetching data..."); element.getdata(); console.log("data
fetched"); executing this code twice in a row gives the results shown in the table below: results when data isn't cached (left) vs.
... when it is found in the cache data isn't cached data is cached
fetching data data
fetched loaded data
fetching data loaded data data
fetched even worse, sometimes the element's data property will be set and other times it won't be by the time this code finishes running.
...And 4 more matches
Request() - Web APIs
syntax var myrequest = new request(input[, init]); parameters input 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.
... example in our
fetch request example (see
fetch request live) we create a new request object using the constructor, then
fetch it using a global
fetch.
fetch call.
...And 4 more matches
Service Worker API - Web APIs
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.
... 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.
...And 4 more matches
HTML documentation index - HTML: Hypertext Markup Language
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.
... 224 link types: dns-pre
fetch attribute, html, link, link types, reference the dns-pre
fetch 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.
... 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.
...And 4 more matches
Using the application cache - HTML: Hypertext Markup Language
the process for loading documents and updating the application cache is specified in greater detail below: when the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then
fetches all the entries listed in the manifest file, creating the first version of the application cache.
...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.
...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.
...And 4 more matches
HTTP headers - HTTP
request headers contain more information about the resource to be
fetched, or about the client requesting the resource.
... origin indicates where a
fetch originates from.
...
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.
...And 4 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
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.
...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.
...if the file is not in the cache, the app adds it there first before then serving it: self.addeventlistener('
fetch', (e) => { e.respondwith( caches.match(e.request).then((r) => { console.log('[service worker]
fetching resource: '+e.request.url); return r ||
fetch(e.request).then((response) => { return caches.open(cachename).then((cache) => { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); here, we respond to the
fetch event with a function...
...And 4 more matches
Subresource Integrity - Web security
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.
...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.
...And 4 more matches
Using the WebAssembly JavaScript API - WebAssembly
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.
... 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.
...And 4 more matches
Creating a dynamic status bar extension - Archive of obsolete content
« previousnext » this article builds upon the article creating a status bar extension, which creates a static status bar panel in the firefox status bar, by dynamically updating its content with information
fetched from the web every few minutes.
...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.
... we end up reloading data from each of the windows once in 10 minutes - fixing this by creating a js component responsible for communication with the server is a good idea for one of the future articles startup: function() { this.refreshinformation(); window.setinterval(this.refreshinformation, 10*60*1000); }, this starts by calling our refreshinformation() function, which is responsible for
fetching and displaying stock ticker information in the status bar panel.
...And 3 more matches
Command line crash course - Learn web development
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.
...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.
...And 3 more matches
Using the Places keywords API
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.
... 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.
...And 3 more matches
AbortController.AbortController() - Web APIs
examples in the following snippet, we aim to download a video using the
fetch api.
... 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.
...And 3 more matches
AbortController.signal - Web APIs
examples in the following snippet, we aim to download a video using the
fetch api.
... 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.
...And 3 more matches
CacheStorage - Web APIs
in the second code block, we wait for a
fetchevent to fire.
... 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.
... finally, return whatever the custom response ended up being equal to, using
fetchevent.respondwith.
...And 3 more matches
PerformanceTiming - Web APIs
if there is no previous document, this value will be the same as performancetiming.
fetchstart.
... performancetiming.
fetchstart read only when the browser is ready to
fetch the document using an http request.
...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.
...And 3 more matches
Resource Timing API - Web APIs
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.
...the
fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup.
...the transfersize property returns the size (in octets) of the
fetched resource including the response header fields plus the response payload body.
...And 3 more matches
Response.type - Web APIs
opaqueredirect: the
fetch request was made with redirect: "manual".
... note: an "error" response never really gets exposed to script: such a response to a
fetch() would reject the promise.
... 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.
...And 3 more matches
Streams API - Web APIs
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.
...it can be used to handle response streams of the
fetch api, or developer-defined streams (e.g.
...a
fetch request).
...And 3 more matches
<script>: The Script element - HTML: Hypertext Markup Language
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.
... 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.
...And 3 more matches
Understanding WebAssembly text format - WebAssembly
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).
... this is functionally equivalent to including a separate function statement outside the function, elsewhere in the module in the same manner as we did before, e.g.: (export "getanswerplus1" (func $functionname)) the javascript code to call our above module looks like so: webassembly.instantiatestreaming(
fetch('call.wasm')) .then(obj => { console.log(obj.instance.exports.getanswerplus1()); // "43" }); importing functions from javascript we have already seen javascript calling webassembly functions, but what about webassembly calling javascript functions?
... 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).
...And 3 more matches
Choosing the right approach - Learn web development
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.
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no no yes code example the following example
fetches several resources from the server, and uses promise.all() to wait for all of them to be available before then displaying all of them — see it live, and see the source code: function
fetchanddecode(url, type) { // returning the top level promise, so the result of the entire chain is returned out of the function return
fetch(url).then(response => { // depending on what type of file is ...
...And 2 more matches
Introduction to web APIs - Learn web development
apis that
fetch data from the server to update small sections of a webpage on their own are very commonly used.
...apis that make this possible include xmlhttprequest and the
fetch api.
...find out more about such apis in
fetching data from the server.
...And 2 more matches
CustomizableUI.jsm
this is roughly equivalent to
fetching the currentset attribute and splitting by commas in the legacy apis.
... nb: will throw if called too early (before placements have been
fetched) or if the area is not currently known to customizableui.
... nb: will throw if called too early (before placements have been
fetched) or if the area is not currently known to customizableui.
...And 2 more matches
Downloads.jsm
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.
...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.
...
fetch() downloads data from a remote network location to a local file.
...And 2 more matches
nsICachingChannel
constants constant value description load_no_network_io 1 << 26 this load flag inhibits
fetching from the net.
...this flag can be used to find out whether
fetching this url would cause validation of the cache entry via the network.
... load_check_offline_cache 1 << 27 this load flag causes the offline cache to be checked when
fetching a request.
...And 2 more matches
Body.arrayBuffer() - Web APIs
examples playing music in our
fetch array buffer live, we have a play button.
...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.
...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.
...And 2 more matches
ExtendableEvent - Web APIs
this ensures that any functional events (like
fetchevent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.
... examples this code snippet is from the service worker pre
fetch sample (see pre
fetch 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.
...And 2 more matches
HTMLImageElement.crossOrigin - Web APIs
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).
...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.
...And 2 more matches
InstallEvent - Web APIs
as a child of extendableevent, it ensures that functional events such as
fetchevent are not dispatched during installation.
... examples this code snippet is from the service worker pre
fetch sample (see pre
fetch 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.
...And 2 more matches
Request - Web APIs
the request interface of the
fetch api represents a resource request.
... you can create a new request object using the request() constructor, but you are more likely to encounter a request object being returned as the result of another api operation, such as a service worker
fetchevent.request.
... examples in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then
fetch this request by passing the request object in as a parameter to a 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 ...
...And 2 more matches
Response - Web APIs
the response interface of the
fetch api represents the response to a request.
... you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker
fetchevent.respondwith, or a simple windoworworkerglobalscope.
fetch().
... examples in our basic
fetch example (run example live) we use a simple
fetch() call to grab an image and display it in an <img> element.
...And 2 more matches
WebAssembly.instantiate() - JavaScript
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.
... first overload example after
fetching some webassembly bytecode using
fetch, we compile and instantiate the module using the webassembly.instantiate() function, importing a javascript function into the webassembly module in the process.
...And 2 more matches
Application cache implementation overview
the implementation of offline cache update is in /uriloader/pre
fetch.
...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.
...after the manifest
fetch is done, nsofflinecacheupdate::loadcompleted() is called.
...if so, the update switches to downloading state and
fetches in parallel items listed in the manifest by call to nsofflinecacheupdate::processnexturi().
FxAccountsProfileClient.jsm
the fxaccountsprofileclient.jsm javascript module provides a way to
fetch firefox accounts profile information.
...components.utils.import("resource://gre/modules/fxaccountsprofileclient.jsm"); creating a new fxaccountsprofileclient new fxaccountsprofileclient(object options); method overview
fetchprofile(); attributes serverurl url profiler server url.
...methods
fetchprofile()
fetches firefox accounts profile information.
... 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.
NetUtil.jsm
method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void async
fetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attribute type description ioservice nsiioservice returns a reference to...
... } }) async
fetch() the async
fetch() method opens an input source, asynchronously, and gives an nsiinputstream containing the data obtained to the callback provided.
... async
fetch( asource, acallback ); parameters asource the source to open asynchronously.
... netutil.async
fetch(channel, function(ainputstream, aresult) { // check that we had success.
L20n Javascript API
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.
... 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.
...a 404 error when
fetching a resource file, or recursive import statements in resource files), context.translationerror, when there is a missing translation in one of supported locales; the context instance will try to retrieve a fallback translation from the next locale in the fallback chain, compiler.error, when l20n is unable to evaluate an entity to a string; there are two types of errors in this category: compiler.valueerror, when l20n can still try to use the literal source string of the entity as fallback, and compiler.indexerror otherwise.
Index
14 http delegation advanced, guide, nss up to version 3.11, nss connects directly over http to an ocsp responder to make the request and
fetch the response.
... 15 http delegation advanced, guide, nss up to version 3.11, nss connects directly over http to an ocsp responder to make the request and
fetch the response.
... 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.
...possible types are "donotuse", "forbid
fetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo".
Feed content access API
nsifeedtextconstruct represents text values in a feed; includes functions that let you
fetch the text as plain text or html.
...loading the feed and sending it to the parser is done using code similar to this:
fetch: function(feedurl) { var httprequest = null; function inforeceived() { var data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri(feedurl, null, null); if (data.length) { var parser = components.classes["@mozilla.org/feed-pro...
...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.
...to initialize a
fetch of the feed, we simply call
fetch(url).
Network request list - Firefox Developer Tools
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.
... copy > copy as
fetch copies the request as a call to the
fetch() method, including the url and any settings object.
... start performance analysis use as
fetch in console submits the request as a call to the
fetch() method in the console.
Body.json() - Web APIs
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('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( document.createelement('strong') ).textcontent = `£${product.price}`; mylist.appendchild(listitem); } }) .catch(console.error); specifications specification status comment
fetchthe definition of 'body.json()' in that specification.
Body.text() - Web APIs
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() 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(); 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.
Cache.put() - Web APIs
often, you will just want to
fetch() one or more requests, then add the result straight to your cache.
...
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.
...here we wait for a
fetchevent to fire.
... 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.
Manipulating video using canvas - Web APIs
it also
fetches references to the graphics contexts for each of the two canvases.
... 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.
... 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.
... 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.
Media Source API - Web APIs
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.
... 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.
... dash moves lots of logic out of the network protocol and into the client side application logic, using the simpler http protocol to
fetch files.
PaymentRequest: merchantvalidation event - Web APIs
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.
... request.addeventlistener("merchantvalidation", 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()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation.
... the content delivered by the validation server is forwarded to the merchant server and is then returned from the
fetch() call's fulfillment handler to the complete() method on the event.
... 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.
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.
... syntax resource.redirectstart; return value a timestamp representing the start time of the
fetch which initiates the redirect.
..."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"]; 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("...
ReadableStreamDefaultReader.read() - Web APIs
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.
... 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); }); } 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.
... async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder("utf-8"); let response = await
fetch(fileurl); let reader = response.body.getreader(); let {value: chunk, done: readerdone} = await reader.read(); chunk = chunk ?
Response.clone() - Web APIs
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.queryselector('.img1'); var image2 = document.queryselector('.img2'); var myrequest = new request('flowers.jpg');
fetch(myrequest).then(function(response) { var response2 = response.clone(); response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image1.src = objecturl; }); response2.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image2.src = objecturl; }); }); specifications specification status comment
fetchthe definition of 'clone()' in that specification.
Response.headers - Web APIs
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.
... 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.
Response.ok - Web APIs
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.
... 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.
Response.redirected - Web APIs
instead, you should actually instead do the filtering when you call
fetch().
...in the code below, a textual message is inserted into an element when a redirect occurred during the
fetch operation.
...
fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.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", { r...
...edirect: "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.status - Web APIs
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.
... 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.
Response.statusText - Web APIs
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 statustext value to the console.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg');
fetch(myrequest).then(function(response) { console.log(response.statustext); // returns "ok" 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 'statustext' in that specification.
Response.url - Web APIs
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.
... 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.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
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.
... 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.
...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.
SubtleCrypto.encrypt() - Web APIs
rsa-oaep this code
fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep.
...unction 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(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code
fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode.
... //encrypt function wants a cryptokey object const key_encoded = await crypto.subtle.importkey( "raw", key.buffer, 'aes-ctr' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc this code
fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in cbc mode.
...e"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // iv will be needed for decryption iv = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-cbc", iv }, key, encoded ); } aes-gcm this code
fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in gcm mode.
Advanced techniques: Creating and sequencing audio - Web APIs
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.
... 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.
...this time it will create an audiobuffersourcenode, and put the buffer data we've
fetched and decoded into it, and play it: function playsample(audiocontext, audiobuffer) { const samplesource = audiocontext.createbuffersource(); samplesource.buffer = audiobuffer; samplesource.connect(audiocontext.destination) samplesource.start(); return samplesource; } note: we can call stop() on an audiobuffersourcenode, however, this will happen automatically when the sampl...
...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.
<video>: The Video Embed element - HTML: Hypertext Markup Language
crossorigin this enumerated attribute indicates whether to use cors to
fetch the related image.
... when not present, the resource is
fetched without a cors request (i.e.
...length) is
fetched.
... stalled the user agent is trying to
fetch media data, but data is unexpectedly not forthcoming.
Content-Security-Policy - HTTP
directives
fetch directives
fetch directives control the locations from which certain resource types may be loaded.
... connect-src restricts the urls which can be loaded using script interfaces default-src serves as a fallback for the other
fetch directives.
...therefore it is recommended to restrict this
fetch-directive (e.g., explicitly set object-src 'none' if possible).
... pre
fetch-src specifies valid sources to be pre
fetched or prerendered.
Index - HTTP
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.
...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.
... 87 origin http, reference, header the origin request header indicates where a
fetch originates from.
... 117 x-dns-pre
fetch-control dns, http, header the x-dns-pre
fetch-control http response header controls dns pre
fetching, 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.
A typical HTTP session - HTTP
the url of a page to
fetch contains both the domain name, and the port number, though the latter can be omitted if it is 80.
...to work around this problem, web developers use several techniques: ping the server periodically via the xmlhttprequest,
fetch apis, using the websockets api, or similar protocols.
... example requests
fetching the root page of developer.mozilla.org, i.e.
...dy> <h1>simple html5 webpage</h1> <p>hello, world!</p> </body> </html> notification that the requested resource has permanently moved: http/1.1 301 moved permanently server: apache/2.4.37 (red hat) content-type: text/html; charset=utf-8 date: thu, 06 dec 2018 17:33:08 gmt location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will
fetch it) keep-alive: timeout=15, max=98 accept-ranges: bytes via: moz-cache-zlb05 connection: keep-alive content-length: 325 (the content contains a default page to display if the user-agent is not able to follow the link) <!doctype html...
Promise.any() - JavaScript
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.
... function
fetchanddecode(url) { return
fetch(url).then(response => { if(!response.ok) { throw new error(`http error!
... status: ${response.status}`); } else { return response.blob(); } }) } let coffee =
fetchanddecode('coffee.jpg'); let tea =
fetchanddecode('tea.jpg'); promise.any([coffee, tea]).then(value => { let objecturl = url.createobjecturl(value); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log(e.message); }); specifications specification promise.any ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
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).
... 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.
...
fetch('./register', { method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ 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: payload is the text that to be shown in the notification, delay defines a delay in seconds until the notification will be shown, and ttl is the time-to-live setting that keeps the notification available on the server for a specified amount of time, also defined in seconds.
Caching compiled WebAssembly modules - WebAssembly
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.
...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...
... 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).
... errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(
fetch(url)).then(results => { return results.instance }); }); } caching a wasm module with the above library function defined, getting a wasm module instance and using its exported features (while handling caching in the background) is as simple as calling it with the following parameters: a cache version, which — as we explained above — you need to update when any wasm module is updated or moved to a different url.
File I/O - Archive of obsolete content
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.async
fetch().
...so therefore for the first parameter, file, you can pass an nsifile object or a string (such as a jar path) see: netutil.async
fetch: components.utils.import("resource://gre/modules/netutil.jsm"); netutil.async
fetch(file, function(inputstream, status) { if (!components.issuccesscode(status)) { // handle error!
...var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.async
fetch(channel, function(inputstream, status) { ...
Monitoring downloads - Archive of obsolete content
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().
Using workers in extensions - Archive of obsolete content
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.
... the worker the worker thread's job in this example is to issue the xmlhttprequest calls that
fetch the updated stock information.
... 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.
Audio for Web games - Game development
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.
... 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 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.
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
names starting with `sec-` are reserved for creating new headers safe from apis using
fetch that grant developers control over headers, such as xmlhttprequest.
...ess-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 via note: the user-agent header is no longer forbidden, as per spec — see forbidden header name list (this was implemented in firefox 43) — it can now be set in a
fetch headers object, or via xhr setrequestheader().
... however, chrome will silently drop the header from
fetch requests (see chromium bug 571722).
Sending forms through JavaScript - Learn web development
historically, xmlhttprequest was designed to
fetch and send xml as an exchange format, which has since been superceded by json.
... 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.
Client-Server Overview - Learn web development
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.
...a get request is used because the request is only
fetching data (not modifying data).
...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.
Getting SpiderMonkey source code
this
fetches a snapshot of the current mozilla tree.
... 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.
nsIDOMOfflineResourceList
onchecking nsidomeventlistener an event listener to be called when
fetching the application cache manifest and checking for updates.
... checking 2 the application cache manifest is being
fetched and checked for updates.
...the resource will be
fetched and added to the application cache.
nsIFaviconService
this cache will also be written to if you use setandloadfaviconforpage() method and it encounters an error while
fetching an icon.
...you should use the new async api moziasyncfavicons.setand
fetchfaviconforpage() instead.
...you should use the new async api moziasyncfavicons.setand
fetchfaviconforpage() instead.
nsIFeed
skipdays nsiarray an array of days of the week on which the feed should not be
fetched.
...for example, to skip
fetching on mondays, a feed that does not want to be
fetched on mondays would specify "monday" in this array.
... skiphours nsiarray an array of the hours of the day during which the feed should not be
fetched.
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 akeysto
fetch, 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".
... boolean
fetchmsgpreviewtext([array, size_is (anumkeys)] in nsmsgkey akeysto
fetch, in unsigned long anumkeys, in boolean alocalonly, in nsiurllistener aurllistener); addkeywordstomessages() used to set/clear tags - we could have a single method to setkeywords which would figure out the diffs, but these methods might be more convenient.
nsIPushService
subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription()
fetches an existing subscription.
... callback the callback to call with the
fetched nsipushsubscription.
... example pushservice.getsubscription( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error
fetching subscription: " + code); return; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription.
DevTools API - Firefox Developer Tools
gettoolbox(target)
fetch the toolbox object for the given target.
... gettooldefinition(toolid)
fetch the tooldefinition object for a tool if it exists and is enabled.
... getthemedefinition(themeid)
fetch the themedefinition object for the theme with the given id.
Body.blob() - Web APIs
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 = 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.
Body.body - Web APIs
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.
... const image = document.getelementbyid('target'); //
fetch the original image
fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobject...
...url(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); specifications specification status comment
fetchthe definition of 'body' in that specification.
Body.bodyUsed - Web APIs
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.
... html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image');
fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = response.blob(); console.log(response.bodyused); return res; }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); specifications specification status comment
fetchthe definition of 'bodyused' in t...
Body - Web APIs
the body mixin of the
fetch api represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.
... examples the example below uses a simple
fetch call to grab an image and display it in an <img> tag.
... 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.
Using files from web applications - Web APIs
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.
...cument.createelement("img"); img.src = url.createobjecturl(this.files[i]); img.height = 60; img.onload = function() { url.revokeobjecturl(this.src); } li.appendchild(img); const info = document.createelement("span"); info.innerhtml = this.files[i].name + ": " + this.files[i].size + " bytes"; li.appendchild(info); } } } this starts by
fetching the url of the <div> with the id filelist.
...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.
Capabilities, constraints, and settings - Web APIs
en constriant is supported by the user agent, you can find out by calling navigator.mediadevices.getsupportedconstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediadevices.getsupportedconstraints(); document.getelementbyid("framerateslider").disabled = !supported["framerate"]; in this example, the supported constraints are
fetched, and a control that lets the user configure the frame rate is disabled if the framerate constraint isn't supported.
... 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 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.
NavigationPreloadManager - Web APIs
await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a
fetch event that uses a preloaded response.
... addeventlistener('
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 'navigationpreloadmanager' in that specification.
PasswordCredential - Web APIs
in supporting browsers an instance of this class may be passed in the credential member of the init object for global
fetch.
... 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.
... 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.
Payment processing concepts - Web APIs
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.
...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().
PerformanceResourceTiming.transferSize - Web APIs
the transfersize read-only property represents the size (in octets) of the
fetched resource.
... if the resource is
fetched from a local cache, or if it is a cross-origin resource, this property returns zero.
... syntax resource.transfersize; return value a number representing the size (in octets) of the
fetched resource.
PublicKeyCredential.response - Web APIs
the response read-only property of the publickeycredential interface is an authenticatorresponse object which is sent from the authenticator to the user agent for the creation/
fetching of credentials.
... note: when validating the
fetching of existing credentials, the whole publickeycredential object and the client extensions are necessary for the relying party's server.
... 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.
RTCConfiguration - Web APIs
icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the pre
fetched ice candidate pool.
... the default value is 0 (meaning no candidate pre
fetching 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.
RTCPeerConnection() - Web APIs
icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the pre
fetched ice candidate pool.
... the default value is 0 (meaning no candidate pre
fetching 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.
ReadableStream.cancel() - Web APIs
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".
... var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`);
fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ?
...dexof(tomatch); } if (matchfoundat === -1) { buffer = buffer.slice(-buffersize); } else if (buffer.slice(matchfoundat + tomatch.length).length >= contextafter) { console.log("here's the match:") console.log(buffer.slice( math.max(0, matchfoundat - contextbefore), matchfoundat + tomatch.length + contextafter )); console.log("cancelling
fetch"); reader.cancel(); return; } else { console.log('found match, but need more context…'); } // keep reading return reader.read().then(process); }); }).catch(err => { console.log("something went wrong.
ReadableStream.tee() - Web APIs
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.
... 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 giv...
... 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.
ReadableStream - Web APIs
the
fetch api offers a concrete instance of a readablestream through the body property of a response object.
... examples in the following example, an artificial response is created to stream html fragments
fetched from another resource to the browser.
...
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
ReadableStreamDefaultReader - Web APIs
a
fetch request).
... examples in the following example, an artifical response is created to stream html fragments
fetched from another resource to the browser.
...
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
RequestDestination - Web APIs
navigator.sendbeacon(), eventsource, <a ping>, <area ping>,
fetch(), xmlhttprequest, websocket, cache and more.
... "audioworklet" the target is data being
fetched for use by an audio worklet.
... specifications specification status comment
fetchthe definition of 'requestdestination' in that specification.
Streams API concepts - Web APIs
examples include a file access operation via a
fetch or xhr call.
... 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.
... 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.
Using textures in WebGL - Web APIs
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 = 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(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.
WebGL best practices - Web APIs
for unchanged vaos, browsers can cache the
fetch limits, whereas when vaos change, browsers must revalidate and recalculate limits.
... geterror(): causes a flush + round-trip to
fetch errors from the gpu process).
... it's quicker to sample from smaller texture images due to better inherent texture
fetch cache locality: zooming out on a non-mipmapped texture ruins texture
fetch cache locality, because neighboring pixels no longer sample from neighboring texels!
Window.open() - Web APIs
the url parameter specifies the url to be
fetched and loaded in the new window.
...the actual
fetching of the url is deferred and starts after the current script block finishes executing.
...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.
Event reference
stalled the user agent is trying to
fetch media data, but data is unexpectedly not forthcoming.
... 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.
... stalled event html5 media the user agent is trying to
fetch media data, but data is unexpectedly not forthcoming.
HTML attribute reference - HTML: Hypertext Markup Language
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.
... referrerpolicy <a>, <area>, <iframe>, <img>, <link>, <script> specifies which referrer is sent when
fetching the resource.
Access-Control-Allow-Credentials - HTTP
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.
... 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.
Origin - HTTP
the origin request header indicates where a
fetch originates from.
... note: the origin header is not set on
fetch requests with a method of head or get (this behavior was corrected in firefox 65 — see bug 1508661).
... 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.
OpenSearch description format
type="application/x-suggestions+json" specifies the url for
fetching search suggestions.
... for search suggestions, the application/x-suggestions+json url template is used to
fetch a suggestion list in json format.
... remotely
fetched favicons must not be larger than 10kb (see bug 361923).
Web Performance
this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-pre
fetchdns-pre
fetch is an attempt to resolve domain names before resources get requested.
...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 pre
fetch 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...
...in this article, we cover native browser features like rel=preconnect, rel=dns-pre
fetch, rel=pre
fetch, and rel=preload, and how to use them to your advantage.
Web security
mixed content an https page that includes content
fetched using cleartext http is called a mixed content page.
... 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.
remote/parent - Archive of obsolete content
examples property retrieval this first example shows
fetching a simple property from every existing and future process.
... // remote.js const { process } = require("sdk/remote/child"); const { processid } = require("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 t...
ui/button/action - Archive of obsolete content
ck it, but only for the currently active window: var { actionbutton } = require("sdk/ui/button/action"); var button = actionbutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to
fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
...'sdk/ui/button/action'); var button = actionbutton({ id: "my-button", label: "default", icon: "./firefox-16.png" }); you can change its label for only the currently active window like this: button.state("window", { "label" : "window-specific label" }); you can change its label for only the currently active tab like this: button.state("tab", { "label" : "tab-specific label" }); to
fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will return a state object containing all the properties for the button associated with that window or tab.
ui/button/toggle - Archive of obsolete content
ck it, but only for the currently active window: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: disableforthiswindow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to
fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state().
...'sdk/ui/button/toggle'); var button = togglebutton({ id: "my-button", label: "default", icon: "./firefox-16.png" }); you can change its label for only the currently active window like this: button.state("window", { "label" : "window-specific label" }); you can change its label for only the currently active tab like this: button.state("tab", { "label" : "tab-specific label" }); to
fetch the button state for a specific window or tab, call state(), passing it the window or tab you're interested in, and it will return a state object containing the id, label, icon, and disabled properties for the button associated with that window or tab.
How to convert an overlay extension to restartless - Archive of obsolete content
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.
...it's available in the global for a window, but in jsm you'll need to
fetch it from an interface: const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest"); here's how to load a file using it: function loadfile(url,type,returnresult) { var request = new xmlhttprequest(); request.open("get", url, true); // async=true request.responsetype = type; request.onerror = function(event) { logerrormessage("error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) ...
Supporting search suggestions in search plugins - Archive of obsolete content
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.
... 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.
Promises - Archive of obsolete content
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.
Adding preferences to an extension - Archive of obsolete content
next, we call our own refreshinformation() method to immediately
fetch and display the current information about the stock the extension is configured to monitor.
... 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.
Index - Archive of obsolete content
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.
... 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.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
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.
...es, "mail"); var ldap_gecos = getldapvalue(values, "cn"); env_user=env_user.tolowercase(); } else alert("no ldap server available, autoconfig impossible!"); //popup debug message if export mozilla_debug=1 if (env_mozdebug) { alert("mozilla_debug\nrunning ldap server: " + running_ldap_server); alert("mozilla_debug\nexecuting " + ldap_http_server + \ ldap_http_unix_uri); alert("mozilla_debug\n
fetching http://" + ldap_http_server \ + ldap_http_unix_uri + ""); } //go
fetch the preference file in a http server //needs a way to check if http server is running!
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
the sections below tell you how to
fetch, build and use the pluginhostctrl.dll .
...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.
Binding Attachment and Detachment - Archive of obsolete content
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.
... an author can ensure that all bindings are synchronously attached by calling loadbindingdocument to pre-
fetch any xbl documents that are required.
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.
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 pre
fetch 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 ...
How CSS works - Learn web development
the browser then
fetches most of the resources that are linked to by the html document, such as embedded images and videos ...
... the browser parses the
fetched css, and sorts the different rules by their selector types into different "buckets", e.g.
Index - Learn web development
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.
... 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.
General asynchronous programming concepts - Learn web development
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.
...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.
Client-side web APIs - Learn web development
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.
... in this article, we'll explain the concept, and look at technologies that make it possible, such as xmlhttprequest and the
fetch api.
Ember resources and troubleshooting - Learn web development
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.
Introduction to client-side frameworks - Learn web development
when you follow a link on this very website, your browser communicates with a server and
fetches new content to display for you.
... modern web applications typically do not
fetch and render new html files — they load a single html shell, and continually update the dom inside it (referred to as single page apps, or spas) without navigating users to new addresses on the web.
Simple Instantbird build
it is faster and more efficient to use mercurial bundles instead the first time you
fetch the complete repo.
... 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?
Interfacing with the Add-on Repository
ns."); var recurl = ""; try { recurl = prefbranch.getcharpref("getaddons.recommended.url"); } catch(e) { recurl = ""; } if (recurl == "") { prefbranch.setcharpref("getaddons.recommended.url", "https://services.addons.mozilla.org/%locale%/%app%/api/%api_version%/list/recommended/all/%max_results%/%os%/%version%?src=firefox"); prefsservice.savepreffile(null); } this
fetches the value of the extensions.getaddons.recommended.url preference, and, if the preference doesn't exist or has no value, sets the value of the preference to the correct one for the amo site.
... 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.
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...
...rt_rev_mi_test_all_local_information_first cert_rev_mi_no_overall_info_requirement cert_rev_mi_require_some_fresh_info_available cert_policy_flag_no_mapping cert_policy_flag_explicit cert_policy_flag_no_any cert_enable_ldap_
fetch cert_enable_http_
fetch new macro in utilrename.h: smime_aes_cbc_128 the nssckbi pkcs #11 module's version changed to 1.70.
NSS tools : vfychain
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.
...possible types are "donotuse", "forbid
fetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo".
NSS tools : vfychain
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.
...possible types are "donotuse", "forbid
fetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo".
Places utilities for JavaScript
the annotation objects returned or send from/to all these functions all are arrays of objects which have the properties: name the annotation name flags annotation flags expires annotation expiration mimetype mimetype of the annotation, usually only used for binary annotations type the type used for non-binary annotations value the value of the annotation getannotationsforuri()
fetch all annotations for a uri, including all properties of each annotation which would be required to recreate it.
... return array of objects, each containing the following properties: name, flags, expires, mimetype, type, value getannotationsforitem()
fetch all annotations for an item, including all properties of each annotation which would be required to recreate it.
nsIApplicationCacheNamespace
constants constant value description namespace_bypass 1 items matching this namespace can be
fetched from the network when loading from this cache.
... 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.
nsICacheEntryInfo
fetchcount long get the number of times the cache entry has been opened.
... last
fetched pruint32 get the last time the cache entry was opened (in seconds since the epoch).
nsIDOMHTMLSourceElement
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.
... 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.
nsIWebPageDescriptor
docshell/base/nsiwebpagedescriptor.idlscriptable this interface allows content being displayed in one window to be loaded into another window without re
fetching it from the network.
... display_normal 0x0002 just re
fetches the existing page.
Using the Mozilla symbol server
in the examples below, a local cache directory is used to avoid repeatedly
fetching the pdb from the server.
... 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.
Virtualenv
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.
... it will require it to be part of a clone of the github repository or have internet access to
fetch setuptools.
Add to iPhoto
otherwise, we
fetch the name of the element and look to see if it's an <img> element.
... 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.
Source map errors - Firefox Developer Tools
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.
... source-map-fehler: typeerror: networkerror when attempting to
fetch resource.
Network request details - Firefox Developer Tools
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.
... device: the device the resource was
fetched from (e.g.
AbortSignal.onabort - Web APIs
the onabort read-only property of the
fetchsignal interface is an event handler invoked when an abort event fires, i.e.
... when the
fetch request(s) the signal is communicating with is/are aborted.
CacheStorage.match() - Web APIs
here we wait for a
fetchevent to fire.
... 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...
Client.postMessage() - Web APIs
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.
... 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.
ClipboardItem() - Web APIs
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.
... 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.
ClipboardItem - Web APIs
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.
DataTransferItem.webkitGetAsEntry() - Web APIs
the first step is to create a filesystemdirectoryreader to handle
fetching the directory's contents.
... the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", function(event) { let items = event.datatransfer.items; event.preventdefault(); listing.innerhtml = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitgetasentry(); if (item) { scanfiles(item, listing); } } }, false); this
fetches the list of datatransferitem objects representing the items dropped from event.datatransfer.items.
FileSystemDirectoryReader.readEntries() - Web APIs
the first step is to create a filesystemdirectoryreader to handle
fetching the directory's contents.
... the event handler that kicks everything off, of course, is the handler for the drop event: dropzone.addeventlistener("drop", function(event) { let items = event.datatransfer.items; event.preventdefault(); listing.innerhtml = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitgetasentry(); if (item) { scanfiles(item, listing); } } }, false); this
fetches the list of datatransferitem objects representing the items dropped from event.datatransfer.items.
GeolocationCoordinates.longitude - Web APIs
examples in this simple example, we
fetch the user's location and display the resulting coordinates once they're returned.
...when the user clicks the button, we'll
fetch and display the location information.
HTMLIFrameElement.referrerPolicy - Web APIs
the htmliframeelement.referrerpolicy property reflects the html referrerpolicy attribute of the <iframe> element defining which referrer is sent when
fetching the resource.
... 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.
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.
HTMLImageElement.loading - Web APIs
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.
HTMLImageElement.referrerPolicy - Web APIs
the htmlimageelement.referrerpolicy property reflects the html referrerpolicy attribute of the <img> element defining which referrer is sent when
fetching the resource.
... 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.
HTMLImageElement - Web APIs
htmlimageelement.complete read only returns a boolean that is true if the browser has finished
fetching the image, whether successful or not.
... 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.
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.
... 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.
HTMLMediaElement - Web APIs
htmlmediaelement.networkstate read only returns a unsigned short (enumeration) indicating the current state of
fetching the media over the network.
... 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.
HTMLScriptElement - Web APIs
if neither attribute is present, then the script is
fetched and executed immediately, blocking further parsing of the page.
... 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.
HTMLSelectElement.selectedOptions - Web APIs
note also the <button>, whose role it is to trigger
fetching the htmlcollection of selected elements using the selected property.
...when clicked, the event handler
fetches the list of selected options using selectedoptions, then iterates over the options in the list.
Headers - Web APIs
the headers interface of the
fetch api allows you to perform various actions on http request and response headers.
...ext/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor: var myheaders = new headers({ 'content-type': 'text/xml' }); // or, using an array of arrays: myheaders = new headers([ ['content-type', 'text/xml'] ]); myheaders.get('content-type') // should return 'text/xml' specifications specification status comment
fetchthe definition of 'headers' in that specification.
Timing element visibility with the Intersection Observer API - Web APIs
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.
...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.
MediaError.code - Web APIs
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.
MediaError - Web APIs
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.
MediaSource.endOfStream() - Web APIs
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.
...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
the most common use case for this is to immediately
fetch all pending mutation records immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer.
...*/ /* 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.
PasswordCredential.additionalData - Web APIs
it then stores the form object in the additionaldata parameter, before sending it to server in a call to
fetch.
...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.
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.
... 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.
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.
... 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.
PaymentResponse.complete() - Web APIs
examples the following example sends payment information to a secure server using the
fetch api.
...var payment = new paymentrequest(supportedinstruments, details, options); payment.show().then(function(paymentresponse) { var
fetchoptions = { method: 'post', credentials: include, body: json.stringify(paymentresponse) }; var serverpaymentrequest = new request('secure/payment/endpoint');
fetch(serverpaymentrequest,
fetchoptions).then( response => { if (response.status < 400) { paymentresponse.complete("success"); } else { paymentresponse.complete("fail"); }; }).catch( reason => { paymentresponse.complete("fail"); }); }).catch(function(err) { console.error("uh oh, something ...
PerformanceEntry.startTime - Web APIs
"resource" - returns the timestamp immediately before the browser starts
fetching the resource.
...the entry is a performanceresourcetiming object), this property returns the performanceentry.
fetchstart timestamp.
PerformanceEventTiming - Web APIs
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.
PerformanceResourceTiming.decodedBodySize - Web APIs
the decodedbodysize read-only property returns the size (in octets) received from the
fetch (http or cache) of the message body, after removing any applied content-codings.
... syntax resource.decodedbodysize; return value the size (in octets) received from the
fetch (http or cache) of the message body, after removing any applied content-codings.
PerformanceResourceTiming.encodedBodySize - Web APIs
the encodedbodysize read-only property represents the size (in octets) received from the
fetch (http or cache), 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.
PerformanceResourceTiming.nextHopProtocol - Web APIs
the nexthopprotocol read-only property is a string representing the network protocol used to
fetch the resource, as identified by the alpn protocol id (rfc7301).
... syntax resource.nexthopprotocol; return value a string representing the network protocol used to
fetch the resource, as identified by the alpn protocol id (rfc7301).
PerformanceResourceTiming.redirectEnd - Web APIs
when
fetching a resource, if there are multiple http redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property returns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is returned.
..."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"]; 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("...
PerformanceResourceTiming.secureConnectionStart - Web APIs
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.
..."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"]; 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("...
PerformanceResourceTiming.workerStart - Web APIs
the workerstart read-only property of the performanceresourcetiming interface 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.
..."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
this can be used by the developer to control the stream as more chunks are
fetched.
... 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
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.
... 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.
ReadableStream.pipeThrough() - Web APIs
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.
... //
fetch the original image
fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(rs => logreadablestream('
fetch response stream', rs)) // create a gray-scaled png stream out of the original .then(body => body.pipethrough(new pngtransformstream())) .then(rs => logreadablestream('png chunk stream', rs)) specifications specification status comment streamsthe definition of 'pipethrough()' in that specification.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
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.
... 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.
ReadableStreamDefaultReader.cancel() - Web APIs
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.
... 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.
Request.context - Web APIs
this defines what sort of resource is being
fetched.
... 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.
Response() - Web APIs
examples in our
fetch response 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.
Response.error() - Web APIs
note: an "error" response never really gets exposed to script: such a response to a
fetch() would reject the promise.
... specifications specification status comment
fetchthe definition of 'error()' in that specification.
ServiceWorkerRegistration.update() - Web APIs
it
fetches the worker's script url, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker.
... the
fetch of the worker bypasses any browser caches if the previous
fetch occurred over 24 hours ago.
SubtleCrypto.importKey() - Web APIs
*/ function importprivatekey(pem) { //
fetch the part of the pem string between header and footer const pemheader = "-----begin private key-----"; const pemfooter = "-----end private 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 arraybuffer c...
...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...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
//load geometry with
fetch() and response.json() const response = await
fetch('assets/geometry.json'); const vertices = await response.json(); //create array buffer const buffer = new arraybuffer(20 * vertices.length); //fill array buffer const dv = new dataview(buffer); for (let i = 0; i < vertices.length; i++) { dv.setfloat32(20 * i, vertices[i].position[0], true); dv.setfloat32(20 * i + 4, vertices[i].position[1], ...
...then we could load the binary file and interpret it as an array buffer: const response = await
fetch('assets/geometry.bin'); const buffer = await response.arraybuffer(); consume array buffer with webgl first, we create a new vertex buffer object (vbo) and supply it with our array buffer: //bind array buffer to a vertex buffer object const vbo = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vbo); gl.bufferdata(gl.array_buffer, buffer, gl.static_draw); then, we specify the memory layout ...
Inputs and input sources - Web APIs
t => { inputsourcelist = event.session.inputsources; inputsourcelist.foreach(source => { switch(source) { case "left": lefthandsource = source; break; case "right": righthandsource = source; break; } }); }); the inputsourceschange event is also fired once when the session's creation callback first completes execution, so you can use it to
fetch the input source list as soon as it's available at startup time.
...with either the this starts by
fetching the target ray's space into the local constant targetrayspace.
Web Authentication API - Web APIs
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.
...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.
Sending and Receiving Binary Data - Web APIs
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.
...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.
Synchronous and asynchronous requests - Web APIs
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.
Using XMLHttpRequest - Web APIs
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.
... 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.
XMLHttpRequest.readyState - Web APIs
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.
... done the
fetch operation is complete.
XMLHttpRequest.send() - Web APIs
an xmlhttprequestbodyinit, which per the
fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring object.
... networkerror the resource type to be
fetched is a blob, and the method is not get.
XMLHttpRequestResponseType - Web APIs
see html in xmlhttprequest to learn more about using xhr to
fetch html content.
...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.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
the new xrrigidtransform's reference space is then
fetched and returned to the caller.
...applymousemovement() should be called when drawing a frame, immediately before
fetching the viewer's pose using getviewerpose(), and the rendering should be performed in this reference space.
Web APIs
aambient light eventsbbackground tasksbattery api beaconbluetooth apibroadcast channel apiccss counter stylescss font loading api cssomcanvas apichannel messaging apiconsole apicredential management apiddomeencoding apiencrypted media extensionsf
fetch apifile system api frame timing apifullscreen apiggamepad api geolocation apihhtml drag and drop apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apipe...
...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 ...
shape-outside - CSS: Cascading Style Sheets
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.
Getting Started - Developer guides
<!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 alway...
... if(timearray[timearray.length-1] === '') { timearray.pop(); } lastdata.textcontent = timearray[timearray.length-1]; } setinterval(
fetchdata, 5000); </script> </body> </html> ...
Media events - Developer guides
stalled sent when the user agent is trying to
fetch media data, but data is unexpectedly not forthcoming.
... 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.
HTML attribute: crossorigin - HTML: Hypertext Markup Language
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.
... <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.
HTML: Hypertext Markup Language
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.
HTTP caching - HTTP
the performance of web sites and applications can be significantly improved by reusing previously
fetched resources.
... cache validation when a cached document's expiration time has been reached, it is either validated or
fetched again.
HTTP conditional requests - HTTP
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.
...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.
Content negotiation - HTTP
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.
...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.
CSP: connect-src - HTTP
the apis that are restricted are: <a> ping,
fetch, xmlhttprequest, websocket, eventsource, and navigator.sendbeacon().
... note: connect-src 'self' does not resolve to websocket schemas in all browsers, more info: https://github.com/w3c/webappsec-csp/issues/7 csp version 1 directive type
fetch directive default-src fallback yes.
CSP: default-src - HTTP
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 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 pre
fetch-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.
CSP: object-src - HTTP
therefore it is recommended to restrict this
fetch-directive (e.g.
... csp version 1 directive type
fetch directive default-src fallback yes.
Referrer-Policy - 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.
...errer: <meta name="referrer" content="origin"> or set it for individual requests with the referrerpolicy attribute on <a>, <area>, <img>, <iframe>, <script>, or <link> elements: <a href="http://example.com" referrerpolicy="origin"> alternatively, a noreferrer link relation on an a, area, or link element can be set: <a href="http://example.com" rel="noreferrer"> integration with css css can
fetch resources referenced from stylesheets.
Set-Cookie - HTTP
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.
...when calling xmlhttprequest.send() or
fetch().
HTTP Messages - HTTP
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).
...not all requests have one: requests
fetching resources, like get, head, delete, or options, usually don't need one.
Promise.prototype.then() - JavaScript
function
fetch_current_data() { // the
fetch() api returns a promise.
... 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.
WebAssembly.Instance() constructor - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } };
fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { ...
... imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(
fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); specifications specification webassembly javascript interfacethe definition of 'instance' in that specification.
WebAssembly.Instance.prototype.exports - 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.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(
fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); note: you can also find this example as instantiate-streaming.html on github (view it live also).
WebAssembly.Instance - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } };
fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { impor...
...ted_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(
fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); this also demonstrates how the exports property is used to access exported functions.
WebAssembly.Memory() constructor - JavaScript
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.
... 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.
WebAssembly.Memory.prototype.buffer - JavaScript
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.
... 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.
WebAssembly.Memory - JavaScript
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.
... 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.
WebAssembly.compileStreaming() - JavaScript
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.
WebAssembly.instantiateStreaming() - JavaScript
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.
WebAssembly.validate() - JavaScript
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.
...
fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(bytes) { var valid = webassembly.validate(bytes); console.log("the given bytes are " + (valid ?
WebAssembly - JavaScript
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.
for await...of - JavaScript
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.
Performance fundamentals - Web Performance
nt an application's first frame that comprises visually some html and css to style that html: the html must be parsed the dom for that html must be constructed resources like images in that part of the dom have to be loaded and decoded the css styles must be applied to that dom the styled document has to be reflowed nowhere in that list is "load the js file needed for an uncommon menu"; "
fetch and decode the image for the high scores list", etc.
... 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.
Mixed content - Web security
an https page that includes content
fetched using cleartext http is called a mixed content page.
... 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).
WebAssembly Concepts - WebAssembly
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.
...the glue code also contains the logic for calling the above-mentioned webassembly javascript apis to
fetch, load and run the .wasm file.
Index - WebAssembly
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.
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
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.
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
in this example we
fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-worker").page({ contentscript: getfirstparagraph, contenturl: "http://en.wikipe...
Bookmarks - Archive of obsolete content
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.
Session store API - Archive of obsolete content
fetching a saved value you can
fetch a value associated with a tab at any time (whether the tab is in the process of being restored or not), using code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, ...
downloading - Archive of obsolete content
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.
Repackaging Firefox - Archive of obsolete content
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.
Building XULRunner - Archive of obsolete content
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.
Mozilla XForms Specials - Archive of obsolete content
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.
Asynchronous JavaScript - Learn web development
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.
Test your skills: JSON - Learn web development
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.
Setting up your own test automation environment - Learn web development
function() { driver.findelement(webdriver.by.name('q')).sendkeys('lambdatest\n').then(function() { driver.gettitle().then(function(title) { settimeout(function() { console.log(title); driver.quit(); }, 5000); }); }); }); } searchtextongoogle(); visit your lambdatest automation dashboard, to
fetch your lambdatest's username and access key by clicking on the key icon on the top-right(see username and access keys).
Deploying our app - Learn web development
, "build": "npm run test && parcel build src/index.html" } now of course we need to add the test to our codebase; create a new directory in your root directory called tests: mkdir tests inside the new directory, create a test file: cd tests touch nasa-feed.test.js open this file, and add the contents of nasa-feed.test.js to it: this test uses the axios package to
fetch the data feed we want to test; to install this dependency, run the following command: npm install --save-dev axios we need to manually install axios because parcel won't help us with this dependency.
Old Thunderbird build
it is faster and more efficient to use mercurial bundles instead the first time you
fetch the complete repo.
HTML parser threading
when the executor acts on speculative loads, it starts speculative http
fetches for images (including video poster frames), style sheets and scripts.
WebRequest.jsm
types resource types the resource type string identifies the kind of resource being
fetched.
openLocationLastURL.jsm
this object lets you
fetch and change the url that is placed in the "open location" dialog box when it opens.
Fonts for Mozilla 2.0's MathML engine
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.
HTTP delegation
background up to version 3.11, nss connects directly over http to an ocsp responder to make the request and
fetch the response.
HTTP delegation
background up to version 3.11, nss connects directly over http to an ocsp responder to make the request and
fetch the response.
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.4 release notes
ne does not validate its inputs bug 453735: when using cert9 (sqlite3) db, set or change master password fails bug 463544: warning: passing enum* for an int* argument in pkix_validate.c bug 469588: coverity errors reported for softoken bug 470055: pkix_httpcertstore_findsocketconnection reuses closed socket bug 470070: multiple object leaks reported by tinderbox bug 470479: io timeout during cert
fetching makes libpkix abort validation.
NSS 3.15.5 release notes
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).
NSS 3.45 release notes
if a failure is encountered while
fetching any of the matching certificates, secfailure is returned and *results will be null.
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
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).
Necko walkthrough
then in necko http code (still on the main thread for now): nshttpchannel::asyncopen nshttpchannel::beginconnect() creates nshttpconnectioninfo object for the channel checks if we're proxying or not fires off the dns pre
fetch request (dispatched to dns thread pool) some other things nshttpchannel::connect might to a speculativeconnect (pre open tcp socket) nshttpchannel::continueconnect some cache stuff nshttpchannel::setuptransaction creates new nshttptransaction, and inits it with mrequesthead (the request headers) and muploadstream (which was created from the request data in c...
Index
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.
JS_NewObject
normally we simply use the class's name as the name of the property of the global object to
fetch.
JS_NewPropertyIterator
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.
Stored value
js_lookupproperty
fetches a property's stored value without triggering its getter.
SpiderMonkey releases
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.
Shell global objects
{ object, property }
fetch the property named params.property of params.object.
Manipulating bookmarks using Places
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.
Places
retrieving part of the bookmarks tree how to
fetch a section of the bookmarks tree using queries.
XPCOM Stream Guide
netutil.jsm provides apis for copying an input stream to an output stream (the asynccopy() method), getting an input stream from another source (the async
fetch() method), and reading an input stream into a string (the readinputstreamtostring() method).
Index
then, the uri can be
fetched by calling open() or asyncopen().
Components.utils.Sandbox
the following objects are supported: -promise (removed in firefox 37) css indexeddb (web worker only) xmlhttprequest textencoder textdecoder url urlsearchparams atob btoa blob file crypto rtcidentityprovider
fetch (added in firefox 41) caches filereader for example: var sandboxscript = 'var encoded = btoa("hello");' + 'var decoded = atob(encoded);'; var options = { "wantglobalproperties": ["atob", "btoa"] } var sandbox = components.utils.sandbox("https://example.org/", options); components.utils.evalinsandbox(sandboxscript, sandbox); ...
Components.utils.importGlobalProperties
the following strings are supported: string/object xpcom component atob blob btoa crypto css
fetch file nsidomfile indexeddb nodefilter firefox 60 nsidomnodefilter obsolete since gecko 60 rtcidentityprovider textdecoder textencoder url urlsearchparams xmlhttprequest nsixmlhttprequest obsolete since gecko 60 for string/object in table without a minimum firefox...
IAccessible2
thus, if there's a reorder/show/hide event the at knows which part of the internal structure has been invalidated and can re
fetch just that part.
imgICache
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.
nsICRLInfo
inherits from: nsisupports last changed in gecko 1.7 attributes attribute type description last
fetchurl autf8string the url this crl was last
fetched from.
nsICRLManager
updatecrlfromurl() update an existing crl from the last
fetched url.
nsIChannel
then, the uri can be
fetched by calling open() or asyncopen().
nsIDNSService
speculative requests return errors if pre
fetching is disabled by configuration.
nsIDocShell
allowdnspre
fetch boolean attribute that determines whether dns pre
fetch is allowed for this subtree of the docshell tree.
nsIDownloadManager
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.
nsIFeedResult
uri nsiuri the address from which the feed was
fetched.
nsIINIParser
// 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".
nsIMsgDBHdr
accountkey string indicates the account that was originally used to
fetch the message.
nsIMsgDBView
void reloadmessage(); reloadmessagewithallparts() reload the currently shown message with
fetchcompletemessage set to true.
nsINavHistoryContainerResultNode
nsinavhistoryresultnode getchild( in unsigned long aindex ); parameters aindex the index into the child list of the node to
fetch.
nsIStringBundleService
intl/strres/nsistringbundle.idlscriptable provides the string bundle service, which provides a way to
fetch localized strings from a property file.
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 async
fetchtelemetrydata(in nsi
fetchtelemetrydatacallback 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
astring formaturlpref( in astring apref ); parameters apref a string representing the name of the preference from which to
fetch the url to format.
nsIUpdateManager
updatecount long the number of updates in the history list; the updates can be
fetched by calling getupdateat().
nsIWebBrowserPersist
persistflags unsigned long flags governing how data is
fetched and saved from the network.
nsIWindowMediator
getmostrecentwindow() this is a shortcut for simply
fetching the first window in front to back order.
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
when you do not use an index, all the results from the query have to first be
fetched, and then those results are sorted.
Declaring and Calling Functions
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.
Plug-in Basics - Plugins
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.
AddressErrors - Web APIs
!validcountries.includes(shippingaddress.country)) { ev.target.shippingoptions = []; shippingaddresserrors.country = invalidcountryerror; updatedetails = { error: genericaddresserror, shippingaddresserrors, ...defaultpaymentdetails }; } ev.updatewith(updatedetails); } the shippingaddresschange event doesn't receive the paymentrequest object directly, so we
fetch it from the target property of the event.
BaseAudioContext.decodeAudioData() - Web APIs
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.
Cache.add() - Web APIs
the add() method is functionally equivalent to the following:
fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly.
Cache.addAll() - Web APIs
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.
Clients.claim() - Web APIs
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.
Clipboard.read() - Web APIs
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.
Clipboard API - Web APIs
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.
ConstantSourceNode.offset - Web APIs
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.
ContentIndex.add() - Web APIs
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.
Content Index API - Web APIs
examples could be a news website pre
fetching the latest articles in the background, or a content streaming app registering downloaded content.
ConvolverNode - Web APIs
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; } ...
CustomElementRegistry.whenDefined() - Web APIs
<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.
DOMParser - Web APIs
these properties can also be read to
fetch html fragments corresponding to the corresponding dom subtree.
Document.open() - Web APIs
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.
Element.innerHTML - Web APIs
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 "<", thereby essentially converting the html into raw text.
Event - Web APIs
animationevent audioprocessingevent beforeinputevent beforeunloadevent blobevent clipboardevent closeevent compositionevent cssfontfaceloadevent customevent devicelightevent devicemotionevent deviceorientationevent deviceproximityevent domtransactionevent dragevent editingbeforeinputevent errorevent
fetchevent focusevent gamepadevent hashchangeevent idbversionchangeevent inputevent keyboardevent mediastreamevent messageevent mouseevent mutationevent offlineaudiocompletionevent overconstrainederror pagetransitionevent paymentrequestupdateevent pointerevent popstateevent progressevent relatedevent rtcdatachannelevent rtcidentityerrorevent rtcidentityevent rtcpeerconnectioniceev...
ExtendableEvent.waitUntil() - Web APIs
the activate events in service workers use waituntil() to buffer functional events such as
fetch and push until the promise passed to waituntil() settles.
FederatedCredential - Web APIs
in supporting browsers, an instance of this class may be passed the credential received from the init object for global
fetch.
FederatedCredential - Web APIs
in browsers that support it, an instance of this interface may be passed in the credential member of the init object for global
fetch.
FileList - Web APIs
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.
HTMLAreaElement.referrerPolicy - Web APIs
the htmlareaelement.referrerpolicy property reflect the html referrerpolicy attribute of the <area> element defining which referrer is sent when
fetching the resource.
HTMLAreaElement - Web APIs
htmlareaelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when
fetching the linked resource.
HTMLElement - Web APIs
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.
HTMLIFrameElement - Web APIs
htmliframeelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when
fetching the linked resource.
HTMLImageElement.x - Web APIs
<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.
HTMLImageElement.y - Web APIs
<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.
HTMLLinkElement.as - Web APIs
the as property of the htmllinkelement interface returns a domstring representing the type of content being loaded by the html link, one of "script", "style", "image", "video", "audio", "track", "font", "
fetch".
HTMLLinkElement.referrerPolicy - Web APIs
the htmllinkelement.referrerpolicy property reflect the html referrerpolicy attribute of the <link> element defining which referrer is sent when
fetching the resource.
HTMLOrForeignElement.nonce - Web APIs
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.
HTMLOrForeignElement - Web APIs
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.
HTMLScriptElement.referrerPolicy - Web APIs
the referrerpolicy property of the htmlscriptelement interface reflects the html referrerpolicy of the <script> element and
fetches made by that script, defining which referrer is sent when
fetching the resource.
Headers() - Web APIs
r' : 'zeke are cool' }; var myheaders = new headers(httpheaders); you can now create another headers object, passing it the first headers object as its init object: var secondheadersobj = new headers(myheaders); secondheadersobj.get('content-type'); // would return 'image/jpeg' — it inherits it from the first headers object specifications specification status comment
fetchthe definition of 'headers()' in that specification.
Headers.delete() - Web APIs
new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specifications specification status comment
fetchthe definition of 'delete()' in that specification.
Headers.get() - Web APIs
specifications specification status comment
fetchthe definition of 'get()' in that specification.
Headers.getAll() - Web APIs
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.
Headers.has() - Web APIs
pty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status comment
fetchthe definition of 'has()' in that specification.
Headers.set() - Web APIs
specifications specification status comment
fetchthe definition of 'set()' in that specification.
Checking when a deadline is due - Web APIs
here we
fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (getdate() is needed for this, as getday() returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (getfullyear() is needed; getyear() is deprecated, and returns a weird value that is not much use to anyone!) var objectstore = db.transaction(['todolis...
MediaDevices.ondevicechange - Web APIs
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.
MediaError.message - Web APIs
the error handler looks like this: audioelement.onerror = function() { let s = ""; let err = audioelement.error; switch(err.code) { case mediaerror.media_err_aborted: s += "the user canceled the audio."; break; case mediaerror.media_err_network: s+= "a network error occurred while
fetching the audio."; break; case mediaerror.media_err_decode: s+= "an error occurred while decoding the audio."; break; case mediaerror.media_err_src_not_supported: s+= "the audio is missing or is in a format not supported by your browser."; break; default: s += "an unknown error occurred."; break; } let message = err.m...
MediaSource.activeSourceBuffers - Web APIs
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.activesourcebuffers); // will contain the source buffer that was added above, // as it is selected for playing in the video player video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.app...
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
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); }); }; ...
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
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 'readystate' in that specification.
MediaSource.sourceBuffers - Web APIs
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); }); }; ...
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.
MerchantValidationEvent - Web APIs
merchantvalidationevent.validationurl secure context a usvstring specifying a url from which the site or app can
fetch payment handler specific validation information.
Navigator.getBattery() - Web APIs
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.
PasswordCredential - Web APIs
in supporting browsers, an instance of this class may be passed the credential from the init object for global
fetch.
PaymentAddress - Web APIs
const json = response.tojson(); const httpresponse = await
fetch("/pay/", { method: "post", body: json }); const result = httpresponse.ok ?
PaymentRequest.onmerchantvalidation - Web APIs
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.
PaymentResponse.onpayerdetailchange - Web APIs
alidation to the errors list const errors = await promise.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await
fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); specifications specification status comment payment request apithe definition of 'onpayerdetailchange' in that specification.
PaymentResponse: payerdetailchange event - Web APIs
alidation to the errors list const errors = await promise.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await
fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addeventlistener equivalent you could also set up the event handler using the addeventlistener() method: response.addeventlistener("payerdetailchange", async ev => { ...
Performance.navigation - Web APIs
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.
PerformanceResourceTiming.connectEnd - Web APIs
to just get the "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 *start and *end properties properties = ["connectstart", "connectend", "domainlookupstart", "domainlookupend", "
fetchstart", "redirectstart", "redirectend", "requeststart", "responsestart", "responseend", "secureconnectionstart"]; 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("...
PerformanceResourceTiming.connectStart - Web APIs
"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"]; 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("...
PerformanceResourceTiming.domainLookupEnd - Web APIs
to just get the "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 *start and *end properties properties = ["connectstart", "connectend", "domainlookupstart", "domainlookupend", "
fetchstart", "redirectstart", "redirectend", "requeststart", "responsestart", "responseend", "secureconnectionstart"]; 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("...
PerformanceResourceTiming.domainLookupStart - Web APIs
"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"]; 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("...
PerformanceResourceTiming.requestStart - Web APIs
"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"]; 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("...
PerformanceResourceTiming.responseEnd - Web APIs
"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"]; 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("...
PerformanceResourceTiming.responseStart - Web APIs
"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"]; 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("...
PublicKeyCredential.getClientExtensionResults() - Web APIs
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.
PublicKeyCredential - Web APIs
ams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we
fetch an existing credential from an authenticator, using navigator.credentials.get().
PublicKeyCredentialRequestOptions.timeout - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), timeout: 6000 // wait a minute for the
fetching operation // and maybe fail if it takes longer }; 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) { console.error(err); }); specifications specification status comment ...
PublicKeyCredentialRequestOptions - Web APIs
the publickeycredentialrequestoptions dictionary of the web authentication api holds the options passed to navigator.credentials.get() in order to
fetch a given publickeycredential.
PushMessageData - Web APIs
unlike the similar methods in the
fetch api, which only allow the method to be invoked once, these methods can be called multiple times.
RTCDataChannel.onbufferedamountlow - Web APIs
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.
RTCIceCandidate.port - Web APIs
example this code snippet
fetches the ip address and port number of the candidate, storing them into an object for future use.
RTCPeerConnection.getConfiguration() - Web APIs
figuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example
fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero.
ReadableStream.pipeTo() - Web APIs
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.
ReadableStreamDefaultController.close() - 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 'close()' in that specification.
ReadableStreamDefaultController.enqueue() - 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 'enqueue()' in that specification.
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...
Request.clone() - Web APIs
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.
Request.credentials - Web APIs
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.
Request.destination - Web APIs
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.
Request.headers - Web APIs
s in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; var myrequest = new request('flowers.jpg', myinit); mycontenttype = myrequest.headers.get('content-type'); // returns 'image/jpeg' specifications specification status comment
fetchthe definition of 'headers' in that specification.
Request.integrity - Web APIs
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.
Request.method - Web APIs
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.
Request.mode - Web APIs
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.
Request.redirect - Web APIs
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.
Request.referrer - Web APIs
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.
Request.referrerPolicy - Web APIs
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.
Request.url - Web APIs
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.
Response.redirect() - Web APIs
example responseobj.redirect('https://www.example.com', 302); specifications specification status comment
fetchthe definition of 'redirect()' in that specification.
Response.useFinalURL - Web APIs
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: on
fetch = (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.
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.
ServiceWorkerContainer: message event - Web APIs
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(() => { // ...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
}) 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.
SourceBuffer.abort() - Web APIs
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.
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...
TextTrackList.onremovetrack - Web APIs
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.
URL - Web APIs
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.
URL API - Web APIs
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.
A basic 2D WebGL animation example - Web APIs
"vertex" : "fragment"} shader:`); console.log(gl.getshaderinfolog(shader)); } return shader; } the code is
fetched from the html document by obtaining the value of the text node contained within the <script> element with the specified id.
Compressed texture formats - Web APIs
no examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await
fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create m...
Lighting in WebGL - Web APIs
w needs to be updated to take into account the lighting value computed by the vertex shader: const fssource = ` varying highp vec2 vtexturecoord; varying highp vec3 vlighting; uniform sampler2d usampler; void main(void) { highp vec4 texelcolor = texture2d(usampler, vtexturecoord); gl_fragcolor = vec4(texelcolor.rgb * vlighting, texelcolor.a); } `; here we
fetch the color of the texel, just like we did in the previous example, but before setting the color of the fragment, we multiply the texel's color by the lighting value to adjust the texel's color to take into account the effect of our light sources.
Using shaders to apply color in WebGL - Web APIs
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.
Signaling and video calling - Web APIs
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.
A simple RTCDataChannel sample - Web APIs
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.
Using DTMF with WebRTC - Web APIs
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.devicePixelRatio - Web APIs
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.
Window - Web APIs
windoworworkerglobalscope.
fetch() starts the process of
fetching a resource from the network.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
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.
Worker - Web APIs
(
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.
XMLDocument.load() - Web APIs
as of at least gecko 1.9, this no longer supports cross-site loading of documents (use xmlhttprequest or
fetch() instead).
HTML in XMLHttpRequest - Web APIs
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.
XMLHttpRequest() - Web APIs
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.
XMLHttpRequest.getResponseHeader() - Web APIs
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.
XMLHttpRequestEventTarget - Web APIs
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.
XRSession: select event - Web APIs
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: selectend event - Web APIs
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.
XRSession: selectstart event - Web APIs
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.
XRSession: squeeze event - Web APIs
the handler
fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandlesqueezewithray().
XRSession: squeezeend event - Web APIs
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.
XRSession: squeezestart event - Web APIs
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.
-moz-image-rect - CSS: Cascading Style Sheets
hat we've saved the last one, start rotating for (var i=1; i<=4; i++) { var curid = "box" + i; // shift the background images var curstyle = window.getcomputedstyle(document.getelementbyid(curid), null).getpropertyvalue("background-image"); document.getelementbyid(curid).style.backgroundimage = prevstyle; prevstyle = curstyle; } } this uses window.getcomputedstyle() to
fetch the style of each element, shifting it to the following element.
Coordinate systems - CSS: Cascading Style Sheets
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.
exsl:node-set() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes 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.
Common (exsl) - EXSLT
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.
Ajax - Developer guides
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.
Guide to Web APIs - Developer guides
web apis from a to z aambient light eventsbbackground tasksbattery api beaconbluetooth apibroadcast channel apiccss counter stylescss font loading api cssomcanvas apichannel messaging apiconsole apicredential management apiddomeencoding apiencrypted media extensionsf
fetch apifile system api frame timing apifullscreen apiggamepad api geolocation apihhtml drag and drop apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apipe...
Setting up adaptive streaming media sources - Developer guides
other reasons to use live profile over ondemand for vod content may be: your client or server does not support range requests your server cannot cache range requests efficiently your server cannot pre
fetch range requests efficiently the sidx* is large and having to load it first slows down startup a little you want to use the original files for both dash and other forms of delivery (such as microsoft smooth streaming) as a transition strategy you can use the same media files for both live transmission and vod at a later stage *sidx or segmentindexbox is a structure describing a segment by givi...
Overview of events and handlers - Developer guides
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.
HTML5 - Developer guides
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.
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.
Link types: prerender - HTML: Hypertext Markup Language
the prerender keyword for the rel attribute of the <link> element is a hint to browsers that the user might need the target resource for the next navigation, and therefore the browser can likely improve the user experience by preemptively
fetching and processing the resource — for example, by
fetching its subresources or performing some rendering in the background offscreen.
Evolution of HTTP - HTTP
at this point, a typical request and response looked like this: get /mypage.html http/1.0 user-agent: ncsa_mosaic/2.0 (windows 3.1) 200 ok date: tue, 15 nov 1994 08:12:31 gmt server: cern/3.0 libwww/2.17 content-type: text/html <html> a page with an image <img src="/myimage.gif"> </html> followed by a second connection and request to
fetch the image (followed by a response to that request): get /myimage.gif http/1.0 user-agent: ncsa_mosaic/2.0 (windows 3.1) 200 ok date: tue, 15 nov 1994 08:12:32 gmt server: cern/3.0 libwww/2.17 content-type: text/gif (image content) these novelties have not been introduced as concerted effort, but as a try-and-see approach over the 1991-1995 period: a server and a browser added one feature and ...
MIME types (IANA media types) - HTTP
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).
Reason: CORS request external redirect not allowed - HTTP
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.
Reason: CORS request not HTTP - HTTP
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.
Accept - HTTP
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.
Access-Control-Allow-Methods - HTTP
examples access-control-allow-methods: post, get, options access-control-allow-methods: * specifications specification status comment
fetchthe definition of 'access-control-allow-methods' in that specification.
Access-Control-Allow-Origin - HTTP
access-control-allow-origin: https://developer.mozilla.org vary: origin specifications specification status comment
fetchthe definition of 'access-control-allow-origin' in that specification.
Access-Control-Expose-Headers - HTTP
l-expose-headers: content-length, x-kuma-revision in requests without credentials, you can also use a wildcard value: access-control-expose-headers: * however, this won't wildcard the authorization header, so if you need to expose that, you will need to list it explicitly: access-control-expose-headers: *, authorization specifications specification status comment
fetchthe definition of 'access-control-expose-headers' in that specification.
Access-Control-Max-Age - HTTP
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.
Access-Control-Request-Headers - HTTP
examples access-control-request-headers: x-pingother, content-type specifications specification status comment
fetchthe definition of 'access-control-request-headers' in that specification.
Access-Control-Request-Method - HTTP
examples access-control-request-method: post specifications specification status comment
fetchthe definition of 'access-control-request-method' in that specification.
Age - HTTP
if it is age: 0, it was probably just
fetched from the origin server; otherwise it is usually calculated as a difference between the proxy's current date and the date general header included in the http response.
CSP: frame-src - HTTP
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).
CSP: plugin-types - HTTP
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: worker-src - HTTP
csp version 3 directive type
fetch directive fallback if this directive is absent, the user agent will first look for the child-src directive, then the script-src directive, then finally for the default-src directive, when governing worker execution.
Cross-Origin-Embedder-Policy - HTTP
allows the document to
fetch cross-origin resources without giving explicit permission through the cors protocol or the cross-origin-resource-policy header.
Date - HTTP
note that date is listed in the forbidden header names in the
fetch spec - so this code will not send date header:
fetch('https://httpbin.org/get', { 'headers': { 'date': (new date()).toutcstring() } }) header type general header forbidden header name yes syntax date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive).
If-Match - HTTP
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.
Location - HTTP
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).
Warning - HTTP
note: the warning header is soon to be deprecated; see warning (https://github.com/httpwg/http-core/issues/139) and warning: header & stale-while-revalidate (https://github.com/whatwg/
fetch/issues/913) for more details.
X-Content-Type-Options - HTTP
e type is not a javascript mime type enables cross-origin read blocking (corb) protection for the mime-types: text/html text/plain text/json, application/json or any other type with a json extension: */*+json text/xml, application/xml or any other type with an xml extension: */*+xml (excluding image/svg+xml) specifications specification status comment
fetchthe definition of 'x-content-type-options definition' in that specification.
Network Error Logging - HTTP
this experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network
fetches from supporting browsers.
200 OK - HTTP
the meaning of a success depends on the http request method: get: the resource has been
fetched and is transmitted in the message body.
Date - JavaScript
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.
Promise.prototype.finally() - JavaScript
examples using finally let isloading = true;
fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.
WebAssembly.Global() constructor - JavaScript
got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:true}, 0); webassembly.instantiatestreaming(
fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running ...
WebAssembly.Global - JavaScript
got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:true}, 0); webassembly.instantiatestreaming(
fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running ...
WebAssembly.Module() constructor - JavaScript
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.
WebAssembly.Module.customSections() - JavaScript
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
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.
WebAssembly.Module.imports() - JavaScript
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.
WebAssembly.Module - JavaScript
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.
WebAssembly.Table() constructor - JavaScript
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.
WebAssembly.Table.prototype.get() - JavaScript
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.
WebAssembly.Table.prototype.set() - JavaScript
{ js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, and invoke the two referenced functions that are now stored in the table (the table2.wasm module (see text representation) adds two function references to the table, both of which print out a simple value): 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.
WebAssembly.Table - JavaScript
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.
WebAssembly.compile() - JavaScript
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().
Optional chaining (?.) - JavaScript
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.
JavaScript
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.
Web app manifests
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.
Optimizing startup performance - Web Performance
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.
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) { ...
Structural overview of progressive web apps - Progressive web apps (PWAs)
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); }) ); }); 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) {...
textLength - SVG: Scalable Vector Graphics
llo"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.addeventlistener("input", function(event) { textelement.textlength.baseval.newvaluespecifiedunits( svglength.svg_lengthtype_px, widthslider.valueasnumber); widthdisplay.innertext = widthslider.value; }, false); widthslider.dispatchevent(new event("input")); after
fetching the element references, an eventlistener is established by calling addeventlistener() on the slider control, to receive any input events which occur.
<feImage> - SVG: Scalable Vector Graphics
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.
SVG documentation index - SVG: Scalable Vector Graphics
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.
Texts - SVG: Scalable Vector Graphics
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.
Exported WebAssembly functions - WebAssembly
an example let's look at an example to clear things up (you can find this on github as table-set.html; see it running live also, and check out the wasm text representation): var othertable = new webassembly.table({ element: "anyfunc", initial: 2 }); webassembly.instantiatestreaming(
fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table (othertable) from javascript using the webassembly.table constructor, then we load table.wasm i...
Compiling an Existing C Module to WebAssembly - WebAssembly
luckily, the canvas api has canvasrenderingcontext2d.getimagedata — that gives you an uint8clampedarray containing the image data in rgba: async function loadimage(src) { // load image const imgblob = await
fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); return ctx.getimagedata(0, 0, img.width, img.height); } now it's "only" a ma...
WebAssembly
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.