Search completed in 1.18 seconds.
628 results for "async":
Your results are loading. Please wait...
Making asynchronous programming easier with async and await - Learn web development
previous overview: asynchronous next more recent additions to the javascript language are async functions and the await keyword, part of the so-called ecmascript 2017 javascript edition (see ecmascript next support in mozilla). these features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards. they make async code look more like old-school synchronous code, so they're well worth learning. this article gives you what you need to know. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises. objective: to understand promises and how to use them. ...
...rds. they make async code look more like old-school synchronous code, so they're well worth learning. this article gives you what you need to know. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises. objective: to understand promises and how to use them. the basics of async/await there are two parts to using async/await in your code. the async keyword first of all we have the async keyword, which you put in front of a function declaration to turn it into an async function. an async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code. try typing the following lines into your browser's js cons...
...t of a function declaration to turn it into an async function. an async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code. try typing the following lines into your browser's js console: function hello() { return "hello" }; hello(); the function returns "hello" — nothing special, right? but what if we turn this into an async function? ...
...And 43 more matches
Introducing asynchronous JavaScript - Learn web development
this section recaps some of the information we saw in the previous article. ...
...this section recaps some of the information we saw in the previous article. ...
...nous next in this article we briefly recap the problems associated with synchronous javascript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can help us solve such problems. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to gain familiarity with what asynchronous javascript is, how it differs from synchronous javascript, and what use cases it has. synchronous javascript to allow us to understand what asynchronous javascript is, we ought to start off by making sure we understand what synchronous javascript is. this section recaps some of the information we saw in the previous article. a lot of the functionality we have looked at in previous...
...And 25 more matches
async function - JavaScript
param the name of an argument to be passed to the function. ...
... param the name of an argument to be passed to the function. ...
... param the name of an argument to be passed to the function. ...
...And 21 more matches
General asynchronous programming concepts - Learn web development
overview: asynchronous next in this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript. asynchronous? normally, a given program's code runs straight along, with only one thing happening at once. if a function relies on the result of another function, it has to wait for the other function to finish and return, and until that happens, the en...
... this is a frustrating experience and isn't a good use of computer processing power — especially in an era in which computers have multiple processor cores available. there's no sense sitting there waiting for something when you could let the other task chug along on another processor core and let you know when it's done. this lets you get other work done in the meantime, which is the basis of asynchronous programming. it is up to the programming environment you are using (web browsers, in the case of web development) to provide you with apis that allow you to run such tasks asynchronously. blocking code asynchronous techniques are very useful, particularly in web programming. when a web app runs in a browser and it executes an intensive chunk of code without returning control to the brows...
...in mind, have a look at simple-sync-worker.html (see it running live), again with your browser's javascript console open. this is a rewrite of our previous example that calculates the 10 million dates in a separate worker thread. now when you click the button, the browser is able to display the paragraph before the dates have finished calculating. the first operation no longer blocks the second. asynchronous code web workers are pretty useful, but they do have their limitations. a major one is they are not able to access the dom — you can't get a worker to directly do anything to update the ui. we couldn't render our 1 million blue circles inside our worker; it can basically just do the number crunching. the second problem is that although code run in a worker is not blocking, it is still ...
...And 12 more matches
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. ...
... the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. ...
...this is likely to happen when i/o is involved or a potentially expensive process wants to break itself up into small...
...And 11 more matches
Graceful asynchronous programming with Promises - Learn web development
this article shows you how promises work, how you'll see them in use with web apis, and how to write your own. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand promises and how to use them. what are promises? we looked at promises briefly in the first article of the course, but here we'll look at them in a lot more depth. ...
...me point in the future. there is no guarantee of exactly when the operation will complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case. generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is. and of course, it's nice that it doesn't block the rest of the code execution. one of the most common engagements you'll have with promises is with web apis that return a promise. let's consider a hypothetical video chat applica...
...ecallback); }, failurecallback); }, failurecallback); this is messy and hard to read (often referred to as "callback hell"), requires the failurecallback() to be called multiple times (once for each nested function), with other issues besides. improvements with promises promises make situations like the above much easier to write, parse, and run. ...
...And 8 more matches
Symbol.asyncIterator - JavaScript
the symbol.asynciterator well-known symbol specifies the default asynciterator for an object. if this property is set on an object, it is an async iterable and can be used in a for await...of loop. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the symbol.asynciterator symbol is a builtin symbol that is used to access an object's @@asynciterator method. in order for an object to be async iterable, it must have a symbol.asynciterator key. ...
...d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description the symbol.asynciterator symbol is a builtin symbol that is used to access an object's @@asynciterator method. in order for an object to be async iterable, it must have a symbol.asynciterator key. ...
...symbol.asynciterator symbol is a builtin symbol that is used to access an object's @@asynciterator method. in order for an object to be async iterable, it must have a symbol.asynciterator key. property attributes of symbol.asynciterator writable no enumerable no configurable no examples user-defined async iterables you can define your own async iterable by setting the [symbol.asynciterator] property on an object. ...
...And 7 more matches
AsyncFunction - JavaScript
the asyncfunction constructor creates a new async function object. in javascript, every asynchronous function is actually an asyncfunction object. note that asyncfunction is not a global object. it can be obtained with the following code: object.getprototypeof(async function(){}).constructor syntax new asyncfunction([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ... argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. ...
...g2[, ...argn]],] functionbody) parameters arg1, arg2, ... argn names to be used by the function as formal argument names. each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. description async function objects created with the asyncfunction constructor are parsed when the function is created. this is less efficient than declaring an async function with an async function expression and calling it within your code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the functio...
... parsed when the function is created. this is less efficient than declaring an async function with an async function expression and calling it within your code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. note: async functions created with the asyncfunction constructor do not create closures to their creation contexts; they are always created in the global scope. ...
...And 6 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
previous overview: asynchronous next this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. ...
...at they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop. these functions are: settimeout() execute a specified block of code once after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationframe() the mo...
...nce after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationframe() the modern version of setinterval(). executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the environment it is being run in. ...
...And 5 more matches
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. looking to become a front-end web developer? ...
... 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. looking to become a front-end web developer? ...
...ng to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this. if you are not familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module. if you are, then you can probably skip to the introducing asynchronous javascript module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding pr...
...And 5 more matches
Synchronous and asynchronous requests - Web APIs
xmlhttprequest supports both synchronous and asynchronous communications. in general, however, asynchronous requests should be preferred to synchronous requests for performance reasons. synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience. asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received. this lets the browser continue to work as normal while your request is being handled. example: send a file to the console log this is the simplest usage of asynchronous xmlhttprequest. var xhr = new xmlhttprequest(); xhr.open("get", "/bar/foo.txt", true); xhr.onload = function (e) { if (xhr.readystate === 4) { if (xhr.status === 200) { console.log...
... line 3 creates an event handler function object and assigns it to the request's onload attribute. this handler looks at the request's readystate to see if the transaction is complete in line 4; if it is, and the http status is 200, the handler dumps the received content. if an error occurred, an error message is displayed. line 15 actually initiates the request. the callback routine i...
...e http status is 200, the handler dumps the received content. if an error occurred, an error message is displayed. line 15 actually initiates the request. the callback routine is called whenever the state of the request changes. example: writing a function to read an external file in some cases, you must read many external files. this is a standard function which uses the xmlhttprequest object asynchronously in order to switch the content of the read file to a specified listener. function xhrsuccess() { this.callback.apply(this, this.arguments); } function xhrerror() { console.error(this.statustext); } function loadfile(url, callback /*, opt_arg1, opt_arg2, ... */) { var xhr = new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arg...
...And 4 more matches
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
the term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete). in computing, the word "asynchronous" is used in two major contexts. networking and communications asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation. ...
...ges between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt. additionally, messages may be sent without waiting for acknowledgement, with the understanding that if a problem occurs, the recipient will request corrections or otherwise handle the situation. ...
...ns or otherwise handle the situation. for humans, e-mail is an asynchronous communication method; the sender sends an email and the recipient will read and reply to the message when it's convenient to do so, rather than doing so at once. and both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. when software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. ...
...And 3 more matches
nsIAsyncInputStream
xpcom/io/nsiasyncinputstream.idlscriptable please add a summary to this article. inherits from: nsiinputstream last changed in gecko 1.7 if an input stream is non-blocking, it may return ns_base_stream_would_block when read. the caller must then wait for the stream to have some data to read. if the stream implements nsiasyncinputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait() method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsiinputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream. ...
...is interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait() method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsiinputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream. ...
...e. nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream. method overview void asyncwait(in nsiinputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult astatus); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the oninputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream). methods asyncwait() asynchronously wait for the stream to be readable or closed. the notification is one-shot, meaning that...
...And 3 more matches
nsIAsyncOutputStream
xpcom/io/nsiasyncoutputstream.idlscriptable please add a summary to this article. inherits from: nsioutputstream last changed in gecko 1.7 if an output stream is non-blocking, it may return ns_base_stream_would_block when written to. the caller must then wait for the stream to become writable. if the stream implements nsiasyncoutputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait() method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsioutputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. ...
...interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait() method). while this interface is almost exclusively used with non-blocking streams, it is not necessary that nsioutputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. ...
... nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. method overview void asyncwait(in nsioutputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream). methods asyncwait() asynchronously wait for the stream to be writable or closed. the notification is one-shot, meaning tha...
...And 3 more matches
Async scripts for asm.js - Game development
every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
...ximum flexibility to optimize the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
...ze the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascript.options.parallel_parsing in about:config. putting async into action getting async compilation is easy: when writing your javascript, just use the async attribute like so: <script async src="file.js"></script> or, to do the same thing via script: var script = document.createelement('script'); script.src = "file.js"; document.body.appendchild(script); (scripts created from script default to async.) the default html shell emscripten generates produces the latter. when is asy...
...And 2 more matches
AsyncShutdown.jsm
firefox shutdown is composed of phases that take place sequentially. typically, each shutdown phase removes some capabilities from the application. for instance, at the end of phase profilebeforechange, no service is permitted to write to the profile directory (with the exception of telemetry). consequently, if any service has requested i/o to the profile directory before or during phase profilebeforechange, the system must be informed that these requests need to be completed before the end of phase profilebeforechange. failing to inform the system of this requirement can (and has been known to) cause data loss. ...
... before the end of phase profilebeforechange. failing to inform the system of this requirement can (and has been known to) cause data loss. example at some point during shutdown, the add-on manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data. since the data is saved to the profile, this must be completed during phase profilebeforechange. asyncshutdown.profilebeforechange.addblocker( "add-on manager: shutting down", function condition() { let promise = ... // do whatever must be done before the end of phase profilebeforechange return promise; }, function info() { let status = ... // collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this exampl...
...from restarting firefox or burning through a battery. in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by calls to info(). instances of phase note that you cannot create an instance of phase yourself. see attributes for the instances of phase. if you need a new phase added to asyncshutdown, please file a bug. methods overview void addblocker(string name, function|promise condition, optional function info) boolean removeblocker(function|promise condition) methods addblocker () register a blocker for the completion of a phase. void addblocker( in string name, in function|promise|* condition, optional in function info ) arguments name ...
...And 2 more matches
mozIAsyncHistory
toolkit/components/places/moziasynchistory.idlscriptable this interface allows you to add multiple visits to a single url in a batch. ...
... toolkit/components/places/moziasynchistory.idlscriptable this interface allows you to add multiple visits to a single url in a batch. ...
...u to add multiple visits to a single url in a batch. ...
...And 2 more matches
nsIAsyncVerifyRedirectCallback
the result of the redirect decision is passed through this callback. ...
...the result of the redirect decision is passed through this callback. ...
...the result of the redirect decision is passed through this callback. ...
...And 2 more matches
NPN_PluginThreadAsyncCall - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary thread safe way to request that the browser calls a plug-in function on the browser or plugin thread (the thread on which the plug-in was initiated). syntax #include <npapi.h> void npn_pluginthreadasynccall(npp plugin, void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance. ...
... void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance. func pointer to the function to call on the correct thread. userdata pointer to the data to pass to the function func once called. returns nothing. description causes asynchronous execution of the specified function pointer on the "plug-in thread", passing in the specified user data pointer when it is called. the "plug-in thread" is the thread hosting the plug-in, which may be either the browser's main thread or the plug-in process if the plug-in is being executed out-of-process. it is the application's responsibility to perform any synchronization between the threa...
...pecified function pointer on the "plug-in thread", passing in the specified user data pointer when it is called. the "plug-in thread" is the thread hosting the plug-in, which may be either the browser's main thread or the plug-in process if the plug-in is being executed out-of-process. it is the application's responsibility to perform any synchronization between the thread calling npn_pluginthreadasynccall() and the thread on which the call is eventually executed. in particular, the user must ensure that the function pointer remains callable and the user data is not deallocated until the browser executes the call. there are inherent race conditions between calling this function and termination of the plug-in instance. the browser might not execute calls successfully registered with this api cal...
...tes the call. there are inherent race conditions between calling this function and termination of the plug-in instance. the browser might not execute calls successfully registered with this api call during plug-in termination. plug-ins should perform appropriate synchronization with the code in their npp_destroy() routine to ensure correct execution and avoid memory leaks. calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately. after control returns to the browser, it is free to call the function with its argument from this thread. see also npp out-of-process plugins ...
async function expression - JavaScript
the async function keyword can be used to define async functions inside expressions. you can also define async functions using an async function statement. syntax async function [name]([param1[, param2[, ..., paramn]]]) { statements } as of es2015, you can also use arrow functions. parameters name the function name. can be omitted, in which case the function is anonymous. the name is only local to the function body. paramn the name of an argument to be passed to the function. statements the statements which comprise the body of the function. description an async function expression is very similar to, and has almost the same syntax as, an async function statement. ...
... name. can be omitted, in which case the function is anonymous. the name is only local to the function body. paramn the name of an argument to be passed to the function. statements the statements which comprise the body of the function. description an async function expression is very similar to, and has almost the same syntax as, an async function statement. the main difference between an async function expression and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions. an async function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined. see also the chapter about functions for more information. examples simple example function resolveafter2seco...
...ions to create anonymous functions. an async function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined. see also the chapter about functions for more information. examples simple example function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds. ...
...ction resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds. }); (async function(x) { // async function expression used as an iife let p_a = resolveafter2seconds(20); let p_b = resolveafter2seconds(30); return x + await p_a + await p_b; })(10).then(v => { console.log(v); // prints 60 after 2 seconds. }); specifications specification ecmascript (ecma-262)the definition of 'async function' in that specification. ...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
the debug.mstraceasynccallbackstarting function associates the callback stack with a previously specified asynchronous operation. syntax debug.mstraceasynccallbackstarting(asyncoperationid) parameters asyncoperationid the id associated with the asynchronous operation. remarks call this function in the callback function for the asynchronous operation after the call to debug.mstraceasyncoperationcompleted. note: some debugging tools do not display the information sent to the debugger. asyncoperationid must correspond to the operation name previously returned from debug.mstraceasyncoperationstarting. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. ...
...asynchronous operation after the call to debug.mstraceasyncoperationcompleted. note: some debugging tools do not display the information sent to the debugger. asyncoperationid must correspond to the operation name previously returned from debug.mstraceasyncoperationstarting. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. ...
...ndows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. }, function (error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode. also supported in store apps (windows 8.1 and windows phone 8.1). ...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
the debug.mstraceasynccallbackcompleted function indicates that an asynchronous operation has completed. syntax debug.mstraceasynccallbackcompleted() parameters asyncoperationid the id associated with the asynchronous operation. status optional the status of the asynchronous operation. if not specified, debug.ms_async_op_status_success is used. remarks call this function when the asynchronous operation completes. asyncoperationid must correspond to the operation id previously returned from debug.mstraceasyncoperationstarting. the possible values for status include: debug.ms_async_op_status_success debug.ms_async_op_status_canceled debug.ms_async_op_status_error note: some debugging tools do not display the information sent to the debugger. example...
... correspond to the operation id previously returned from debug.mstraceasyncoperationstarting. the possible values for status include: debug.ms_async_op_status_success debug.ms_async_op_status_canceled debug.ms_async_op_status_error note: some debugging tools do not display the information sent to the debugger. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. }, function (error) { ...
...ndows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation. }, function (error) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_error); debug.mstraceasynccallbackstarting(opid); }); debug.mstraceasynccallbackcompleted(); } function dosomethingasync() { return winjs.promise.as(true); } asyncwrapperfunction(); requirements supported in the internet explorer 11 standards document mode. also supported in store apps (windows 8.1 and windows phone 8.1). ...
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
the debug.msupdateasynccallbackrelation function updates the relationship status between a synchronous work item and the associated asynchronous operation. syntax debug.msupdateasynccallbackrelation(relatedasyncoperationid, relationtype) parameters relatedasyncoperationid the id associated with the asynchronous operation. relationtype optional the value that specifies the relationship status. remarks the synchronous work item is typically the callback function for the asynchronous operation. this function may be called when an asynchronous operation is aborted, when a join operation is used, or in other scenarios. ...
... note: some debugging tools do not display the information sent to the debugger by this function. ...
...onal the value that specifies the relationship status. remarks the synchronous work item is typically the callback function for the asynchronous operation. this function may be called when an asynchronous operation is aborted, when a join operation is used, or in other scenarios. the possible values for relationtype include: debug.ms_async_callback_status_assign_delegate debug.ms_async_callback_status_join debug.ms_async_callback_status_chooseany debug.ms_async_callback_status_cancel debug.ms_async_callback_status_error for more information, see debug constants. note: some debugging tools do not display the information sent to the debugger by this function. requirements supported in the internet explorer 11 standards document mode. also supported in...
mozbrowserasyncscroll
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserasyncscroll event is fired when the content of a browser <iframe> is scrolled. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether the event normally bubbles or not. canc...
...t in css pixels of the document within the browser <iframe>. note: top + height may be larger than scrollheight. this indicates that the content is over-scrolled, which occurs when the page "rubber-bands" after being scrolled all the way to the bottom. similarly, left + width may be greater than scrollwidth, and both left and top may be negative. ...
...ly, left + width may be greater than scrollwidth, and both left and top may be negative. note: for performance reasons, this event is asynchronous. that means that the value retrieved through the event object can be different than the real current position of the scroll when the event is processed. ...
mozIAsyncFavicons
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) nsifaviconservice handles this interface, so you do not need to directly create a new service. simply queryinterface() the nsifaviconservice to this interface. as an alternative, you can just use placesutils.favicons from javascript. ...
... is not null, the other parameters may contain the favicon data. however, if no favicon data is currently associated with the favicon uri, adatalen will be 0, adata will be an empty array, and amimetype will be an empty string. setandfetchfaviconforpage() declares that a given page uses a favicon with the given uri and attempts to fetch and save the icon data by loading the favicon uri through a asynchronous network request. if the icon data already exists, we will not try to reload the icon unless aforcereload is true. similarly, if the icon is in the failed favicon cache we will not do anything unless aforcereload is true, in which case we'll try to reload the favicon. this function will only save favicons for "good" uris, as defined by what gets added to history or is a bookmark. for "bad" ...
nsIAsyncStreamCopier
netwerk/base/public/nsiasyncstreamcopier.idlscriptable this interface is used to copy the contents of one stream to another. inherits from: nsirequest last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void asynccopy(in nsirequestobserver aobserver, in nsisupports aobservercontext); void init(in nsiinputstream asource, in nsioutputstream asink, in nsieventtarget atarget, in boolean asourcebuffered, in boolean asinkbuffered, in unsigned long achunksize, in boolean aclosesource, in boolean aclosesink); methods asynccopy() starts the copy operation. the specified observer is notified when the copy completes. ...
...requestobserver aobserver, in nsisupports aobservercontext); void init(in nsiinputstream asource, in nsioutputstream asink, in nsieventtarget atarget, in boolean asourcebuffered, in boolean asinkbuffered, in unsigned long achunksize, in boolean aclosesource, in boolean aclosesink); methods asynccopy() starts the copy operation. the specified observer is notified when the copy completes. void asynccopy( in nsirequestobserver aobserver, in nsisupports aobservercontext ); parameters aobserver receives notifications. aobservercontext the object to receive notifications with information about the progress of the copy operation. init() initializes the stream copier. note: at least one of the streams must be buffered. void init( in nsiinputstream asource, in nsioutputstream asink, in...
SourceBuffer.appendBufferAsync() - Web APIs
the appendbufferasync() method of the sourcebuffer interface begins the process of asynchronously appending media segment data from an arraybuffer or arraybufferview object to the sourcebuffer. it returns a promise which is fulfilled once the buffer has been appended. syntax appendpromise = sourcebuffer.appendbufferasync(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer. return value a promise which is fulfilled when the buffer has been added successfully to the sourcebuffer, or null if the request could not be initiated. ...
...e = sourcebuffer.appendbufferasync(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer. return value a promise which is fulfilled when the buffer has been added successfully to the sourcebuffer, or null if the request could not be initiated. example this simplified example async function, fillsourcebuffer(), takes as input parameters buffersource, buffer, and a sourcebuffer to which to append the source media from the buffer. async function fillsourcebuffer(buffer, msbuffer) { try { while(true) { await msbuffer.appendbufferasync(buffer); } } catch(e) { handleexception(e); } } specifications not currently part of any specification. this is bein...
SourceBuffer.removeAsync() - Web APIs
the removeasync() method of the sourcebuffer interface starts the process of asynchronously removing from the sourcebuffer media segments found within a specific time range. a promise is returned, which is fulfilled when the buffers in the specified time range have been removed. this method can only be called when updating is false. if that's not the case, call abort() instead. syntax removepromise = sourcebuffer.removeasync(start, end); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer. ...
...ntax removepromise = sourcebuffer.removeasync(start, end); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer. example this example establishes an asynchronous function, emptysourcebuffer(), which simply clears the contents of the specified sourcebuffer. async function emptysourcebuffer(msbuffer) { await msbuffer.removeasync(0, infinity).catch(function(e) { handleexception(e); } } specifications not currently part of the mse specification. specification status comment media source extensions recommendation ...
XMLDocument.async - Web APIs
Web › API › XMLDocument › async
document.async can be set to indicate whether a xmldocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
...r synchronous request. true is the default value, indicating that documents should be loaded asynchronously. ...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
...
Debug.msTraceAsyncOperationStarting - Archive of obsolete content
initiates a trace for an asynchronous operation. debug ...
mozIStorageAsyncStatement
an asynchronous sql statement. this differs from mozistoragestatement by only being usable for asynchronous execution. (mozistoragestatement can be used for both synchronous and asynchronous purposes.) this specialization for asynchronous operation allows us to avoid needing to acquire synchronization primitives also used by the asynchronous execution thread. in contrast, mozistoragestatement may need to acquire the primitives and consequently can cause the main thread to lock for extended intervals while the asynchronous thread performs some long-running operation. inherited interface mozistoragebasestatement ...
Index - Web APIs
Web › API › Index
ons, pause, waapi, web animations api the pause() method of the web animations api's animation interface suspends playback of the animation. 73 animation.pending api, animation, animations, property, reference, web animations, web animations api the read-only animation.pending property of the web animations api indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. 74 animation.play() api, animation, interface, method, reference, web animations, play, waapi, web animations api the play() method of the web animations api's animation interface starts or resumes playing of an animation. if the animation is finished, calling play() restarts the animation, playing i...
... batterymanager.onlevelchange api, battery api, event handler, property, reference the batterymanager.onlevelchange property specifies an event listener to receive levelchange events. these events occur when the battery level is updated. 273 beacon api guide, overview, web performance, user behavior tracker, user tracker the beacon interface is used to schedule an asynchronous and non-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). 274 using the beacon api guide, web performance the beacon interface sche...
...nd non-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). 274 using the beacon api guide, web performance the beacon interface schedules an asynchronous and non-blocking request to a web server. 275 beforeinstallpromptevent api, beforeinstallpromptevent, event, experimental, interface, reference the beforeinstallpromptevent is fired at the window.onbeforeinstallprompt handler before a user is prompted to "install" a web site to a home screen on mobile. 276 beforeinstallpromptevent.prompt() api, beforeins...
...And 41 more matches
Index
Mozilla › Tech › XPCOM › Index
erface exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you return from that handler the bottom frame, and any frame you found attached through it, are invalidated via the jsdiephemeral interface. once a jsdistackframe has been invalidated all method and property accesses will throw a ns_error_not_available exception. ...
...perty accesses will throw a ns_error_not_available exception. 193 moziasyncfavicons interfaces, interfaces:scriptable, places nsifaviconservice handles this interface, so you do not need to directly create a new service. simply queryinterface() the nsifaviconservice to this interface. as an alternative, you can just use placesutils.favicons from javascript. 194 moziasynchistory interfaces, interfaces:scriptable, places, xpcom interface reference implemented by: @mozilla.org/browser/history;1 as a service: 195 mozicoloranalyzer interfaces, interfaces:scriptable, places, reference, xpcom api reference, xpcom interface reference given an image uri, find the most representative color for that image based on the frequency of each color. ...
...rs. it allows consumers to add aggregate functions that are available to sql queries and triggers. an aggregate function is a function that returns one value from a series of values. there are a number of already defined aggregate functions provided by sqlite. objects implementing this interface can be registered with mozistorageconnection.createaggregatefunction(). 204 mozistorageasyncstatement stub an asynchronous sql statement. 205 mozistoragebindingparams interfaces, interfaces:scriptable, storage the mozistoragebindingparams interface is used to bind values to parameters prior to calling mozistoragestatement.executeasync(). 206 mozistoragebindingparamsarray interfaces, interfaces:scriptable, storage the mozistoragebindingp...
...And 24 more matches
Choosing the right approach - Learn web development
previous overview: asynchronous to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. we'll probably add to this resource as time goes on. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to be able to make a sound choice of when to use different asynchronous programming techniques. ...
...oking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. we'll probably add to this resource as time goes on. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to be able to make a sound choice of when to use different asynchronous programming techniques. asynchronous callbacks generally found in old-style apis, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback can in turn do something with the result. this is the precursor to promises; it's not as efficient or flexible. use only when necessary. useful for... single delayed oper...
...t.createelement('img'); image.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); pitfalls nested callbacks can be cumbersome and hard to read (i.e. "callback hell"). failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the errors for the entire chain. async callbacks just aren't very graceful. promise callbacks are always called in the strict order they are placed in the event queue; async callbacks aren't. async callbacks lose full control of how the function will be executed when passed to a third-party library. browser compatibility really good general support, although the exact support for callbacks in apis depends on the particular api. r...
...And 23 more matches
IPDL Tutorial
arate file. the ipdl compiler generates several c++ headers from each ipdl protocol. this generated code manages the details of the underlying communication layer (sockets and pipes), constructing and sending messages, ensuring that all actors adhere to their specifications, and handling many error conditions. the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol. two messages can be sent from the parent to the child, init() and shutdown(). one message can be sent from the child to the parent, ready(). ipdl protocols start with the letter p. the file in which the protocol is declared must have a matching...
...eady(); } void recvshutdown() { pr_unloadlibrary(mpluginlibrary); } private: prlibrary* mpluginlibrary; }; launching the subprocess and hooking these protocol actors into our ipc "transport layer" is beyond the scope of this document. see ipdl processes and threads for more details. because protocol messages are represented as c++ methods, it's easy to forget that they are in fact asynchronous messages: by default the c++ method will return immediately, before the message has been delivered. the parameters of the recv* methods (const nscstring& pluginpath in the example) are references to temporary objects, so copy them if you need to keep their data around. direction each message type includes a "direction." the message direction specifies whether the message can be sent fr...
...child was introduced above. the second is parent, which means that the messages declared under the parent label can only be sent from-child-to-parent. the third is both, which means that the declared messages can be sent in both directions. the following artificial example shows how these specifiers are used and how these specifiers change the generated abstract actor classes. ...
...And 21 more matches
Bytecode Descriptions
heck afterwards that the method returned an object. checkobjcoercible stack: val ⇒ val throw a typeerror if val is null or undefined. implements: requireobjectcoercible. but most instructions that require an object will perform this check for us, so of the dozens of calls to requireobjectcoercible in the spec, we need this instruction only for destructuring assignment and initialization. toasynciter stack: iter, next ⇒ asynciter create and push an async iterator wrapping the sync iterator iter. next should be iter's .next method. implements: createasynctosynciterator. the spec says this operation takes one argument, but that argument is a record with two relevant fields, [[iterator]] and [[nextmethod]]. used for for await loops. setprototype mutateproto stack: obj, protoval ⇒ o...
... prototype of callee in preparation for calling super(). callee must be a derived class constructor. implements: getsuperconstructor, steps 4-7. checkthisreinit stack: thisval ⇒ thisval throw a referenceerror if thisval is not magicvalue(js_uninitialized_lexical). used in derived class constructors to prohibit calling super more than once. implements: bindthisvalue, step 3. generators and async functions generator stack: ⇒ gen create and push a generator object for the current frame. this instruction must appear only in scripts for generators, async functions, and async generators. there must not already be a generator object for the current frame (that is, this instruction must execute at most once per generator or async call). initialyield operands: (uint24_t resumeindex) stack...
...r, the functionbody of the generator is not supposed to start running until the first .next() call, so after setup the script suspends itself: the "initial yield". later, when resuming execution, rval, gen and resumekind will receive the values passed in by jsop::resume. resumekind is the generatorresumekind stored as an int32 value. this instruction must appear only in scripts for generators and async generators. gen must be the generator object for the current frame. it must not have been previously suspended. the resume point indicated by resumeindex must be the next instruction in the script, which must be afteryield. implements: generatorstart, steps 4-7. format: jof_resumeindex afteryield operands: (uint32_t icindex) bytecode emitted after yield expressions. this is useful for the debu...
...And 15 more matches
core/promise - Archive of obsolete content
while this has a good reason and many advantages, it comes with a price. ...
...while this has a good reason and many advantages, it comes with a price. ...
...nd you omit the value handler, the value will propagate to bar (bar will be fulfilled with that value): var bar = foo().then(null, function failure(error) { // handle error... }); chaining there are two ways to chain promise operations. you can chain them using either inside or outside handlers. flat chaining you can use then for chaining intermediate operations on promises (var data = readasync().then(parse).then(extract)). you can chain multiple then functions, because then returns a promise resolved to a return value of an operation and errors propagate through the promise chains. in general good rule of thumb is to prefer then based flat chaining. it makes code easier to read and make changes later: var data = readasync(url). // read content of url asynchronously then(parse). ...
...And 14 more matches
mozIStorageConnection
is the primary interface for interacting with a database, including creating prepared statements, executing sql, and examining database errors. 1.0 68 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for a general overview on how to use this interface, see storage. ...
...back acallback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); void close(); void committransaction(); void createaggregatefunction(in autf8string afunctionname, in long anumarguments, in mozistorageaggregatefunction afunction); mozistorageasyncstatement createasyncstatement(in autf8string asqlstatement); void createfunction(in autf8string afunctionname, in long anumarguments, in mozistoragefunction afunction); mozistoragestatement createstatement(in autf8string asqlstatement); void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anum...
...the connection is open and ready to use. this will be false if the connection failed to open, or it has been closed. read only. databasefile nsifile the current database nsifile. null if the database connection refers to an in-memory database. read only. lasterror long the last sqlite error code that occurred. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. lasterrorstring autf8string the english error string reported by the sqlite library for the last sqlite operation. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. lastinsertrowid long long the row ...
...And 13 more matches
for await...of - JavaScript
syntax for await (variable of iterable) { statement } variable on each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. ...
... syntax for await (variable of iterable) { statement } variable on each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. ...
...terating over async iterable objects as well as on sync iterables, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined async/sync iterables. it invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object. like the await operator, the statement can only be used inside an async function. for await...of doesn't work with async iterators that are not async iterables. syntax for await (variable of iterable) { statement } variable on each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. iterable object whose iterable properties are to be iterated over. ...
...And 13 more matches
Using Promises - JavaScript
« previousnext » a promise is an object representing the eventual completion or failure of an asynchronous operation. since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them. essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs. ...
...tially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs. ...
...a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs. ...
...And 12 more matches
Necko walkthrough
r the uri (ns_newchannel) if "http:", it will be an nsihttpchannel nsdocshell::dochannelload nsuriloader::openuri passes an nsistreamlistener pointer, 'loader' to nsuriloader::openchannel - it creates an nsdocumentopeninfo object, which implements nsistreamlistener, i.e. has onstartrequest, onstoprequest, ondataavailable, the three functions in which channel responses are received asynchronously. nshttpchannel::asyncopen called from openuri; openchannel isn't named the best, since the opening happens in the context of openuri, its calling function. this is where it hits necko code. but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response callback...) chan...
...usly. nshttpchannel::asyncopen called from openuri; openchannel isn't named the best, since the opening happens in the context of openuri, its calling function. this is where it hits necko code. but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response callback...) channel->asyncopen. receive response get a callback to each of these: nsistreamlistener::onstartrequest (header info) nsistreamlistener::ondataavailable (data in single or multiple chunks) nsistreamlistener::onstoprequest (no more data from http) this all happens on the main thread, in a non-blocking fashion: make your request on the main thread, then carry on and ...
... receive response get a callback to each of these: nsistreamlistener::onstartrequest (header info) nsistreamlistener::ondataavailable (data in single or multiple chunks) nsistreamlistener::onstoprequest (no more data from http) this all happens on the main thread, in a non-blocking fashion: make your request on the main thread, then carry on and get the async response later, also on the main thread. there is an option to receive ondataavailable specifically on a non-main thread, but all other calls happen on the main thread. 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 d...
...And 9 more matches
Index - Learn web development
, l10n:priority javascript is a programming language that allows you to implement complex things on web pages. every time a web page does more than just sit there and display static information for you to look at—displaying timely content updates, interactive maps, animated 2d/3d graphics, scrolling video jukeboxes, or more—you can bet that javascript is probably involved. 49 asynchronous javascript beginner, codingscripting, guide, javascript, landing, promises, async, asynchronous, await, callbacks, requestanimationframe, setinterval, settimeout in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. 50 choosing t...
...we'll probably add to this resource as time goes on. ...
...we'll probably add to this resource as time goes on. ...
...And 8 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. connecting to a remote peer the start() function shown here can be called by either of the two end-points that want to talk to one another. it doesn't matter who does it first; the negotiation will just work. async function start() { try { const stream = await navigator.mediadevices.getusermedia(constraints); for (const track of stream.gettracks()) { pc.addtrack(track, stream); } selfvideo.srcobject = stream; } catch(err) { console.error(err); } } this isn't appreciably different from older webrtc connection establishment code. the user's camera and microphone are obtained...
...t negotiation logic now we get into the true perfect negotiation logic, which functions entirely independently from the rest of the application. handling the negotiationneeded event first, we implement the rtcpeerconnection event handler onnegotiationneeded to get a local description and send it using the signaling channel to the remote peer. let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer = true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.error(err); } finally { makingoffer = false; } }; note that setlocaldescription() without arguments automatically creates and sets the appropriate description based on the current signalingstate. the set description is either a...
...f there's no negotiation underway. here, it will be always be an offer, because the negotiationneeded event is only fired in stable state. we set a boolean variable, makingoffer to true to mark that we're preparing an offer. to avoid races, we'll use this value later instead of the signaling state to determine whether or not an offer is being processed because the value of signalingstate changes asynchronously, introducing a glare opportunity. once the offer has been created, set and sent (or an error occurs), makingoffer gets set back to false. handling incoming ice candidates next, we need to handle the rtcpeerconnection event icecandidate, which is how the local ice layer passes candidates to us for delivery to the remote peer over the signaling channel. pc.onicecandidate = ({candidate}...
...And 8 more matches
Promise - JavaScript
the promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. to learn about the way promises work and how you can use them, we advise you to read using promises first. description a promise is a proxy for a value not necessarily known when the promise is created. it allows you to associate handlers with an asynchronous action's eventual success value or failure reason. this lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successful...
...ing that the operation failed. a pending promise can either be fulfilled with a value, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's then method are called. if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. as the promise.prototype.then() and promise.prototype.catch() methods return promises, they can be chained. not to be confused with: several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. scheme. promises in javascript represent processes that are already happe...
...f promisea into a "settled" state will cause both instances of .then() to be invoked. const promisea = new promise(myexecutorfunc); const promiseb = promisea.then(handlefulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an already "settled" promise. in that case the action (if appropriate) will be performed at the first asynchronous opportunity. note that promises are guaranteed to be asynchronous. therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. the effect is much like that of settimeout(action,10). const promisea = new promise( (resolutionfunc,rejectionfunc) => { resolutionfunc(777); }); // at this point, "promisea" is already settled...
...And 8 more matches
Index - Archive of obsolete content
f sdk modules which use content scripts to interact with web content. 78 core/heritage helper functions for inheritance. 79 core/namespace provides an api for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public api. 80 core/promise implementation of promises to make asynchronous programming easier. 81 dev/panel enables you to extend the firefox developer tools. 82 event/core the event/core module allows the creation of apis to broadcast and subscribe to events. 83 event/target create objects that broadcast events. 84 frame/hidden-frame creates firefox frames (i.e. xul <iframe> ...
...ed by the search plugin to fetch live search suggestions. 302 tabbed browser add-ons, code snippets, extensions here you should find a set of useful code snippets to help you work with firefox's tabbed browser. the comments normally mark where you should be inserting your own code. 303 techniques . 304 promises add-ons, examples, snippets, async no summary! 305 updating addons broken by private browsing changes add-ons, reference after reading this document, contact josh matthews with further questions or clarifications, or file a bug if your extension has stopped working due to a change described here and you are having trouble updating it. 306 using dependent libraries in extension components a...
...e, non-standard, obsolete, operator, reference the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one. however, it has been removed from the standard and the firefox implementation. do not use it! 2005 array.observe() array, javascript, method, obsolete the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects. it provided a stream of changes in order of occurrence. it's equivalent to object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. 2006 array.unobserve() a...
...And 7 more matches
HTTP Cache
one of the *storage methods on nsicachestorageservice. represents a distinct storage area (or scope) to put and get cache entries mapped by urls into and from it. similarity with the old cache: this interface may be with some limitations considered as a mirror to nsicachesession, but less generic and not inclining to abuse. unimplemented or underimplemented functionality: asyncevictstorage (bug 977766), asyncvisitstorage (bug 916052) nsicacheentryopencallback //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentryopencallback.idl the result of nsicachestorage.asyncopenuri is always and only sent to callbacks on this interface. these callbacks are ensured to be invoked when asyncopenuri returns ns_ok. important difference...
... the result of nsicachestorage.asyncopenuri is always and only sent to callbacks on this interface. these callbacks are ensured to be invoked when asyncopenuri returns ns_ok. important difference in behavior from the old cache: when the cache entry object is already present in memory or open as “force-new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e. immediately); there is currently no way to opt out of this feature (watch bug 938186). nsicacheentry //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentry.idl obtained asynchronously or pseudo-asynchronously by a call to nsicachestorage.asyncopenuri. provides access to a cached entry data and meta data for reading or writing o...
...sents an app id the scope belongs to, otherwise there is no app (app id is considered 0) p - when present the scope is of a private browsing load, this never persists cachestorageservice keeps a global hashtable mapped by the scope key. elements in this global hashtable are hashtables of cache entries. the cache entries are mapped by concantation of enhance id and uri passed to nsicachestorage.asyncopenuri. so that when an entry is beeing looked up, first the global hashtable is searched using the scope key. an entries hashtable is found. then this entries hashtable is searched using <enhance-id:><uri> string. the elemets in this hashtable are cacheentry classes, see below. the hash tables keep a strong reference to cacheentry objects. the only way to remove cacheentry objects from memory ...
...And 7 more matches
AddonManager
the callbacks will be called just once but that may be before or after the method returns. one of the forces of the addonmanager is that it deals with any kind (type) of add-on in a generic manner. to do so many methods of the addonmanager take the add-on types as parameters. ...
... maps type id to addontype. autoupdatedefault boolean whether add-ons should auto-update by default (overrideable per add-on). corresponds to the extensions.autoupdatedefault preference. ...
...llback() a callback that is passed a single addoninstall void installcallback( in addoninstall install ) parameters install the addoninstall passed back from the asynchronous request installlistcallback() a callback that is passed an array of addoninstalls void installlistcallback( in addoninstall installs[] ) parameters installs the array of addoninstalls passed back from the asynchronous request addoncallback() a callback that is passed a single addon void addoncallback( in addon addon ) parameters addon the addon passed back from the asynchronous request. if an error occurred (such as an add-on not being found), null is passed back instead. addonlistcallback() a callback that is passed an array of addons void addonlistcallback( in addon addons[] ) parame...
...And 7 more matches
nsIFaviconService
e is up to the caching system. this cache will also be written to if you use setandloadfaviconforpage() method and it encounters an error while fetching an icon. void addfailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can be null. expireallfavicons() expires all known favicons, removing them from the database. ...
... this method retrieves the given favicon data. throws an exception if we don't have data. if there is no data but we have an entry for this favicon, adatalen will be "0" and adata will be null. ...
... this method retrieves the given favicon data. throws an exception if we don't have data. if there is no data but we have an entry for this favicon, adatalen will be "0" and adata will be null. ...
...And 7 more matches
Introduction to the File and Directory Entries API - Web APIs
describes restrictions that raise security errors if you ignore them. to learn more about terminology used in this api, see the definitions section. for the reference documentation on the file and directory entries api, see the reference landing page and its subpages. the specification is still being defined and is subject to change. overview the file and directory entries api includes both asynchronous and synchronous versions of the interfaces. the asynchronous api can be used in cases where you don't want an outstanding operation to block the ui. the synchronous api, on the other hand, allows for simpler programming model, but it must be used with webworkers. usefulness of the api the file and directory entries api is an important api for the following reasons: it lets apps have ...
... locally. the client caches attachments for later upload. ...
...load. big concepts before you start using the file and directory entries api, you need to understand a few concepts: the file and directory entries api is a virtual representation of a file system the file and directory entries api can use different storage types browsers impose storage quota the file and directory entries api has asynchronous and synchronous versions when using the asynchronous api, always use the error callbacks the file and directory entries api interacts with other apis the file and directory entries api is case-sensitive the file and directory entries api is a virtual representation of a file system the api doesn't give you access to the local file system, nor is the sandbox really a section of the file system. instead, it is a virtualized file system th...
...And 7 more matches
Optimizing startup performance - Web Performance
gestions to help you achieve that goal, both when writing a new app and when porting an app from another platform to the web. starting up nicely regardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single event handler on the app's main thread. instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken...
...oes as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up. this will prevent the app, browser, and/or device from appearing to have locked up. why is it important to be asynchronous? other than the reasons suggested above, consider the impact of a non-responsive page or user interface. the user is unable to cancel if they launched your app by mistake. if the app is being run in a browser, it's possible the user may get an "unresponsive app" or "slow script" notification. you should present some kind of interface, such as a progress bar, so that the user knows how much...
...e the user may get an "unresponsive app" or "slow script" notification. you should present some kind of interface, such as a progress bar, so that the user knows how much longer they'll need to wait while your app starts up. where there's a will... if you're starting your project from scratch, it's usually pretty easy to just write everything the "right way," making appropriate bits of the code asynchronous. all pure startup calculations should be performed in background threads, while you keep the run-time of main thread events as short as possible. include a progress indicator so the user knows what's going on and how long they'll be waiting. in theory, anyway, it should be pretty easy to design your new app to start up nicely. on the other hand, however, it can get tricky when you're port...
...And 7 more matches
Message manager overview
me message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it. ...
...hat particular window. if you send a message using the window message manager, it gets sent to all content tabs in that window. ...
...ou send are delivered only to that content tab. you can mix and match: so for example, you could load a script into every tab using the global message manager, but then send a message to the script instance loaded into a specific tab by using the browser message manager. ...
...And 6 more matches
NetUtil.jsm
the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. ...
... the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. ...
...rming common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. ...
...And 6 more matches
Storage
indows as a known extension for an 'application compatibility database' and changes are backed up by the system automatically as part of system restore functionality. this can result in significantly higher overhead file operation. closing a connection to close a connection on which only synchronous transactions were performed, use the mozistorageconnection.close() method. if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose() method. the latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via callback when the connection is closed. statements this section demonstrates how you can execute sql statements on your database. for a complete reference see mozistoragestatement. ...
...dexes for parameters are always one less than the number you write in the sql. the use of numerical indexes for parameters is strongly discouraged in javascript where named parameters are much easier to use. binding multiple sets of parameters starting in gecko 1.9.2 (firefox 3.6), there's a new, more convenient way to bind multiple sets of parameters at once prior to executing your statement asynchronously. this api is only available for asynchronous execution. let stmt = dbconn.createstatement("insert into table_name (value) values(:value)"); let params = stmt.newbindingparamsarray(); for (let i = 0; i < 10; i++) { let bp = params.newbindingparams(); bp.bindbyname("value", i); params.addparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a state...
... attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams(). once all the parameters are set up, a single call to mozistoragestatement.bindparameters() will ensure that the parameters are bound before execution. you can then execute the statement asynchronously, and the statement will get each set of bindings bound to it before execution asynchronously. executing a statement you may execute statements either synchronously (which is supported in firefox gecko 1.8 and 1.9) or asynchronously (starting in gecko 1.9.1). if your code needs to work with applications based on gecko 1.8 or 1.9, you should the technique covered in the section synchrono...
...And 6 more matches
Debug - Archive of obsolete content
rite and writeln functions of the debug object display strings in the visual studio output window at run time. to debug internet explorer scripts, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 and later versions include the javascript debugger. if the script is not being debugged, the debug methods and properties have no effect. ...
...ut window at run time. to debug internet explorer scripts, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 and later versions include the javascript debugger. if the script is not being debugged, the debug methods and properties have no effect. constants async callback status codes contant description value debug.ms_async_callback_status_assign_delegate the synchronous work item assigned a callback or continuation to be run by an asynchronous operation. 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operation. 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation. 2 ...
..._assign_delegate the synchronous work item assigned a callback or continuation to be run by an asynchronous operation. 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operation. 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation. 2 debug.ms_async_callback_status_cancel the synchronous work item was canceled. 3 debug.ms_async_callback_status_error the synchronous work item caused an error in an asynchronous operation. ...
...And 5 more matches
Necko Interfaces Overview
setters for various uri parts (eg. scheme, host, path, ...) per protocol implementation necko provides uri impl's for common uri formats (see nsstandardurl, nssimpleuri) nsichannel : nsirequest represents a logical connection to the resource identified by a nsiuri per protocol implementation single use (ie. channel is used to download the resource once) download initiated via nsichannel::asyncopen method can be canceled via nsirequest::cancel method at anytime after invocation of asyncopen method nsiprotocolhandler a service that manages a protocol, identified by it's uri scheme (eg. http) maps uri string to nsiuri instance via newuri method creates nsichannel instance from nsiuri instance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consum...
... method at anytime after invocation of asyncopen method nsiprotocolhandler a service that manages a protocol, identified by it's uri scheme (eg. ...
...ler a service that manages a protocol, identified by it's uri scheme (eg. ...
...And 5 more matches
nsIChannelEventSink
nderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. these methods are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method. ...
...l's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. these methods are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method. starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously. ...
...there, from the loadgroup's notificationcallbacks. these methods are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method. starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously. ...
...And 5 more matches
nsIProtocolProxyService
in gecko 1.7 implemented by: @mozilla.org/network/protocol-proxy-service;1. ...
...on_blocking 1<<0 this flag may be passed to the resolve method to request that it fail instead of block the calling thread. proxy auto config (pac) may perform a synchronous dns query, which may not return immediately. so, calling resolve without this flag may result in locking up the calling thread for a lengthy period of time. ...
...otherwise, this method returns null indicating that a direct connection should be used. if this proxy is unavailable, getfailoverforproxy() may be called to determine the correct secondary proxy to be used. ...
...And 5 more matches
WebGL best practices - Web APIs
tion is complete. (see also parallel shader compilation below.) get*parameter() in general: possible flush + round-trip. in some cases, these will be cached to avoid the round-trip, but try to avoid relying on this. checkframebufferstatus(): possible flush + round-trip. getbuffersubdata(): usual finish + round-trip. (this is okay for read buffers in conjunction with fences - see async data readback below.) readpixels() to the cpu (i.e. without an unpack buffer bound): finish + round-trip. instead, use gpu-gpu readpixels in conjunction with async data readback. always keep vertex attrib 0 array-enabled if you draw with vertex attrib 0 array disabled, you will force the browser to do complicated emulation when running on desktop opengl (such as on macos). this is beca...
...won't use again can have high cost, particularly on tiled-rendering gpus common on mobile. when you're done with the contents of a framebuffer attachment, use invalidateframebuffer to discard the data, instead of leaving the driver to waste time storing the data for later use. depth/stencil and/or multisampled attachments in particular are great candidates for invalidateframebuffer. ...
...s of a framebuffer attachment, use invalidateframebuffer to discard the data, instead of leaving the driver to waste time storing the data for later use. depth/stencil and/or multisampled attachments in particular are great candidates for invalidateframebuffer. ...
...And 5 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
."; } </script> ... such timing-related issues are also hardware-related -- slower systems can reveal bugs that faster systems hide. one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywindow = window.open("about:blank"); mywindow.location.href = "http://www.ibm.com"; } </script> the problem with the code is that window.open is asynchronous -- it does not block the javascript execution until the window has finished loading. therefore, you may execute the line after the window.open line before the new window has finished. you can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener). differences in javascript-generating html javascript can, through docume...
...</foo></xml>"; var mydocument; if (window.domparser) { // this browser appears to support domparser var parser = new domparser(); mydocument = parser.parsefromstring(xmlstring, "text/xml"); } else if (window.activexobject){ // internet explorer, create a new xml document using activex // and use loadxml as a dom parser. mydocument = new activexobject("microsoft.xmldom"); mydocument.async = false; mydocument.loadxml(xmlstring); } else { // not supported. } see using xml data islands in mozilla for an alternative approach. xmlhttprequest internet explorer allows you to send and retrieve xml files using msxml's xmlhttp class, which is instantiated through activex using new activexobject("msxml2.xmlhttp") or new activexobject("microsoft.xmlhttp"). since there is no standard ...
...osoft.xmlhttp"). since there is no standard method of doing this, mozilla provides the same functionality in the global javascript xmlhttprequest object. since version 7 ie also supports the "native" xmlhttprequest object. ...
...And 4 more matches
Communicating with frame scripts
chrome code and frame scripts communicate back and forth using a messaging api which can include json-serializable objects as arguments. the api is mostly symmetrical, with one major exception: frame scripts can send asynchronous or synchronous messages to chrome, but chrome can only send asynchronous messages to content. this is an intentional design decision made to prevent content code from making chrome code unresponsive. ...
... content. this is an intentional design decision made to prevent content code from making chrome code unresponsive. where absolutely necessary, frame scripts can pass wrappers called cross process object wrappers (also known as cpows) to chrome, and chrome can use these wrappers to get synchronous access to content objects. content to chrome the frame script can choose to send synchronous or asynchronous messages to chrome code. asynchronous messaging to send an asynchronous message the frame script uses the global sendasyncmessage() function: // frame script sendasyncmessage("my-addon@me.org:my-e10s-extension-message"); sendasyncmessage() takes one mandatory parameter, which is the name of the message. all messages share the same namespace, so to avoid conflicts with other code, you'l...
...e name, you can pass detailed data as a string or a json-serializable object, and after that you can pass any objects it wants to pass to content as cpows. the example below sends a message named "my-e10s-extension-message", with a data payload containing details and tag properties, and exposes the event.target object as a cpow: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }, { target : event.target }); }, false); to receive messages from content, a chrome script needs to add a message listener using the message manager's addmessagelistener() api. the message passed to the listener is an object containing the following properties: ...
...And 4 more matches
Performance
described in their respective subtopics. performance best practices declaring stateless functions once per process bad: // addon.js services.mm.loadframescript("framescript.js", true) // framescript.js const precomputedconstants = // ... function helper(window, action) { // ... do some work on the window } function dosomething(message) { result = helper(content, message.data) sendasyncmessage("my-addon:response-from-child", {something: result}) } addmessagelistener("my-addon:request-from-parent", dosomething) why is this bad? because declared functions are also objects. and since frame scripts get evaluated for each tab this means new function objects get instantiated, new constants get computed, block scopes must be set up etc. while it may seem fairly innocencous in thi...
...ript.js components.utils.import("resource://my-addon/processmodule.jsm", {}).addframe(this) // processmodule.jsm const exported_symbols = ['addframe']; const precomputedconstants = // ... function helper(window, action) { // ... do some work on the window } function dosomething(message) { frameglobal = message.target result = helper(frameglobal.content, message.data) frameglobal.sendasyncmessage("my-addon:response-from-child", {something: result}) } function addframe(frameglobal) { frameglobal.addmessagelistener("my-addon:request-from-parent", dosomething) } javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless callbacks. but care must be taken to not leak references to the frame script g...
... taken to not leak references to the frame script global when it is passed into a jsm. alternatively the frame's unload event or weak maps can be used to ensure that frames can be cleaned up when their respective tab is closed. store heavyweight state once per process bad: // addon.js var main = new myaddonservice(); main.onchange(statechange); function statechange() { services.mm.broadcastasyncmessage("my-addon:update-configuration", {newconfig: main.serialize()}) } // framescript.js var maincopy; function onupdate(message) { maincopy = myaddonservice.deserialize(message.data.newconfig); } addmessagelistener("my-addon:update-configuration", onupdate) // maincopy used by other functions the main issue here is that a separate object is kept for each tab. not only does that incr...
...And 4 more matches
Performance best practices for Firefox front-end engineers
historically, there hasn't been an easy way of doing this - however, bug 1434376 has recently landed some chromeonly helpers to the window binding to make this simpler. if you want to queue up some javascript to run after the next "natural" style and layout flush, try: // suppose we want to get the computed "display" style of some node without // causing a style flush. ...
...e a lot of dom objects have one or even several properties that do so. if you require size or position information, you have a few options. bug 1434376 has recently landed a helper in the window binding to make it easier for priviledged code to queue up javascript to run when we know that the dom is not dirty, and size, position, and style information is cheap to query for. ...
...the use of initial values or the cascade, the offscreen animation optimizations are dependent on the explicit definition. see this comment and a few previous comments on that bug for more information. use indexeddb for storage appcache and localstorage are synchronous storage apis that will block the main thread when you use them. avoid them at all costs! indexeddb is preferable, as the api is asynchronous (all disk operations occur off of the main thread), and can be accessed from web workers. indexeddb is also arguably better than storing and retrieving json from a file—particularly if the json encoding or decoding is occurring on the main thread. indexeddb will do javascript object serialization and deserialization for you using the structured clone algorithm, meaning that you can stas...
...And 4 more matches
Sqlite.jsm
qlite interface. sqlite.jsm offers some compelling advantages over the low-level storage xpcom interfaces: automatic statement management. sqlite.jsm will create, manage, and destroy statement instances for you. you don't need to worry about caching created statement instances, destroying them when you are done, etc. this translates to fewer lines of code to talk to sqlite. all operations are asynchronous. use of synchronous storage apis is discouraged because they block the main thread. all the functionality in sqlite.jsm is asynchronous. easier memory management. since sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory in the process. there is even a shrinkmemory api that will minimize memory usage of th...
...s should not attempt to use the connection after calling this method as the connection will be unusable. it is possible to automatically close the connection when the browser is closed with the shutdown hook: const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); try { sqlite.shutdown.addblocker("my connection closing", async () => await conn.close()); } catch (e) { // it's too late to block shutdown, just close the connection. await conn.close(); throw e; } clone(readonly) this function returns a clone of the current connection-promise. these functions receive the following arguments: readonly (optional) if true the clone will be read-only, default is false. if the original connection is already read-o...
...n({path: "mydb.sqlite"}); const result = await conn.execute("select 1"); await conn.close(); alert("we are done!"); this isn't a terrific example because it doesn't include error handling. bound parameters here are some examples demonstrating bound parameters. assume we open an opened connection in the conn variable. ...
...And 4 more matches
PaymentRequest.show() - Web APIs
parameter, providing a promise that is fulfilled once the data is ready. if this is provided, show() will not allow the user to interact with the payment interface until the promise is fulfilled, so that data can be updated prior to the user engaging with the payment process. processing the result and, if necessary, calling paymentresponse.retry() to retry a failed payment can all be done either asynchronously or synchronously, depending on your needs. for the best user experience, asynchronous solutions are typically the best way to go. most examples on mdn and elsewhere use async/await to wait asynchronously while results are validated and so forth. syntax paymentpromise = paymentrequest.show(detailspromise); parameters detailspromise optional an optional promise that you can provide...
...) was not in response to a user action, such as a click or keyup event. other reasons a securityerror may be thrown are at the discretion of the user agent, and may include situations such as too many calls to show() being made in a short time or show() being called while payment requests are blocked by parental controls. ...
...scretion of the user agent, and may include situations such as too many calls to show() being made in a short time or show() being called while payment requests are blocked by parental controls. usage notes the most common patterns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection. ...
...And 4 more matches
Method definitions - JavaScript
ion assigned to the method's name. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const obj = { get property() {}, set property(value) {}, property( parameters… ) {}, *generator( parameters… ) {}, async property( parameters… ) {}, async* generator( parameters… ) {}, // with computed keys get [property]() {}, set [property](value) {}, [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, async* [generator]( parameters… ) {}, }; description the shorthand syntax is similar to the getter and setter syntax introduced in ecmascript 2015. given the following code...
...conjunction with the asterisk (*). ...
...And 4 more matches
await - JavaScript
when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. ...
...when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. ...
...when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. if the value of the expression following the await operator is not a promise, it's converted to a resolved promise. ...
...And 4 more matches
RDF in Mozilla FAQ - Archive of obsolete content
nages a table of all loaded datasources. the table is keyed by the datasource's "uri", which is either the url of an rdf/xml file, or a "special" uri starting with rdf: that refers to a built-in datasource. datasources may be loaded via the rdf service using the getdatasource() method. if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it. the datasource will remain "cached" until the last reference to the datasource is released. if the uri argument refers to a built-in datasource, the rdf service will use the xpcom component manager to load a component whose contractid is constructed using the "special" uri and the well-known prefix@mozilla.org/rdf/datasource;1?name=</code>. for example, rdf:foo would load:...
...ervice's getdatasource() method: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // ...and from it, get the datasource. ...
...nterfaces.nsirdfdatasource); // the nsirdfremotedatasource interface has the interfaces // that we need to setup the datasource. var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); // be sure that your web server will deliver this as text/xml (recommended) or text/rdf! remote.init("http://www.mozilla.org/some-rdf-file.rdf"); // make it load! note that this will happen asynchronously. by setting // ablocking to true, we could force it to be synchronous, but this // is generally a bad idea, because your ui will completely lock up! remote.refresh(false); // note that ds will load asynchronously, so assertions will not // be immediately available you may decide that you need to "manually" create an rdf/xml datasource if you want to force it to load synchronously. how...
...And 3 more matches
IPDL Best Practices
auto pointer will attempt to trigger protocol deletion a second time. while this can be worked around with actordestroy, being explicit about deleting the protocol with send__delete__ is easier to maintain, with symmetric alloc/deallocpprotocol functions also being easier to reason about. minimize overall use of messages reducing ipc traffic is a righteous goal. consider the following protocol: async protocol pasyncquerier { child: pasyncquery(); } async protocol pasyncquery { child: kickoffquery(nsstring query); parent: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent. following actor construction, the parent will send a kickoffquery message and presumably ignore the actor until it receives returnresult...
... there is a guaranteed sequence of messages that will be sent. ...
...anteed sequence of messages that will be sent. ...
...And 3 more matches
Extending a Protocol
not really fully documented anywhere - and the ipdl parser gets easily confused (hence us excluding comments below). creating the protocol pecho.ipdl let's start by saving the following file to ./dom/ipc/pecho.ipdl. we will explain what all the parts mean below. note that the file's name and the protocol name must match. include protocol pwindowglobal; namespace mozilla { namespace dom { async refcounted protocol pecho { manager pwindowglobal; parent: async echo(nscstring data) returns (nscstring aresult); async __delete__(); }; } // namespace dom } // namespace mozilla now, edit "./dom/ipc/moz.build" file and add 'pecho.ipdl', to the ipdl_sources array. remember that it needs to be in alphabetical order or it won't compile. breaking it down: include protocol pwindowglobal...
...it's also "refcounted", meaning it we can use refptr<> for instances that can be cycle collected. manager pwindowglobal; - we explicitly state that pwindowglobal is our manager. parent: - these are the messages that the parent is able to recieve. ...
... }; } // namespace dom } // namespace mozilla now, edit "./dom/ipc/moz.build" file and add 'pecho.ipdl', to the ipdl_sources array. remember that it needs to be in alphabetical order or it won't compile. breaking it down: include protocol pwindowglobal; - we include pwindowglobal, because it's going to manage the protocol for us. async refcounted protocol pecho {....} - this protocol is "async", meaning we are going to use mozpromises. ...
...And 3 more matches
Task.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/task.jsm"); introduction for an introduction to tasks, you may start from the task.js documentation, keeping in mind that only the core subset is implemented in this module. tasks are built upon generator functions and promises. the task.spawn() function takes a generator function and starts running it as a task. every time the task yields a promise, it waits until the promise is resolved. ...
...k functions. if you specify a function that is not a generator, it is called with no arguments, and the yield operator returns the return value of the function. this comes in handy when iterating over function lists where some items have been converted to tasks and some not. if you specify anything else, the yield operator returns exactly what you specified. method overview function async(atask); promise spawn(atask); properties attribute type description result read only constructor constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. example: task.spawn( function() { yield ... ; throw new task.result("value"); } note: if you ...
...row new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to return a result from a non-legacy generator function, don't use this. return the value instead: task.spawn( function*() { yield ... ; return "value"; } methods async() create and return an "async function" that starts a new task. function async( atask ); async() is similar to spawn(), except that: it doesn't immediately start the task, rather it returns an "async function" that starts the task when the function is called; it binds the task to the async function's this object and arguments; it requires the task to be a function. as...
...And 3 more matches
Scroll-linked effects
ten scrolling effects are implemented by listening for the scroll event and then updating elements on the page in some way (usually the css position or transform property.) you can find a sampling of such effects at css scroll api: use cases. these effects work well in browsers where the scrolling is done synchronously on the browser's main thread. however, most browsers now support some sort of asynchronous scrolling in order to provide a consistent 60 frames per second experience to the user. in the asynchronous scrolling model, the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the dom and fired on the main thread. this means that the effects implemented will lag a little bit behind what the user sees the scroll po...
...or thread and is visible to the user before the scroll event is updated in the dom and fired on the main thread. this means that the effects implemented will lag a little bit behind what the user sees the scroll position to be. this can cause the effect to be laggy, janky, or jittery — in short, something we want to avoid. below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: example 1: sticky positioning here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down. <body style="height: 5000px" onscroll="document.getelementbyid('toolbar').style.top = math.max(100, window.scrolly) + 'px'"> <div id="toolbar" style="positi...
...ntbyid('toolbar').style.top = math.max(100, window.scrolly) + 'px'"> <div id="toolbar" style="position: absolute; top: 100px; width: 100px; height: 20px; background-color: green"></div> </body> this implementation of sticky positioning relies on the scroll event listener to reposition the "toolbar" div. as the scroll event listener runs in the javascript on the browser's main thread, it will be asynchronous relative to the user-visible scrolling. therefore, with asynchronous scrolling, the event handler will be delayed relative to the user-visible scroll, and so the div will not stay visually fixed as intended. instead, it will move with the user's scrolling, and then "snap" back into position when the scroll event handler runs. this constant moving and snapping will result in a jittery visua...
...And 3 more matches
SavedFrame
s.waivexrays: const contentviewofstack = components.utils.waivexrays(somestack); accessor properties of the savedframe.prototype object source the source url for this stack frame, as a string. line the line number for this stack frame. column the column number for this stack frame. functiondisplayname either spidermonkey’s inferred name for this stack frame’s function, or null. ...
... = components.utils.waivexrays(somestack); accessor properties of the savedframe.prototype object source the source url for this stack frame, as a string. line the line number for this stack frame. column the column number for this stack frame. functiondisplayname either spidermonkey’s inferred name for this stack frame’s function, or null. ...
...rototype object source the source url for this stack frame, as a string. line the line number for this stack frame. column the column number for this stack frame. functiondisplayname either spidermonkey’s inferred name for this stack frame’s function, or null. asynccause if this stack frame is the asyncparent of other stack frames, then this is a string representing the type of asynchronous call by which this frame invoked its children. ...
...And 3 more matches
mozIStorageStatement
read only. parametercount unsigned long number of parameters. read only. params mozistoragestatementparams the cur...
...me like :userinput escape '/'" ); statement.params.userinput = statement.escapestringforlike(someuserinput, "/"); binding functions these functions are discussed in more detail with sample code in the overview document. newbindingparamsarray() creates and returns a new mozistoragebindingparamsarray object that can be used to bind multiple values to parameters in preparation for calling executeasync(). mozistoragebindingparamsarray newbindingparamsarray(); parameters none. bindparameters() binds all the parameters in the specified array to the statement in preparation for calling executeasync(). note: starting in gecko 2.0, this method returns ns_error_unexpected if the specified mozistoragebindingparamsarray is empty. void bindparameters( in mozistoragebindingparamsarray aparamete...
...esize ); parameters aparamindex the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). avalue to be bound to the specified index. avaluesize size of avalue. execution functions these functions are discussed in more detail with sample code in the overview document. ...
...And 3 more matches
nsIChannel
rm way. inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters. then, the uri can be fetched by calling open() or asyncopen(). after a request has been completed, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. this interface must be used only from the xpcom main thread. implemented by netwerk/base/src/nsbasechannel.cpp and netwerk/protocol/http/src/nshttpchannel.cpp...
...ompleted, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. this interface must be used only from the xpcom main thread. implemented by netwerk/base/src/nsbasechannel.cpp and netwerk/protocol/http/src/nshttpchannel.cpp. method overview void asyncopen(in nsistreamlistener alistener, in nsisupports acontext); nsiinputstream open(); attributes attribute type description contentcharset acstring the character set of the channel's content if available and if applicable. this attribute only applies to textual data. setting contentcharset before the channel has been opened provides a hint t...
...data. setting contenttype before the channel has been opened provides a hint to the channel as to what the mime type is. the channel may ignore this hint in deciding on the actual mime type that it will report. setting contenttype after onstartrequest has been fired or after open() is called will override the type determined by the channel. setting contenttype between the time that asyncopen() is called and the time when onstartrequest is fired has undefined behavior at this time. the value of the contenttype attribute is a lowercase string. a value assigned to this attribute will be parsed and normalized as follows: any parameters (delimited with a ';') will be stripped. if a charset parameter is given, then its value will replace the the contentcharset attr...
...And 3 more matches
nsIDNSService
rg/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); note: starting in gecko 7.0, the "happy eyeballs" strategy is used to reduce lengthy timeouts when attempting backup connections during attempts to connect from clients that have broken ipv6 connectivity. this is done by disabling ipv6 on backup connections. ...
... void init(); obsolete since gecko 1.8 nsidnsrecord resolve(in autf8string ahostname, in unsigned long aflags); void shutdown(); obsolete since gecko 1.8 attributes attribute type description myhostname autf8string read only. constants resolve flag constants various flags that may be ored together to form the aflags parameter passed to asyncresolve() and resolve(). constant value description resolve_bypass_cache (1 << 0) this flag suppresses the internal dns lookup cache. resolve_canonical_name (1 << 1) the canonical name of the specified host will be queried. resolve_priority_medium (1 << 2) the query is given medium priority. if used with low, medium takes precedence. ...
...cedence. resolve_priority_low (1 << 3) the query is given lower priority. if used with medium, medium takes precedence. resolve_speculate (1 << 4) indicates request is speculative. speculative requests return errors if prefetching is disabled by configuration. ...
...And 3 more matches
DevTools API - Firefox Developer Tools
eady the toolbox is ready to use. select(toolid) a tool has been selected. this event is emitted before the corresponding {toolid}-selected event. {toolid}-init(frame) a tool is about to be loaded. the frame is the <iframe> element that has been created for the tool. {toolid}-build(panel) the frame for a tool has loaded and the toolpanel.build() method has been called but the asynchronous initialization has not started. the parameter is a toolpanel object. {toolid}-ready(panel) the asynchronous initialization for a tool has completed and it is ready to be used. the parameter is a toolpanel object. {toolid}-selected(panel) a tool has been selected. the parameter is a toolpanel object. {toolid}-destroy(panel) a tool is about to be destroyed. the parameter is...
...ild: (window, toolbox) => new mytoolpanel(window, toolbox) }; // register it. gdevtools.registertool(def); targettype fixme: hosttype fixme toolpanel the toolpanel is an interface the toolbox uses to manage the panel of a tool. the object that tooldefinition.build() returns should implement the methods described below. methods open() optional. a method that can be used to perform asynchronous initialization. if the method returns a promise, many operations (e.g. gdevtools.showtoolbox() or toolbox.selecttool()) and events (e.g. toolbox-ready) are delayed until the promise has been fulfilled. return value: the method should return a promise that is resolved with the toolpanel object once it's ready to be used. destroy() a method that is called when the toolbox is clos...
... operations (e.g. gdevtools.showtoolbox() or toolbox.selecttool()) and events (e.g. toolbox-ready) are delayed until the promise has been fulfilled. return value: the method should return a promise that is resolved with the toolpanel object once it's ready to be used. destroy() a method that is called when the toolbox is closed or the tool is unregistered. if the tool needs to perform asynchronous operations during destruction the method should return a promise that is resolved once the process is complete. return value: a promise if the function performs asynchronous operations, otherwise undefined. example here's a basic template for a toolpanel implementation. // in the tooldefintion object, do // build: (window, target) => new mypanel(window, target), function mypan...
...And 3 more matches
ContentIndex - Web APIs
k for the index property, which gives us access to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' };...
...unction which uses the add() method to register it with the content index. ...
...er it with the content index. ...
...And 3 more matches
Content Index API - Web APIs
k for the index property, which gives us access to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' };...
...unction which uses the add() method to register it with the content index. ...
...er it with the content index. ...
...And 3 more matches
HTMLScriptElement - Web APIs
e. htmlscriptelement.src is a domstring representing the url of an external script. it reflects the src attribute. htmlscriptelement.event is a domstring; an obsolete way of registering event handlers on elements in an html document. htmlscriptelement.charset is a domstring representing the character encoding of an external script. it reflects the charset attribute. ...
...ing representing the url of an external script. it reflects the src attribute. htmlscriptelement.event is a domstring; an obsolete way of registering event handlers on elements in an html document. htmlscriptelement.charset is a domstring representing the character encoding of an external script. it reflects the charset attribute. ...
... domstring; an obsolete way of registering event handlers on elements in an html document. htmlscriptelement.charset is a domstring representing the character encoding of an external script. it reflects the charset attribute. htmlscriptelement.async htmlscriptelement.defer the async and defer attributes are boolean attributes that control how the script should be executed. the defer and async attributes must not be specified if the src attribute is absent. there are three possible execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads. if the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing. if neither attribute is present, th...
...And 3 more matches
Promise.all() - JavaScript
r. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.all(iterable); parameters iterable an iterable object such as an array. return value an already resolved promise if the iterable passed is empty. ...
...se.all(iterable); parameters iterable an iterable object such as an array. return value an already resolved promise if the iterable passed is empty. an asynchronously resolved promise if the iterable passed contains no promises. note, google chrome 58 returns an already resolved promise in this case. a pending promise in all other cases. this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. see the example about "asynchronicity or synchronicity of promise.all" below. returned values will be in order of the promises passed, regardless of completion order. description this method can be useful for aggregating the results of multiple promises. it is t...
...ty) when all the promises in the given iterable have resolved, or if any of the promises reject. see the example about "asynchronicity or synchronicity of promise.all" below. returned values will be in order of the promises passed, regardless of completion order. description this method can be useful for aggregating the results of multiple promises. it is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting. in comparison, the promise returned by promise.allsettled() will wait for all input promises to complete, regardless of whether or not one rejects. consequently, it will always return the final result of every promise and function fr...
...And 3 more matches
test/utils - Archive of obsolete content
, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous. to make them asynchronous, pass a third argument done, which is a function to call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before...
... parameters exports : object a test file's exports object beforefn : function the function to be called before each test. it has two arguments, or three ...
...okmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert, done) { removeallbookmarksasync(function () { done(); }); }); require('sdk/test').run(exports); globals functions before(exports, beforefn) runs beforefn before each test in the file. may be asynchronous if beforefn accepts a third argument, which is a callback. parameters exports : object a test file's exports object beforefn : function the function to be called before each test. it has two arguments, or three if it is asynchronous: the first argument is the test's name as a string. the second argument is the assert object for the test. the third, optional, argument is a callbac...
...And 2 more matches
File I/O - Archive of obsolete content
a nsiuri; to get the string "file://...", see url.spec to get an nsifile from the 'file://' url, use nsifileurl: // url is a nsiuri; see nsiioservice::newuri for getting a string into a nsiuri. var file = url.queryinterface(components.interfaces.nsifileurl).file; // file is a nsifile to load from file://, http://, chrome://, resource:// and other urls directly, use xmlhttprequest or netutil.asyncfetch(). also note that generally you don't need to use nsifile::path. use nsifile directly wherever possible. an example below shows how you should save a path in user prefs. storing nsifile in preferences the following two snippets show the right way to store a file path in user preferences (more about preferences in mozilla): absolute path (nsifile) to store an arbitrary path in user prefe...
... will allow you to read a file without locking up the ui thread while reading. please note that some i/o, such as getting file information and opening the file can still happen on the main thread and therefore block the ui for periods of time. this sample code uses netutil.jsm. so therefore for the first parameter, file, you can pass an nsifile object or a string (such as a jar path) see: netutil.asyncfetch: components.utils.import("resource://gre/modules/netutil.jsm"); netutil.asyncfetch(file, function(inputstream, status) { if (!components.issuccesscode(status)) { // handle error! return; } // the file data is contained within inputstream. // you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read wit...
...ook up (which would be synchronous i/o). in this case an nsichannel object has to be explicitly created from the file: components.utils.import("resource://gre/modules/netutil.jsm"); // content type hint is useful on mobile platforms where the filesystem // would otherwise try to determine the content type. var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.asyncfetch(channel, function(inputstream, status) { ... }); writing to a file write a string this sample uses netutil.jsm and fileutils.jsm. components.utils.import("resource://gre/modules/netutil.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); // file is nsifile, data is a string // you can also optionally pass a flags parameter here. it defaults to // fileutils.mode_w...
...And 2 more matches
Promises - Archive of obsolete content
promise apis for common asynchronous operations due to the performance and stability costs of synchronous io, many apis which rely on it have been deprecated. the following page contains examples of many promise-based replacement apis for common operations. these apis allow asynchronous operation to be achieved with a coding style similar to synchronous variants. the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code. a task example like the following: components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function* () { var response = yield request("login", { username: user, password: password });...
... via the os.file api, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files. it is also available for use off-main-thread in workers as a synchronous api. this interface replaces the previous, complicated xpcom nsifile and streams apis, and their related javascript helper modules. these older interfaces should be avoided, even in their asynchronous forms, due to their performance penalties and needless complexity. representative example usage components.utils.import("resource://gre/modules/osfile.jsm"); task.spawn(function* () { // retrieve file metadata to check modification time. let info = yield os.file.stat(configpath); if (info.lastmodificationdate <= timestamp) return; timestamp = info.lastmodificati...
... order by value desc limit 1"); latesttimestamp = row.getresultbyindex(0); } finally { // make sure to close the database when finished. // failure to do this will prevent firefox from shutting down // cleanly. yield db.close(); } }); promise wrappers and helpers the following are some example promise-based wrappers for common callback-based asynchronous apis. addonmanager var aom = { __proto__: addonmanager, addon: function addon(addon) { if (!(addon && "getdatadirectory" in addon)) return addon; return { __proto__: addon, getdatadirectory: function getdatadirectory() { return new promise((accept, reject) => { return addon.getdatadirectory...
...And 2 more matches
Cross Process Object Wrappers
b content: instead, it must factor out the code that interacts with web content into separate scripts that are called frame scripts. chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing api. to learn more about this, see the documentation on using the message manager. chrome to content messaging must be asynchronous. this is because the chrome process runs the firefox ui, so if it were blocked by the content process, then a slow content process could cause firefox to become unresponsive to users. converting synchronous code to be asynchronous can be difficult and time-consuming. as a migration aid, the messaging framework enables frame scripts to make content objects available to chrome through a w...
... objects available to chrome through a wrapper called a cross process object wrapper, also known as a cpow. however, although cpows are convenient, they have serious limitations and can cause responsiveness problems, so should only be used when necessary and only as a migration aid. ...
...messages to chrome using one of two global functions: sendasyncmessage() or sendsyncmessage(). the optional third parameter to each of these functions is an object whose properties are objects to wrap. for example, this frame script sends a dom node to chrome when the user clicks it, as the clicked property of the third argument: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-e10s-extension-message", {}, { clicked : event.target }); }, false); in the chrome script, the dom node is now accessible through a cross process object wrapper, as a property of the objects property of the message. the chrome script can get and set the wrapped object's properties and call its functions: // chrome script windowmm.addmessagelistener("my-e10s-extension-message", handle...
...And 2 more matches
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
nsifileoutputstream stream.init(file, ioflags, perm, behaviorflags); channels have streams too any implementation of nsichannel will have an input stream as well, but unless you own the channel, you shouldn't try to read from the input stream. there are two ways of getting the input stream: by calling the channel's .open() method for a synchronous read, or by calling the channel's .asyncopen() method with an nsistreamlistener object. you can get an nsichannel object from the io service's newchannel(spec, charset, baseuri) method or its .newchannelfromuri(uri) method. the "safe file output stream" mozilla provides a "safe file output stream" implementation. this implementation actually writes the contents of the file you're trying to create to a temporary file. if everything go...
... .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = "utf-8"; var stream = converter.converttoinputstream(string); javascript modules are your friends there are several useful javascript modules at your disposal. for streams, the most obvious are netutil.jsm and fileutils.jsm. netutil.jsm provides apis for copying an input stream to an output stream (the asynccopy() method), getting an input stream from another source (the asyncfetch() method), and reading an input stream into a string (the readinputstreamtostring() method). fileutils.jsm provides apis for getting output streams for files, with the .openfileoutputstream(file, modeflags) and .opensafefileoutputstream(file, modeflags) methods, and for closing those output streams with the .closesafefile...
...treams with the .closesafefileoutputstream(inputstream) method. as we mentioned earlier, you can use the io service to get any channel, and from there an input stream. the io service is available through the services.jsm module as the .io property. stream listeners a stream listener is an object you build to let you know when there is data in a stream ready for you to consume. most streams are asynchronous: they make no assumptions that all the data a resource provides is available immediately. (this is particularly true of streams that reach out over a network connection, like http and ftp channels.) stream listeners implement three methods. from the nsistreamlistener interface, the .ondataavailable(request, context, inputstream, offset, count) method gives you the input stream and the num...
...And 2 more matches
nsICacheSession
netwerk/cache/public/nsicachesession.idlscriptable handles open synchronous and asynchronous cache entry operations along with evicting cache entries and checking for cache devices instantiation according to the session storage policies. ...
... netwerk/cache/public/nsicachesession.idlscriptable handles open synchronous and asynchronous cache entry operations along with evicting cache entries and checking for cache devices instantiation according to the session storage policies. ...
...mentry(in acstring key, in nsicachelistener listener); attributes attribute type description doomentriesifexpired prbool expired entries will be doomed or evicted if this attribute is set to true. if false, expired entries will be returned (useful for offline mode and clients, such as http, that can update the valid lifetime of cached content). this attribute defaults to true. methods asyncopencacheentry() this method gives an asynchronous cache access. does not block the calling thread. instead, the listener will be notified when the descriptor is available. void asyncopencacheentry( in acstring key, in nscacheaccessmode accessrequested, in nsicachelistener listener, [optional] in boolean nowait ); parameters key the key for cache entry. accessrequested the requested acce...
...And 2 more matches
nsIProgressEventSink
the information is intended to be displayed to the user in some meaningful way. an implementation of this interface can be passed to a channel via the channel's notificationcallbacks attribute. ...
...the information is intended to be displayed to the user in some meaningful way. an implementation of this interface can be passed to a channel via the channel's notificationcallbacks attribute. ...
...tus and progress information that is generally not critical to the processing of the channel. the information is intended to be displayed to the user in some meaningful way. an implementation of this interface can be passed to a channel via the channel's notificationcallbacks attribute. see nsichannel for more info. the channel will begin passing notifications to the progress event sink after its asyncopen method has been called. notifications will cease once the channel calls its listener's onstoprequest method or once the channel is canceled (via nsirequest.cancel()). note: this interface is actually not specific to channels and may be used with other implementations of nsirequest. method overview void onprogress(in nsirequest arequest, in nsisupports acontext, in unsigned long...
...And 2 more matches
nsIResumableChannel
netwerk/base/public/nsiresumablechannel.idlscriptable this interface is meant to be implemented by the channels that support resuming broken downloads (for example necko's html and ftp channels). ...
...orts ctxt, in unsigned long startpos, in nsiresumableentityid entityid); obsolete since gecko 1.8 void resumeat(in unsigned long long startpos, in acstring entityid); attributes attribute type description entityid acstring the entity id for this uri. available after onstartrequest. read only. exceptions thrown ns_error_not_resumable if this load is not resumable. ...
...r this uri. available after onstartrequest. read only. exceptions thrown ns_error_not_resumable if this load is not resumable. methods asyncopenat() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) open this channel, and read starting at the specified offset. the request given to the nsistreamlistener will be qiable to nsiresumableinfo. void asyncopenat( in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid ); parameters listener as for asyncopen. ctxt as for asyncopen. startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. resumeat() prepare this channel fo...
...And 2 more matches
nsIStreamConverter
rted plain text into html. you could implement this interface to allow everyone else to use your conversion logic using a standard api. stream converter users there are currently two ways to use a stream converter: synchronous: stream to stream. you can supply the service with a stream of type x and it will convert it to your desired output type and return a converted (blocking) stream to you. asynchronous: nsistreamlistener to nsistreamlistener. you can supply data directly to the converter by calling it's nsistreamlistener.ondataavailable() method. it will then convert that data from type x to your desired output type and return converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable() method. stream converter suppliers registering a ...
...rocess. first of all the stream converter implementation must register itself with the component manager using a contractid in the format below. second, the stream converter must add the contractid to the registry. ...
...he stream converter root key is defined in this file): @mozilla.org/streamconv;1?from=from_mime_type&to=to_mime_type method overview void asyncconvertdata(in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert(in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt); methods asyncconvertdata() asynchronous version: converts data arriving via the converter's nsistreamlistener.ondataavailable() method from one type to another, pushing the converted data out to the caller via alistener::ondataavailable(). ...
...And 2 more matches
LockManager.request() - Web APIs
false. signal optional: an abortsignal (the signal property of an abortcontroller); if specified and the abortcontroller is aborted, the lock request is dropped if it was not already granted. callback … return value a promise that resolves with undefined when the request is granted. examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback. once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // the lock was granted. }); mode example the following example shows how to use the mode option for readers and writers. notice that both functions use a lock called my_resource. t...
... }); } the do_write() function use the same lock but in 'exclusive' mode which will delay invocation of the request() call in do_read() until the write operation has completed. ...
... mode example the following example shows how to use the mode option for readers and writers. notice that both functions use a lock called my_resource. the do_read() requests a lock in 'shared' mode meaning that multiple calls may occur simultaneously across different event handlers, tabs, or workers. async function do_read() { await navigator.locks.request('my_resource', {mode: 'shared'}, async lock => { // read code here. }); } the do_write() function use the same lock but in 'exclusive' mode which will delay invocation of the request() call in do_read() until the write operation has completed. this applies across event handlers, tabs, or workers. function do_write() { await navigator.locks.request('my_resource', {mode: 'exclusive'}, async lock => { // write code here. ...
...And 2 more matches
Using Service Workers - Web APIs
the service worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a service worker and maintains that for its lifetime. so documents will have to be reloaded to actually be controlled. the below graphic shows a summary of the available service worker events: promises promises are a great mechanism for running async operations, with success dependant on one another. this is central to the way service workers work. promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .then() to the end and include callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure callback. let’s compare a t...
...r. this is central to the way service workers work. promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .then() to the end and include callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure callback. let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent. sync try { const value = myfunction(); console.log(value); } catch(err) { console.log(err); } async myfunction().then((value) => { console.log(value); }).catch((err) => { console.log(err); }); in the first example, we have to wait for myfunction() to run and return value before any more of the code can execute. in the second example, myfunction() returns ...
... now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? this is a standard thing to want to do, but it can be a bit of a pain. ...
...And 2 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
take advantage of the access this gives you to the internals of streams to make adjustments. among the simplest things you can do is to implement a "hold" feature, wherein a participant in a call can click a button and turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio. note: this example makes use of modern javascript features including async functions and the await expression. this enormously simplifies and makes far more readable the code dealing with the promises returned by webrtc methods. in the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. activating hold mode local peer when the local user decides to enable hold mod...
... by webrtc methods. in the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. activating hold mode local peer when the local user decides to enable hold mode, the enablehold() method below is called. it accepts as input a mediastream containing the audio to play while the call is on hold. ...
...audio to play instead of the local peer's microphone audio, can come from anywhere. one possibility is to have a hidden <audio> element and use htmlaudioelement.capturestream() to get its audio stream. remote peer on the remote peer, when we receive an sdp offer with the directionality set to "sendonly", we handle it using the holdrequested() method, which accepts as input an sdp offer string. ...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
ification is in flux. inline an on-screen presentation of the xr imagery within the context of the document window. if the session couldn't be created for some reason—such as feature policy disallowing its use or the user declining to grant permission to use the headset—the promise gets rejected. so a more complete function that starts up and returns a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } this function returns the new xrsession or throws an exception if an error occurs while creating the session. customizing the session in addition to the display mode, the requestsession() method can take an optional object with init...
...reference spaces should be used to represent the world's coordinate system. you can specify either required or optional reference spaces in order to obtain a session compatible with the reference spaces you need or prefer to use. ...
... in order to ensure that the session you get can use unbounded spaces: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr", { requiredfeatures: [ "unbounded" ] }); return session; } catch(error) { throw error; } } on the other hand, if you need aninline session and would prefer a local reference space, you can do this: async function createinlinesession(xr) { try { session = await xr.requestsession("inline", { optionalfeatures: [ "local" ] }); return session; } catch(error) { throw error; } } this createinlinesession() function will try to create an inline session that's compatible with the local reference space. when you're ready to create your reference space, you can try for a local s...
...And 2 more matches
Web Locks API - Web APIs
while held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources. web locks concepts and usage a lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. ...
...rce, identified by a name chosen by the web app. for example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and indexed db, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) the api is used as follows: the lock is requested. work is done while holding the lock in an asynchronous task. the lock is automatically released when the task completes. navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something(); await do_something_else(); // now the lock will be released. }); while a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. the first queued r...
... await do_something(); await do_something_else(); // now the lock will be released. }); while a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. the first queued request will be granted only when the lock is released. the api provides optional functionality that may be used as needed, including: returning values from the asynchronous task shared and exclusive lock modes conditional acquisition diagnostics to query the state of locks in an origin an escape hatch to protect against deadlocks locks are scoped to origins; the locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins. the main entry point is navigator.lock...
...And 2 more matches
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts metadata content, or any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlscriptelement attributes this element includes the global attributes. ...
...ding tag are mandatory. permitted parents any element that accepts metadata content, or any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlscriptelement attributes this element includes the global attributes. asynchtml5 for classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. this attribute allows the elimina...
...nation of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case. this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. see browser compatibility for notes on browser support. see also async scripts for asm.js. crossorigin normal script elements pass minimal information to the window.onerror for scripts which do not pass the standard cors checks. to allow error logging for sites which use a separate domain for static media, use this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicat...
...And 2 more matches
Promise() constructor - JavaScript
us a pull request. syntax new promise(executor) parameters executor a function to be executed by the constructor, during the process of constructing the promiseobj. the executor is custom code that ties an outcome to a promise. you, the programmer, write the executor. the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typically, some asynchronous operation. } at the time when the constructor generates the new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" to the promiseobj. therefore, the code within the executor has the opportunity to perform some operation and then reflect the operation's outcome(if the value is not another promise object) as either ...
...mise object) as either "fulfilled" or "rejected" by terminating with an invocation of either the resolutionfunc or the rejectionfunc, respectively. the executor has no meaningful return value. it communicates via the side-effect caused by resolutionfunc or rejectionfunc. the side-effect is that the promiseobj becomes "resolved." typically, it works like this: the operation within executor is asynchronous and provides a callback. the callback is defined within the executor code. the callback terminates by invoking resolutionfunc. the invocation of resolutionfunc includes a value parameter. the value is passed back to the tethered promiseobj. the promiseobj (asynchronously) invokes any .then() associated with it. the value received by promiseobj.then() is passed to the invocation of handle...
...t as an argument, you can say that it is "resolved", but still cannot be said to be "settled". examples creating a new promise a promise object is created using the new keyword and its constructor. this constructor takes a function, called the "executor function", as its parameter. this function should take two functions as parameters. ...
...And 2 more matches
Promise.prototype.then() - JavaScript
he received argument). onrejected optional a function called if the promise is rejected. this function has one argument, the rejection reason. if it is not a function, it is internally replaced with a "thrower" function (it throws an error it received as argument). return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop). the behavior of the handler function follows a specific set of rules. if a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected w...
... that promise's value as its value. returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler. following, an example to demonstrate the asynchronicity of the then method. // using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack. the value received and returned is: " + value); ...
...r // reject(new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subsequent then in the method chain. the below snippet simulates asynchronous code with the settimeout function. promise.resolve('foo') // 1. receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return new promise(function(resolve, reject) { settimeout(function() { string += 'bar'; resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on t...
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
h adobe, codingscripting, flash, glossary, infrastructure flash is an obsolescent technology developed by adobe for viewing expressive web applications, multimedia content, and streaming media. adobe flash can run from supporting web browsers via a browser plug-in. 14 ajax ajax, codingscripting, glossary, infrastructure, l10n:priority ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest. 15 algorithm codingscripting, glossary an algorithm is a self-contained series of instructions to perform a function. 16 alignment container alignment container, css, glossary, alignment the alignment container is the rect...
...rominent part of the nascent internet. arpanet was closed in early 1990. 23 array array, codingscripting, glossary, javascript, programming an array is an ordered collection of data (either primitive or object depending upon the language). arrays are used to store multiple values in a single variable. this is compared to a variable that can store only one value. 24 asynchronous glossary, web, webmechanics, asynchronous the term asynchronous refers to or multiple related things happening without waiting for the previous one to complete). 25 attribute codingscripting, glossary, html an attribute extends an element, changing its behavior or providing metadata. 26 bandwidth glossary, infrastructure bandwidth is the ...
...king standard web sites/apps that enjoy all the best parts of the web — such as discoverability via search engines, being linkable via urls, and working across multiple form factors — and supercharging them with modern apis (such as service workers and push) and features that confer other benefits more commonly attributed to native apps. 335 promise glossary, promise, promises, asynchronous a promise is an object that's returned by a function that has not yet completed its work. the promise literally represents a promise made by the function that it will eventually return a result through the promise object. 336 property disambiguation, glossary the term property can have several meanings depending on the context. it may refer to: 337 pro...
...whole or in part) as the image presented on a polygon's surface within a 3d rendered image. it is not to be confused with pixel which is the unit of screen space. this is one of the main differences between texel’s and pixels, pixels are image data. texel components are made up of subjective data, therefore they can be an image as well as a depth map. 456 thread glossary, thread, asynchronous thread in computer science is the execution of running multiple tasks or programs at the same time. each unit capable of executing code is called a thread. 457 three js browser, codingscripting, javascript, programming language, three.js three.js is a javascript-based webgl engine that can run gpu-powered games and other graphics-powered apps straight from the br...
Fetching data from the server - Learn web development
en needed, helping to solve the problem described above. this is achieved by using apis like xmlhttprequest or — more recently — the fetch api. these technologies allow web pages to directly handle making http requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data. this is normally not the case these days (you'd be more likely to use xmlhttprequest or fetch to request json), but the result is still the same, and the term "ajax" is still often used to describe the technique. the ajax model involves using a web api as a proxy to more intelligently request data r...
...he type of response we are expecting — which is defined by the request's responsetype property — as text. this isn't strictly necessary here — xhr returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. xhr allows you to handle this using its onload event handler — this is run when the load event fires (when the response has returned). when this has occurred, the response data will be ...
...he example from a local file. this is because of security restrictions (for more on web security, read website security). to get around this, we need to test the example by running it through a local web server. to find out how to do this, read how do you set up a local testing server? fetch the fetch api is basically a modern replacement for xhr; it was introduced in browsers recently to make asynchronous http requests easier to do in javascript, both for developers and other apis that build on top of fetch. let's convert the last example to use fetch instead. make a copy of your previous finished example directory. (if you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files — verse1.txt, verse2.txt, ...
... so what is going on in the fetch code? first of all, we invoke the fetch() method, passing it the url of the resource we want to fetch. this is the modern equivalent of request.open() in xhr, plus you don't need any equivalent to .send(). after that, you can see the .then() method chained onto the end of fetch() — this method is a part of promises, a modern javascript feature for performing asynchronous operations. fetch() returns a promise, which resolves to the response sent back from the server — we use .then() to run some follow-up code after the promise resolves, which is the function we've defined inside it. this is the equivalent of the onload event handler in the xhr version. this function is automatically given the response from the server as a parameter when the fetch() promi...
What is JavaScript? - Learn web development
used to be to put your script element right at the bottom of the body (e.g. just before the </body> tag), so that it would load after all the html has been parsed. the problem with this solution is that loading/parsing of the script is completely blocked until the html dom has been loaded. on larger sites with lots of javascript, this can cause a major performance issue, slowing down your site. async and defer there are actually two modern features we can use to bypass the problem of the blocking script — async and defer (which we saw above). let's look at the difference between these two. scripts loaded using the async attribute (see below) will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. you get no guarantee tha...
...(which we saw above). let's look at the difference between these two. scripts loaded using the async attribute (see below) will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. you get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. it is best to use async when the scripts in the page run independently from each other and depend on no other script on the page. for example, if you have the following script elements: <script async src="js/vendor/jquery.js"></script> <script async src="js/script2.js"></script> <script async src="js/script3.js"></script> you can't rely on the order the scripts will load in. jquery.js may load before or after scrip...
...js/vendor/jquery.js"></script> <script async src="js/script2.js"></script> <script async src="js/script3.js"></script> you can't rely on the order the scripts will load in. jquery.js may load before or after script2.js and script3.js and if this is the case, any functions in those scripts depending on jquery will produce an error because jquery will not be defined at the time the script runs. async should be used when you have a bunch of background scripts to load in, and you just want to get them in place as soon as possible. for example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, titles, and lobby, without them being blocked by script loading. scripts loaded using the de...
...fer attribute will load in the order they appear on the page. so in the second example, we can be sure that jquery.js will load before script2.js and script3.js and that script2.js will load before script3.js. they won't run until the page content has all loaded, which is useful if your scripts depend on the dom being in place (e.g. they modify one of more elements on the page). to summarize: async and defer both instruct the browser to download the script(s) in a separate thread, while the rest of the page (the dom, etc.) is downloading, so the page loading is not blocked by the scripts. if your scripts should be run immediately and they don't have any dependencies, then use async. if your scripts need to wait for parsing and depend on other scripts and/or the dom being in place, load th...
Error codes returned by Mozilla APIs
ain that would exceed the amount allowed for that domain. ns_error_dom_file_not_found_err (0x80650000) file was not found. ns_error_dom_file_not_readable_err (0x80650001) file could not be read. network errors the following errors can occur when creating connections over the network, or when reading or writing data. ns_binding_failed (0x804b0001) ns_binding_aborted (0x804b0002) the asynchronous request failed because it was aborted by some user action. ns_binding_redirected (0x804b0003) the asynchronous request has been "redirected" to a different async request. (for example, an http redirect occurred). this error code is used with load groups to notify the load group observer when a request in the load group is redirected to another request. ns_binding_retargeted (0x804b0004)...
... ns_error_malformed_uri (0x804b000a) the uri is malformed. ...
...ion is already established. xxx currently unused - consider removing. ns_error_not_connected (0x804b000c) the connection does not exist. xxx currently unused - consider removing. ns_error_connection_refused (0x804b000d) ns_error_net_timeout (0x804b000e) ns_error_in_progress (0x804b000f) the requested action could not be completed while the object is busy. implementations of nsichannel.asyncopen() will commonly return this error if the channel has already been opened (and has not yet been closed). ns_error_offline (0x804b0010) ns_error_no_content (0x804b0011) returned from nsichannel.asyncopen() to indicate that ondataavailable will not be called because there is no content available. this is used by helper app style protocols (for example, mailto). ns_error_unknown_protocol (...
... ns_error_first_header_field_component_empty (0x804b0022) while parsing for the first component of a header field using syntax such as that for content-disposition or content-type, the first component was found to be empty. javascript errors these errors typically occur when interfacing between javascript and native co...
Message manager overview
there are three different subtypes of frame message manager: the global message manager, the window message manager, and the browser message manager. all three enable chrome code to: load a script into a frame in the content the content process using a loadframescript() function. these scripts are called "frame scripts". communicate with frame scripts using addmessagelistener() and broadcastasyncmessage() or sendasyncmessage() functions. note that in this context, "browser" refers to the xul <browser> object, which is a frame that hosts a single web document. it does not refer to the more general sense of a web browser. global message manager the global message manager operates on every <browser> (that is, every open content tab). loadframescript() loads the given script into e...
... that in this context, "browser" refers to the xul <browser> object, which is a frame that hosts a single web document. it does not refer to the more general sense of a web browser. global message manager the global message manager operates on every <browser> (that is, every open content tab). loadframescript() loads the given script into every <browser> in every browser window. broadcastasyncmessage() sends the message to every <browser> in every browser window. it's a chromemessagebroadcaster object, which implements the following interfaces: nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster you can access the global message manager like this: // chrome script let globalmm = cc["@mozilla.org/globalmessagemanager;1"] .getservice(ci.nsimessagelistenermana...
... it's a chromemessagebroadcaster object, which implements the following interfaces: nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster the window message manager can be accessed as a property of the browser window: // chrome script let windowmm = window.messagemanager; browser message manager the br...
... you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager. it's a chromemessagesender object, which implements the following interfaces: nsiprocesschecker nsiframescri...
How to implement a custom autocomplete search component
queryinterface: xpcomutils.generateqi([ ci.nsiautocompleteresult ]) }; /** * @constructor * * @implements {nsiautocompletesearch} */ function providerautocompletesearch() { } providerautocompletesearch.prototype = { classid: class_id, classdescription : class_name, contractid : contract_id, /** * searches for a given string and notifies a listener (either synchronously * or asynchronously) of the result * * @param searchstring the string to search for * @param searchparam an extra parameter * @param previousresult a previous result to use for faster searchinig * @param listener the listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, previousresult, listener) { var results = ['mary', 'john']; var au...
...to do so put the following declaration in your chrome.manifest...
... queryinterface: function(aiid) { if (!aiid.equals(ci.nsiautocompleteresult) && !aiid.equals(ci.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; // implements nsiautocompletesearch function simpleautocompletesearch() { } simpleautocompletesearch.prototype = { /* * search for a given string and notify a listener (either synchronously * or asynchronously) of the result * * @param searchstring - the string to search for * @param searchparam - an extra parameter * @param previousresult - a previous result to use for faster searchinig * @param listener - a listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, result, listener) { // this autocomplete source assumes the deve...
...push(searchresults[i].value); if (searchresults[i].comment) comments.push(searchresults[i].comment); else comments.push(null); } } var newresult = new simpleautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, comments); listener.onsearchresult(this, newresult); } }, /* * stop an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: function(aiid) { if (!aiid.equals(ci.nsiautocompletesearch) && !aiid.equals(ci.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; // factory var simpleautocompletesearchfactory = { singleton: null, createinstance: function (aouter, aiid) { if (aouter !
DeferredTask.jsm
alize(); attributes isarmed boolean indicates whether the task is currently requested to start again later, regardless of whether it is currently running. isrunning boolean indicates whether the task is currently running. this is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function. methods ispending obsolete since gecko 28 check the current task state. bool ispending(); return value returns true if pending, false otherwise. start obsolete since gecko 28 start (or postpone) task. void start(); flush obsolete since gecko 28 perform any postponed task immediately. void flush(); cancel obsolete since gecko 28 cancel any pend...
...k is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the new execution terminates. if the task is not running and the timer is not armed, the method returns a resolved promise. promise finalize(); example firefox 28 note this section describes about deferredtask.jsm in firefox 28.0 or higher. ...
...}, 2000); // the task is ready, but will not be executed until requested. ...
... was already running at this point, then one last execution from start to finish will happen again, immediately after the current execution terminates. if the timer is not armed, the "finalize" method only ensures that any running task terminates. ...
L20n Javascript API
ctx.registerlocalenegotiator(function(available, requested, deflocale, callback) { yourapp.getallavailablelanguages(function(allavailable) { var fallbackchain = yourapp.intersect(alla...
...the following arguments: available - all locales available to the context instance, requested - locales preferred by the user, deflocale - the default locale to be used as the ultimate fallback, callback - the function to call when the negotiation completes (useful for asynchronous negotiators). it must return an array which is the final fallback chain of locales, or if the negotiation is asynchronous, it must return a falsy value and call the callback argument upon completion. ctx.registerlocalenegotiator(function(available, requested, deflocale, callback) { yourapp.getallavailablelanguages(function(allavailable) { var fallbackchain = yourapp.intersect(allavailable, requested); cb(fallbackchain); }); }); ctx.requestlocales(...requestedlocales: string?) specify the user'...
...ate against and freeze the context instance. when a context instance is frozen, no more resources can be added or linked. all io related to fetching the resource files takes place when a context instance freezes. when all resources have been fetched, parsed and compiled, the context instance will emit a ready event. the final list of locales supported by the context instance will be negotiated asynchronously by the negotiator registered by registerlocalenegotiator. ctx.requestlocales('pl'); ctx.requestlocales('fr-ca', 'fr'); if requestedlocales argument list is empty or undefined, the default locale from registerlocales will be used. ctx.requestlocales('pl'); if registerlocales hasn't been called, the special i-default locale is used, which means that the following minimal code...
...isters a callback which fires when all entities listed in ids have been retrieved. ctx.localize(['hello', 'about'], function(l10n) { var node = document.queryselector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); the callback becomes bound to the entities on the ids list. it will be called when the entities become available (asynchronously) or whenever the translation of any of the entities changes. localize should be the preferred way of localizing the ui. the callback function is passed an l10n object with the following properties: entities: an object whose keys are the identifiers and value are the entity objects as returned by getentitysync, reason: an object with the reason why callback was invoked. the reason...
Components.isSuccessCode
ro xpcom return code (that is, not ns_ok) does not necessarily indicate failure. components.issuccesscode() is functionally equivalent to the following javascript: function issuccesscode(returncode) { return (returncode & 0x80000000) === 0; } since failure error codes are turned into exceptions when encountered in javascript, this function usually is not necessary. however, if you are using asynchronous apis, it may be essential. for example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed. if the task is sufficiently complex that it can fail, the notification will include a status code indicating the success or failure of the operation (see, for example, nsirequestobserver.onstopre...
... to determine the success or failure of the complex task, you would call components.issuccesscode() upon the status code included in the notification. examples checking whether copying a stream's data succeeded the following example demonstrates copying data from a buffered nsiinputstream to an nsioutputstream, checking for whether the copy succeeded using components.issuccesscode(). note: nsiasyncstreamcopier.init() has changed in gecko 1.9.2, omit last 2 boolean parameters if you're using gecko 1.9.1 and earlier. const cc = components.classes; const ci = components.interfaces; const cr = components.results; // global flags polled externally var copyfailed = false; var copyinprogress = false; function copybufferedstream(instream, outstream) { var copyobserver = { onstartrequ...
...copyinprogress = false; // did the copy fail? ...
...if (!components.issuccesscode(statuscode)) copyfailed = true; }, queryinterface: function(aiid) { if (aiid.equals(ci.nsirequestobserver) || aiid.equals(ci.nsisupports)) return this; throw cr.ns_error_no_interface; } }; var copier = cc["@mozilla.org/network/async-stream-copier;1"] .createinstance(ci.nsiasyncstreamcopier); copier.init(instream, outstream, null, true, false, 8192, true, true); copier.asynccopy(copyobserver, null); } ...
HOWTO
in all callbacks where your script is finished, i.e. ...
...in all callbacks where your script is finished, i.e. ...
...in all callbacks where your script is finished, i.e. ...
...in all callbacks where your script is finished, i.e. ...
mozIVisitInfoCallback
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides callback handling functionality for moziasynchistory.updateplaces() 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) method overview void handleerror(in nsresult aresultcode, in moziplaceinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handleerror() called when a moziplaceinfo couldn't be processed. void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason wh...
... methods handleerror() called when a moziplaceinfo couldn't be processed. void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason why the change failed. aplaceinfo the information that was unable to be processed. handleresult() called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). if more than one operation is done for a given visit, this method is only called once (for all changes at once). void handleresult( in moziplaceinfo aplaceinfo ); parameters aplaceinfo the information that was entered into the database. oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for ea...
...a given visit, this method is only called once (for all changes at once). void handleresult( in moziplaceinfo aplaceinfo ); parameters aplaceinfo the information that was entered into the database. oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this method was replaced by the separate handleresult() and handleerror() methods in gecko 8.0 (firefox 8.0 / thunderbird...
...t aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this method was replaced by the separate handleresult() and handleerror() methods in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). see also mozivisitinfo moziasynchistory ...
nsIAuthPrompt2
base/public/nsiauthprompt2.idlscriptable an interface allowing to prompt for a username and password. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is usually acquired using getinterface on notification callbacks or similar. ...
...r. it can be used to prompt users for authentication information, either synchronously or asynchronously. this interface is implemented by @mozilla.org/login-manager/prompter;1. to create an instance, use: var authprompt2 = components.classes["@mozilla.org/login-manager/prompter;1"] .createinstance(components.interfaces.nsiauthprompt2); method overview nsicancelable asyncpromptauth(in nsichannel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo); boolean promptauth(in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo); constants constant value description level_none 0 the password will be sent unencrypted. no security provided.
...evel, in nsiauthinformation authinfo); constants constant value description level_none 0 the password will be sent unencrypted. no security provided. level_pw_encrypted 1 password will be sent encrypted, but the connection is otherwise insecure. level_secure 2 the connection, both for password and data, is secure. methods asyncpromptauth() asynchronously prompt the user for a username and password. this has largely the same semantics as nsiauthprompt.promptusernameandpassword(), but must return immediately after calling and return the entered data in a callback. if the user closes the dialog using a cancel button or similar, the callback's nsiauthpromptcallback.onauthcancelled() method must be called. calling nsicance...
...on when the prompt fails to queue, for example because of out-of-memory error. it must not throw when the prompt could already be potentially shown to the user. in that case information about the failure has to come through the callback. this way we prevent multiple dialogs shown to the user because consumer may fall back to synchronous prompt on synchronous failure of this method. nsicancelable asyncpromptauth( in nsichannel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo ); parameters achannel the channel that requires authentication. acallback acontext level one of the level constants. authinfo authentication information object. the implementation should fill in this object with the informat...
nsIMicrosummaryService
a microsummary generator for the given uri. nsimicrosummarygenerator getgenerator( in nsiuri generatoruri ); parameters generatoruri the uri of the generator. return value returns an nsimicrosummarygenerator for the given uri. getmicrosummaries() get the set of microsummaries available for a given page. the set might change after this method returns, since this method will trigger an asynchronous load of the page in question (if it isn't already loaded) to see if it references any page-specific microsummaries. if the caller passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when callers want to display a list of microsummaries for a page that isn't loade...
.... if the caller passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when callers want to display a list of microsummaries for a page that isn't loaded, and they want to display the actual content of the selected microsummary immediately (rather than after the content is asynchronously loaded). nsimicrosummaryset getmicrosummaries( in nsiuri pageuri, in long long bookmarkid optional ); parameters pageuri the uri of the page for which to retrieve available microsummaries. bookmarkid optional the id of the bookmark for which this method is being called. return value returns an nsimicrosummaryset of nsimicrosummaries for the given page. getmicrosumm...
... nsimicrosummary microsummary ); parameters bookmarkid the bookmark to check. microsummary the microsummary to check. return value returns whether or not the microsummary is the current one for the bookmark. refreshmicrosummary() refreshes a microsummary, updating its value in the datastore and ui. if this method can refresh the microsummary instantly, it will. ...
...k. refreshmicrosummary() refreshes a microsummary, updating its value in the datastore and ui. if this method can refresh the microsummary instantly, it will. otherwise, it'll asynchronously download the necessary information (the generator and/or page) before refreshing the microsummary. callers should check the content property of the returned microsummary object to distinguish between sync and async refreshes. if its value is null, then it's an async refresh, and the caller should register itself as an nsimicrosummaryobserver via nsimicrosummary.addobserver() to find out when the refresh completes. nsimicrosummary refreshmicrosummary( in long long bookmarkid ); parameters bookmarkid the bookmark whose microsummary is being refreshed. return value returns the microsummary being r...
nsIServerSocket
the listener...
... abacklog); void initwithaddress([const] in prnetaddrptr aaddr, in long abacklog);native code only! void close(); void asynclisten(in nsiserversocketlistener alistener); prnetaddr getaddress();native code only! attributes attribute type description port long returns the port of this server socket. read only. methods asynclisten() this method puts the server socket in the listening state. it will asynchronously listen for and accept client connections. the listener will be notified once for each client connection that is accepted. the listener's onsocketaccepted() method will be called on the same thread that called asynclisten() (the calling thread must have an nsieventtarget). the listener will be passed a refe...
...connections. the listener will be notified once for each client connection that is accepted. the listener's onsocketaccepted() method will be called on the same thread that called asynclisten() (the calling thread must have an nsieventtarget). the listener will be passed a reference to an already connected socket transport (nsisockettransport). see nsiserversocketlistener for more details. void asynclisten( in nsiserversocketlistener alistener ); parameters alistener the listener to be notified when client connections are accepted. close() this method closes a server socket. ...
... void close(); parameters none. native code only!getaddress returns the address to which this server socket is bound. since a server socket may be bound to multiple network devices, this address may not necessarily be specific to a single network device. ...
URLs - Plugins
browser cannot locate the url and retrieve the data, it does not create a stream for the instance; in this case, the plug-in receives notification of the result. to request a stream and receive notification of the result in all cases, use npn_geturlnotify. for http urls, the browser resolves npn_geturl as the http server method get, which requests url objects. note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data. for this reason as well, calling npn_geturlnotify may be more useful than npn_geturl; the plug-in is notified upon either successful or unsuccessful completion of the request. nperror npn_geturl(npp instance, const char *url, const char *targ...
...request the creation of a new stream with the contents of the specified url, and, in addition, npn_geturlnotify notifies the plug-in of the successful or unsuccessful completion of the request. the browser notifies the plug-in by calling the plug-in's npp_urlnotify function and passing it the notifydata value, which may be used to track multiple requests. npn_geturlnotify handles the url request asynchronously. it returns immediately and only later handles the request and calls npp_urlnotify. without this notification, the plug-in cannot tell whether a request with a null target failed or a request with a non-null target was completed. nperror npn_geturlnotify(npp instance, const char* url, const char* target, void* notifydata); the instance, url, and target paramete...
...e browser resolves this method as the http server method post, which transmits data to the server. the data to post can be contained either in a local temporary file or a new memory buffer. to post a file, set the flag file to true, the buffer buf to the path name string for a file, and len to the length of the path string. the file-type url prefix "file://" is optional. npn_posturl is typically asynchronous: it returns immediately and only later handles the request and calls npp_notify (which, in turn, calls npp_urlnotify). nperror npn_posturl(npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file); the instance, url, and target parameters have the same definitions as those of npn_geturl. the buf parameter identifies a local temporary file or data buf...
...aders (even a blank line) in a memory buffer. to do this, use npn_posturlnotify for this purpose. § the npn_posturlnotify function has all the same capabilities and works like npn_posturl in most ways except that (1) it supports specifying headers when posting a memory buffer, and (2) it calls npp_urlnotify upon successful or unsuccessful completion of the request. npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify. nperror npn_posturlnotify( npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file, void* notifydata ); the parameters of this function have the same definitions as those of npn_posturl. the notifydata parameter contains plug-in-private data passed by npp_urln...
Waterfall - Firefox Developer Tools
console the period between matching calls to console.time() and console.timeend(). timer name the argument passed to the console functions. stack at start call stack console.time(), with links to functions. stack at end (new in firefox 41). call stack at console.timeend(). if this is inside a callback from a promise, this will also show the "async stack". timestamp a single call to console.timestamp(). label the argument passed to timestamp(). domcontentloaded the document's domcontentloaded event. load the document's load event. worker event in main thread shown when the main thread sends a messa...
...n freeze. using the frame rate tool and the waterfall together, it's easy to see when long-running javascript is causing responsiveness problems. in the screenshot below, we've zoomed in on a js function that's caused a drop in the frame rate: the intensive javascript article shows how the waterfall can highlight responsiveness problems caused by long javascript functions, and how you can use asynchronous methods to keep the main thread responsive. expensive paints some paint effects, such as box-shadow, can be expensive, especially if you are applying them in a transition where the browser has to calculate them in every frame. if you're seeing drops in the frame rate, especially during graphically-intensive operations and transitions, check the waterfall for long green markers. garbage ...
...prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar. async stack new in firefox 41. starting in firefox 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeend() was called. if console.timeend() was called from the resolution of a promise, it will also display "(async: promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. for example...
... to make a timestamp marker, call console.timestamp(). you can pass an argument to label the timestamp. for example, suppose we adapt the code above to make a timestamp every 10 iterations of the loop, labeled with the iteration number: var iterations = 70; var multiplier = 1000000000; functi...
Using Fetch - Web APIs
this kind of functionality was previously achieved using xmlhttprequest. fetch provides a better alternative that can be easily used by other technologies such as service workers. fetch also provides a single logical place to define other http-related concepts such as cors and extensions to http. ...
...ts are controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. supplying request options the fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings: see fetch() for the full options available, and more details. // example post method implementation: async function postdata(url = '', data = {}) { // default options are marked with * const response = await fetch(url, { method: 'post', // *get, post, put, delete, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'content-type...
...ile line by line the chunks that are read from a response are not broken neatly at line boundaries and are uint8arrays, not strings. if you want to fetch a text file and process it line by line, it is up to you to handle these complications. the following example shows one way to do this by creating a line iterator (for simplicity, it assumes the text is utf-8, and doesn't handle fetch errors). ...
... ({ value: chunk, done: readerdone } = await reader.read()); chunk = remainder + (chunk ? ...
File and Directory Entries API - Web APIs
files and/or directories in a virtual, sandboxed file system. because this is a non-standard api, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. check the browser compatibility section for details. two very similar apis exist depending on whether you desire asynchronous or synchronous behavior. the synchronous api is intended to be used inside a worker and will return the values you desire. the asynchronous api will not block and functions and the api will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives. the firefox implementation of the file and directory entries api is very limited; th...
...calls to work with it. the htmlinputelement.webkitentries property lets you access the filesystemfileentry objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser (bug 1326031). if htmlinputelement.webkitdirectory is true, the <input> element is instead a directory picker, and you get filesystemdirectoryentry objects for each selected directory. asynchronous api the asynchronous api should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. it includes the following interfaces: filesystem represents a file system. filesystementry the basic interface representing a single entry in a file system. this is implemented by other interfaces which represent files or directori...
...le system. filesystemdirectoryreader created by calling filesystemdirectoryentry.createreader(), this interface provides the functionality which lets you read the contents of a directory. filesystemflags defines a set of values which are used when specifying option flags when calling certain methods in the file and directory entries api. fileerror represents an error which is generated by asynchronous file system calls. there are also two global functions (which are not part of the specification at this time and are implemented only by google chrome). they're available on the window object and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchronous api the synchronous api is should only be used in workers; these calls block until they're fini...
...and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchronous api the synchronous api is should only be used in workers; these calls block until they're finished executing, and simply return the results instead of using callbacks. using them on the main thread will block the browser, which is naughty. the interfaces below otherwise mirror the ones from the asynchronous api. filesystemsync represents a file system. filesystementrysync the basic interface representing a single entry in a file system. this is implemented by other interfaces which represent files or directories. filesystemfileentrysync represents a single file in a file system. filesystemdirectoryentrysync represents a single directory in a file system. filesystemdirectoryreadersy...
IDBRequest - Web APIs
each request has a readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. ...
...bases and database objects using event handler attributes. each reading and writing operation on a database is done using a request. the request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the idbrequest instance. all asynchronous operations immediately return an idbrequest instance. each request has a readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. when the state is set to done, every request returns a result and an error, and an event is fired on the request. when the state is still pending, any attempt to access the result or error raises an invalidsta...
... idbrequest instance. each request has a readystate that is set to the 'pending' state; this changes to 'done' when the request is completed or fails. when the state is set to done, every request returns a result and an error, and an event is fired on the request. when the state is still pending, any attempt to access the result or error raises an invalidstateerror exception. in plain words, all asynchronous methods return a request object. if the request has been completed successfully, the result is made available through the result property and an event indicating success is fired at the request (idbrequest.onsuccess). if an error occurs while performing the operation, the exception is made available through the result property and an error event is fired (idbrequest.onerror). the interfac...
... eventtarget. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error caused a request to fail. also available via the onerror property. success fired when an idbrequest succeeds. also available via the onsuccess property. example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not dbopenrequest.onerror =...
Using IndexedDB - Web APIs
indexeddb is a way for you to persistently store data inside a user's browser. because it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline. about this document this tutorial walks you through using the asynchronous api of indexeddb. if you are not familiar with indexeddb, you should first read basic concepts about indexeddb. for the reference documentation on the indexeddb api, see the indexeddb article and its subpages. this article documents the types of objects used by indexeddb, as well as the methods of the asynchronous api (the synchronous api was removed from spec). basic pattern the basic pattern that indexeddb encourages is the following: open a database. create an object sto...
...us open our database var request = window.indexeddb.open("mytestdatabase", 3); see that? opening a database is just like any other operation — you have to "request" it. the open request doesn't open the database or start the transaction right away. the call to the open() function returns an idbopendbrequest object with a result (success) or error value that you handle as an event. most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or error. the result for the open function is an instance of an idbdatabase. the second parameter to the open method is the version of the database. the version of the database determines the database schema — the object stores in the database and their structure. if the database doesn't already exist...
...an intuitive approach to maintaining some information across browser sessions is to read it from the database when the browser (or a particular page) is opened, update it as the user interacts with the browser, and then save it to the database when the browser (or page) closes. however, this will not work. the database transactions will be created in the unload event handler, but because they are asynchronous they will be aborted before they can execute. in fact, there is no way to guarantee that indexeddb transactions will complete, even with normal browser shutdown. see bug 870645. as a workaround for this normal shutdown notification, you might track your transactions and add a beforeunload event to warn the user if any transactions have not yet completed at the time of unloading. at least...
...this means that a function (e.g. opendb()) that calls open() and onsuccess will return before the onsuccess handler has run. this issue is also true of other request methods such as transaction() and get(). ...
Navigator.sendBeacon() - Web APIs
syntax navigator.sendbeacon(url, data); parameters url the url that will receive the data. can be relative or absolute. data a arraybuffer, arraybufferview, blob, domstring, formdata, or urlsearchparams object containing the data to send. return values the sendbeacon() method returns true if the user agent successfully queued the data for transfer. otherwise, it returns false. description this method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. ...
...thod is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. for example, which link the user clicked before navigating away and unloading the page. ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous xmlhttprequests made in an unload handler. historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay th...
...th a synchronous xmlhttprequest in an unload handler. this results in the next page load to be delayed. window.addeventlistener("unload", function logdata() { var xhr = new xmlhttprequest(); xhr.open("post", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces. ...
..., false); // third parameter of `false` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces. with the sendbeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. this solves all of the problems with submission of analytics data: the data is sent reliably it's sent asynchronously it doesn't impact the loading of the next page in addition, the code is simpler to write than any of the older techniques! the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method. window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http req...
PaymentResponse.retry() - Web APIs
l complete("success") to finalize the payment and proces it. if show() is rejected, the payment request failed, usually because either there's already one being processed, because the user agent doesn't support any of the specified payment methods, or because of a security issue. see the list of exceptions for show() for further details. call complete("fail") to close the payment request. ...
... let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the exception */ } } examples try { await paymentrequest.retry(errorfields); } catch (domexception err) { ... ...
...dle the exception */ } } examples try { await paymentrequest.retry(errorfields); } catch (domexception err) { ... ...
...se, "payerdetailchange", payervalidator); promisestofixthings.push(promise); } await promise.all([response.retry(errors), ...promisestofixthings]); await recursivevalidate(request, response); } function fixfield(requestorresponse, event, validator) { return new promise(resolve => { // browser keeps calling this until promise resolves. ...
Using the Screen Capture API - Web APIs
screen sharing on browsers that support it but do not implement the current standard api. this works with at least chrome, edge, and firefox. capturing screen contents capturing screen contents as a live mediastream is initiated by calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents. ...
...browsers that support it but do not implement the current standard api. this works with at least chrome, edge, and firefox. capturing screen contents capturing screen contents as a live mediastream is initiated by calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents. ...
...olves to a stream containing the live screen contents. starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below. starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user agent responds by pres...
...span class="info">${msg}</span><br>`; this allows us to use the familiar console.log(), console.error(), and so on to log information to the log box in the document. starting display capture the startcapture() method, below, starts the capture of a mediastream whose contents are taken from a user-selected area of the screen. startcapture() is called when the "start capture" button is clicked. ...
SubtleCrypto.exportKey() - Web APIs
e key. notsupported raised when trying to export in an unknown format. typeerror raised when trying to use an invalid format. examples note: you can try the working examples out on github. raw export this example exports an aes key as an arraybuffer containing the bytes for the key. see the complete code on github. /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button. */ win...
...y as a pkcs #8 object. the exported key is then pem-encoded. see the complete code on github. /* convert an arraybuffer into a string from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function ab2str(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. ...
...encryption key as a pem-encoded subjectpublickeyinfo object. see the complete code on github. /* convert an arraybuffer into a string from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function ab2str(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. ...
..."encrypt", "decrypt"] ).then((keypair) => { const exportbutton = document.queryselector(".spki"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.publickey); }); }); json web key import this code exports an ecdsa private signing key as a json web key object. see the complete code on github. /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "jwk", key ); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = json.stringify(exported, null, " "); } /* generate a sign/verify key pair, then set up an event listener on the "export" button. */ window.crypto.subtle.generatekey( { name: "ecds...
SubtleCrypto.unwrapKey() - Web APIs
use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2. */ async function getunwrappingkey() { // 1. get the key material (user-supplied password) const keymaterial = await getkeymaterial(); // 2 initialize the salt parameter. // the salt must match the salt originally used to derive the key. // in this example it's supplied as a constant "saltbytes". const saltbuffer = bytestoarraybuffer(saltbytes); // 3 derive the key from key material and salt...
...": "pbkdf2", salt: saltbuffer, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-kw", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* unwrap an aes secret key from an arraybuffer containing the raw bytes. takes an array containing the bytes, and returns a promise that will resolve to a cryptokey representing the secret key. */ async function unwrapsecretkey(wrappedkey) { // 1. get the unwrapping key const unwrappingkey = await getunwrappingkey(); // 2. initialize the wrapped key const wrappedkeybuffer = bytestoarraybuffer(wrappedkey); // 3. unwrap the key return window.crypto.subtle.unwrapkey( "raw", // import format wrappedkeybuffer, // arraybuffer representing key to unwrap unwr...
...se as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-gcm key using pbkdf2. */ async function getunwrappingkey() { // 1. get the key material (user-supplied password) const keymaterial = await getkeymaterial(); // 2 initialize the salt parameter. // the salt must match the salt originally used to derive the key. // in this example it's supplied as a constant "saltbytes". const saltbuffer = bytestoarraybuffer(saltbytes); // 3 derive the key from key material and salt...
... salt: saltbuffer, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* unwrap an rsa-pss private signing key from an arraybuffer containing the raw bytes. takes an array containing the bytes, and returns a promise that will resolve to a cryptokey representing the private key. */ async function unwrapprivatekey(wrappedkey) { // 1. get the unwrapping key const unwrappingkey = await getunwrappingkey(); // 2. initialize the wrapped key const wrappedkeybuffer = bytestoarraybuffer(wrappedkey); // 3. initialize the iv const ivbuffer = bytestoarraybuffer(ivbytes); // 4. unwrap the key return window.crypto.subtle.unwrapkey( "pkcs8", // import format ...
SubtleCrypto.verify() - Web APIs
ign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. ...
...for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. ...
...e for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. ...
...or sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. ...
SubtleCrypto.wrapKey() - Web APIs
given some key material and some random salt derive an aes-kw key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-kw", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key. */ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it. */ windo...
...ven some key material and some random salt derive an aes-gcm key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key. ...
...ven some key material and some random salt derive an aes-cbc key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-cbc", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key. ...
...ven some key material and some random salt derive an aes-gcm key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256}, true, [ "wrapkey", "unwrapkey" ] ); } /* wrap the given key. ...
Advanced techniques: Creating and sequencing audio - Web APIs
sound sample it's straightforward enough to emulate phone dial (dtmf) sounds, by playing a couple of oscillators together using the methods we've already looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved. ...
...h to emulate phone dial (dtmf) sounds, by playing a couple of oscillators together using the methods we've already looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved. loading the sample we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing. let's create anothe...
...unction 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. ...
...ait fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing. let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to take an array of files and loop over them to load more than one sample. this would be very handy for more...
Connecting to Remote Content - Archive of obsolete content
you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code. following initialization, onload and onerror handlers are registered to a callback function to handle the response return...
...be "get", "post" or "put". sending a post request requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not. in asynchronous mode code execution continues immediately after the send call. in synchronous mode the code and user interface are blocked while waiting for a response to come back. note: requests can take a long time to process and you don't want users to be stuck waiting while a request is obtained and processed. therefore, it is very important that xmlhttprequest calls are al...
... now let's look at the most common types of content you can use to communicate with remote servers. json content json is a very lightweight and simple data representation format, similar to the object representation used in javascript. unlike javascript, the json format doesn't allow any kind of code that can be run, only data. ...
Updating addons broken by private browsing changes - Archive of obsolete content
reading this document, contact josh matthews with further questions or clarifications, or file a bug if your extension has stopped working due to a change described here and you are having trouble updating it. ...
...n will require updating to correctly support the new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed). idls nsitransferable: see using the clipboard for information about the new init method. imgicache: this must no longer be obtained as a service. see the imgicache article for more information. moziasyncfavicons/nsifaviconservice: setandfetchfaviconforpage/setandloadfaviconforpage now take a required privacy status argument, either nsifaviconservice.favicon_load_private or nsifaviconservice.favicon_load_non_private. nsiwebbrowserpersist: saveuri gained a new argument; see the nsiwebbrowserpersist docs for more information. nsicontentprefservice: getpref, setpref, haspref, hascachedpref, rem...
...download ids (and specifically the id property of nsidownload) are deprecated, and don't allow access to private downloads. all downloads now use guids, and contain a new guid property. nsidownload now has retry, cancel, remove, pause, and resume methods which should be used instead of deprecated similarly-named nsidownloadmanager methods. nsidownload's getdownload method is deprecated; use the asynchronous getdownloadbyguid method instead. nsidownloadmanager now has activeprivatedownloads, activeprivatedownloadcount, and privatedbconnection members to complement the existing public ones. nsidownloadmanager's addlistener method is deprecated. addprivacyawarelistener should be used instead, or no notifications will be received for private downloads. there is a new download-manager-remove-do...
Notes on HTML Reflow - Archive of obsolete content
or example, for a text frame when the text must be wrapped. some reflows are immediate in response to user or script actions; for example, resizing the window or changing the document's default font. these are dispatched directly from the presentation shell (e.g., nsipresshell::stylechangereflow), and affect the entire frame tree. other reflows are incremental and are dealt with asynchronously; for example, when content streams in from the network. incremental reflows are queued by the presentation shell for batched dispatch. reflow state the reflow state object, nshtmlreflowstate, is used to pass constraining information "down" from parent frames to child frames. for example, a <div> with a constrained width (e.g., set via the css width property) would note this in t...
...t its child frames. initial, incremental, resize, and style change reflows may each be performed as an immediate "global" reflow from the presentation shell: an initial reflow is performed when the presentation shell is initialized to flow the shell's initial frame hierarchy. incremental reflows are dispatched en masse when the presentation shell's incremental reflow queue is asynchronously serviced. a resize reflow is performed when the presentation shell's dimensions change; e.g., because the user resized the shell's window. a style change reflow is performed when the presentation shell's global stylistic information is changed; e.g., addition or removal of a style sheet, a change to the shell's default font. a dirty reflow is never performed directly from the presen...
...t the frame itself has changed. scheduling. to request (or schedule ) an incremental reflow (e.g., in response to a change in the content model), a reflow command object is created and passed to the presentation shell via the nsipresshell::appendreflowcommand method. the presentation shell does not process the command immediately. instead, it queues the command, and processes it asynchronously along with other queued reflow commands en masse . coalescing. as described below, the reflow command has a type and a target frame . multiple reflow commands with the same type and target frame are coalesced : the presentation shell simply refuses to add subsequent commands of the same type for the same frame to the queue. a caller may also can...
jspage - Archive of obsolete content
on(b,a){return math.pow(2,10*--b)*math.cos(20*b*math.pi*(a[0]||1)/3);}});["quad","cubic","quart","quint"].each(function(b,a){fx.transitions[b]=new fx.transition(function(c){return math.pow(c,[a+2]); });});var request=new class({implements:[chain,events,options],options:{url:"",data:"",headers:{"x-requested-with":"xmlhttprequest",accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",issuccess:null,emulation:true,urlencoded:true,encoding:"utf-8",evalscripts:false,evalresponse:false,nocache:false},initialize:function(a){this.xhr=new browser.request(); this.setoptions(a);this.options.issuccess=this.options.issuccess||this.issuccess;this.headers=new hash(this.options.headers);},onstatechange:function(){if(this.xhr.readystate!=4||!thi...
..."){var c=(this.options.encoding)?"; charset="+this.options.encoding:""; this.headers.set("content-type","application/x-www-form-urlencoded"+c);}if(this.options.nocache){var f="nocache="+new date().gettime();g=(g)?f+"&"+g:f; }var e=b.lastindexof("/");if(e>-1&&(e=b.indexof("#"))>-1){b=b.substr(0,e);}if(g&&a=="get"){b=b+(b.contains("?")?"&":"?")+g;g=null;}this.xhr.open(a.touppercase(),b,this.options.async); this.xhr.onreadystatechange=this.onstatechange.bind(this);this.headers.each(function(m,l){try{this.xhr.setrequestheader(l,m);}catch(n){this.fireevent("exception",[l,m]); }},this);this.fireevent("request");this.xhr.send(g);if(!this.options.async){this.onstatechange();}return this;},cancel:function(){if(!this.running){return this; }this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$...
..."); b.send({data:this,url:a||b.options.url});return this;}});request.html=new class({extends:request,options:{update:false,append:false,evalscripts:true,filter:false},processhtml:function(c){var b=c.match(/<body[^>]*>([\s\s]*?)<\/body>/i); c=(b)?b[1]:c;var a=new element("div");return $try(function(){var d="<root>"+c+"</root>",g;if(browser.engine.trident){g=new activexobject("microsoft.xmldom"); g.async=false;g.loadxml(d);}else{g=new domparser().parsefromstring(d,"text/xml");}d=g.getelementsbytagname("root")[0];if(!d){return null;}for(var f=0,e=d.childnodes.length; f<e;f++){var h=element.clone(d.childnodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response; b.html=d.stripscripts(function(e){b.javascript=e;});var a=this.processhtm...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
rsion of firefox they were implemented in. ...
...were implemented in. ...
...t 2016 array.prototype.includes() (firefox 43) typedarray.prototype.includes() (firefox 43) exponentiation operator (firefox 52) ecmascript 2017 object.values() (firefox 47) object.entries() (firefox 47) string.prototype.padstart() (firefox 48) string.prototype.padend() (firefox 48) object.getownpropertydescriptors() (firefox 50) async functions async function (firefox 52) async function expression (firefox 52) asyncfunction (firefox 52) await (firefox 52) trailing commas in function parameter lists (firefox 52) ecmascript 2018 spread in object literals and rest parameters (firefox 55) for await...of (firefox 57) global_objects/sharedarraybuffer (firefox 57, with flags) global_objects/promise/finally (firefox 58) global_objects/regexp/dotall (not yet...
Index - Game development
shaders use glsl (opengl shading language), a special opengl shading language with syntax similar to c. glsl is executed directly by the graphics pipeline. there are two types of shaders: vertex shaders and fragment (pixel) shaders. vertex shaders transform shape positions into 3d drawing coordinates. fragment shaders compute the renderings of a shape's colors and other attributes. ...
...pengl shading language with syntax similar to c. glsl is executed directly by the graphics pipeline. there are two types of shaders: vertex shaders and fragment (pixel) shaders. vertex shaders transform shape positions into 3d drawing coordinates. fragment shaders compute the renderings of a shape's colors and other attributes. ...
...e graphics pipeline. there are two types of shaders: vertex shaders and fragment (pixel) shaders. vertex shaders transform shape positions into 3d drawing coordinates. fragment shaders compute the renderings of a shape's colors and other attributes. 25 async scripts for asm.js games, javascript, asm.js, async every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascript.options.parallel_p...
Audio for Web games - Game development
id="clavi-play-label">play</span> </button> </li> </ul> <p class="sourced">all tracks sourced from <a href="http://jplayer.org/">jplayer.org</a></p> </section> all of these tracks are the same tempo and are designed to be synchronized with each other, so we need to make sure they are loaded and available to the api before we are able to play them. we can do this with javascript's async/await functionality. once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can har...
...ndow.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing. l...
...s 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. we need an offset here, so if we have started ...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
e and execute nameel.focus(). the problem here is that svelte hasn't yet updated the dom. one way to solve this problem is to use settimeout() to delay the call to nameel.focus() until the next event cycle, and give svelte the opportunity to update the dom. try this now: function onedit() { editing = true // enter editing mode settimeout(() => nameel.focus(), 0) // asynchronous call to set focus to name input } the above solution works, but it is rather inelegant. svelte provides a better way to handle these cases. the tick() function returns a promise that resolves as soon as any pending state changes have been applied to the dom (or immediately, if there are no pending state changes). let's try it now. first of all, import tick at the top of the <script>...
...tter way to handle these cases. the tick() function returns a promise that resolves as soon as any pending state changes have been applied to the dom (or immediately, if there are no pending state changes). let's try it now. first of all, import tick at the top of the <script> section alongside your existing import: import { tick } from 'svelte' next, call tick() with await from an async function; update onedit() like so: async function onedit() { editing = true // enter editing mode await tick() nameel.focus() } if you try it now you'll see that everything works as expected. note: to see another example using tick(), visit the svelte tutorial. adding functionality to html elements with the use:action directive next up, we want the na...
...element like textinput, myinput or similar. moreover, you can add as many use:action directives as you want to an element. also, we didn't have to struggle with onmount(), ondestroy() or tick() — the use directive takes care of the component lifecycle for us. other actions improvements in the previous section, while working with the todo components, we had to deal with bind:this, tick(), and async functions just to give focus to our <input> as soon as it was added to the dom. this is how we can implement it with actions instead: const focusoninit = (node) => node && typeof node.focus === 'function' && node.focus() and then in our markup we just need to add another use: directive: <input bind:value={name} use:selectonfocus use:focusoninit ... our onedit() function ca...
Handling common JavaScript problems - Learn web development
each one reports i as 11, because for loops do all their iterating before nested functions are invoked. if you want this to work correctly, you need to define a function to add the handler separately, calling it on each iteration and passing it the current value of para and i each time (or something similar). see good-for-loop.html (see the source code also) for a version that works. making sure asynchronous operations have returned before trying to use the values they return. for example, this ajax example checks to make sure the request is complete and the response has been returned before trying to use the response for anything. this kind of operation has been made easier to handle by the introduction of promises to the javascript language. note: buggy javascript code: the 10 most common...
...age to the console. try inserting the following line just below line 31 (bolded above): console.log('response value: ' + superheroes); refresh the page in the browser, and you will get an output in the console of "response value:", plus the same error message we saw before the console.log() output shows that the superheroes object doesn't appear to contain anything. a very common problem with async requests like this is when you try to do something with the response object before it has actually been returned from the network. let's fix this problem by running the code once the load event has been fired — remove the console.log() line, and update this code block: let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); to the following: request.onload =...
... number of modern javascript language features defined in recent versions of the specs (ecmascript 6 / ecmascript next) that simply won't work in older browsers. some of these are syntactic sugar (basically an easier, nicer way of writing what you can already do using existing features), and some offer interesting new possibilities. for example: promises are a great new feature for performing asynchronous operations and making sure those operations are complete before code that relies on their results is used for something else. as an example, the fetch api (a modern equivalent to xmlhttprequest) uses promises to fetch resources across the network and make sure that the response has been returned before they are used (for example, displaying an image inside an <img> element). they are not s...
Creating Sandboxed HTTP Connections
onstartrequest - gets called when a new request is initiated. ondataavailable - new data i...
...ce.newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's newchannelfromuri method: // get a channel for that nsiuri var channel = ioservice.newchannelfromuri(uri); to initiate the connection, the asyncopen method is called. it takes two arguments: a listener and a context that is passed to the listener's methods. channel.asyncopen(listener, null); http notifications the above mentioned listener is a nsistreamlistener, which gets notified about events such as http redirects and data availability. onstartrequest - gets called when a new request is initiated. ondataavailable - new data is available. since this is a stream, it could be called multiple times (depending on the size of the returned data, networking c...
...ents.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); // get a channel for that nsiuri gchannel = ioservice.newchannelfromuri(uri); // get an listener var listener = new streamlistener(callbackfunc); gchannel.notificationcallbacks = listener; gchannel.asyncopen(listener, null); function streamlistener(acallbackfunc) { this.mcallbackfunc = acallbackfunc; } streamlistener.prototype = { mdata: "", // nsistreamlistener onstartrequest: function (arequest, acontext) { this.mdata = ""; }, ondataavailable: function (arequest, acontext, astream, asourceoffset, alength) { var scriptableinputstream = components.classes["@mozilla.o...
Frame script loading and lifetime
he message manager (which is the global this), and sending a message. if you did not set the third argument to true in bootstrap.js on services.mm.addmessagelistener, sending this message during, and after, the unloading event will do nothing. ...
...elling them to disable themselves; for example, by undoing any changes they've made or removing any event listeners. there is a bug in non-e10s where this order is not true. in e10s framescripts work fine on updating. for non-e10s waiting for bug 1202125 - framescripts are not backwards loaded in message order in non-e10s. ...
... at the moment, frame scripts are cached until the browser restarts: this problem is tracked as bug 1051238. ...
Download
any time, even if the download failed or is currently in progress. promise showcontainingdirectory(); parameters none. promise resolves to undefined when the instruction to open the containing folder has been successfully given to the operating system. note that the os might still take a while until the folder is actually opened. cancel() cancels the download. the cancellation request is asynchronous. until the cancellation process finishes, temporary files or part files may still exist even if they are expected to be deleted. in case the download completes successfully before the cancellation request could be processed, this method has no effect, and it returns a resolved promise. you should check the properties of the download at the time the returned promise is resolved to determin...
...d it returns a resolved promise. you should check the properties of the download at the time the returned promise is resolved to determine if the download was canceled. calling this method when the download has been completed successfully, failed, or has been canceled has no effect, and the method returns a resolved promise. this behavior is designed for the case where the call to cancel happens asynchronously, and is consistent with the case where the cancellation request could not be processed in time. promise cancel(); parameters none. promise resolves to undefined when the cancellation process has finished. promise can be rejected with never rejected. removepartialdata() removes any partial data kept as part of a canceled or failed download. if the download is not canceled or fa...
...l data kept as part of a canceled or failed download. after this method has been called, the download cannot be started again. note: this method should be used in place of the cancel() and removepartialdata() methods while shutting down or disposing of the download object, to prevent other callers from interfering with the operation. this is required because cancellation and other operations are asynchronous. promise finalize( boolean aremovepartialdata ); parameters aremovepartialdata optional whether any partially downloaded data should be removed after the download has been stopped. the default is false. promise resolves to undefined when the operation has finished successfully. ...
Optimizing Applications For NSPR
combined (mxn) model, which includes nt, irix (sprocs), and pthreads-user, the primordial thread is always a local thread. therefore, if you call a blocking system call from the primordial thread, it is going to block more than just the primordial thread and the system may not function correctly. on nt, this problem is especially obvious because the idle thread, which is in charge of driving the asynch io completion port, is also blocked. do not call blocking system calls from the primordial thread. create a global thread and call the system call in that thread, and have the primordial thread join that thread. nspr uses timer signals to implement thread preemption for local threads on some platforms. if all the software linked into the application is not ported to the nspr api, the applicatio...
...ion has dependencies on libraries that are implemented in the netscape communicator. the work to undo this dependency has already been started and the result will be made available soon. macintosh threads are not preemptable. as usual, it isn't that we couldn't preempt them, but rather that the macintosh libraries are not prepared for such things to happen. nspr does take advantage of macintosh' asynchronous i/o capability to perform scheduling during i/o. still, there is no enforceable mechanism to guarantee thread scheduling fairness. calendar time facilities are limited on macintosh. one can only determine the immediate setting of daylight savings time, not what it would be at some arbitrary time in the past or the future. initialization of nspr may fail if the host is not connected to a ...
... on either win-nt or win-95. win-95 nspr uses native threads as nspr threads. generally speaking, the native threads (on nt or '95) are quite functional. however, having lots of them (100s or even 1000s) is unrealistic. <tt>pr_interrupt()</tt> is not implemented. win-nt the win-nt port of nspr takes advantage of some of the features of nt that are not available in win-95, such as fibers and asynch i/o. the implementation is well suited for high performance application, such as a server, but clients may find the win-95 version more suited (and adequate) for interactive applications such as are prevalent on today's workstations. the nt version implements a mxn threading model, using native nt threads as the virtual processors and nt's fiber abstraction as the locally scheduled threads. th...
Necko Architecture
nels it creates can reuse them later. the channel does the true work of protocol interpretation and data movement (if any). although the protocol handler creates channels, protocol interpretation doesn't begin until the user initiates the transaction using the nsichannel api. receiving data & nsistreamlistener you can read or write, from or to a channel using either the synchronous api, or the asynchronous api. if you want to move data asynchronously you need to be able to receive callbacks using an implementation of nsistreamlistener. an nsistreamlistener is told when the uri transaction has "started," when data is available (in the case of reading data), and when it has "stopped." it is up to the nsistreamlistener implementation to decide what to do with these various notifications. the on...
...be used. as a user, you don't care where the data came from, or where it "is," as long as you get the data. the data may be in memory, it may be on disk, or it may be located somewhere else. the point is that streams provide a loose interface for data access. if you initiate a synchronous transfer on a channel, you are handed back a stream that you can read or write from or to. if you initiate an asynchronous transfer, you receive callbacks that notify you when things are happening. in the case of an asynchronous read... when you receive the ondataavailable() callback, you are handed an nsiinputsteam which you can read the data from (you will more than likely need to be able to handle multiple ondataavailable() callbacks, buffering the data you receive as necessary). the transaction is not comp...
...ur protocol handler and ask it for a channel. after registering your protocol handler necko will use it to create channels for any uris it encounters that have the scheme your protocol handler registered for. please use existing protocol handler's for reference (the data: protocol handler is the simplest handler necko provides, http is a fairly complex (uses many classes) implementation utilizing asynchronous i/o, and ftp provides an example of a protocol implementation that creates an extra thread which uses synchronous i/o). dependencies necko requires the following libraries for linking: nspr xpcom original document information author(s): jud valeski last updated date: november 8, 1999 copyright information: portions of this content are © 1998–2007 by individual mozilla.org c...
Multithreading in Necko
thread to kick off pending requests well before the main thread would get around to doing so. socket transport thread (1) socket connections are processed on a single background thread. this thread is controlled by the nssockettransportservice. it sits in a loop, polling a list of sockets. when a socket can be read, the socket's listener is notified either synchronously (on the same thread) or asynchronously via a nsistreamlistenerproxy impl. file transport threads (1-4) file i/o is processed via a thread pool that has between 1 and 4 threads. these threads are controlled by the nsfiletransportservice. each file transport object is given time on one of the file transport threads. during which it reads (writes) until its buffers are full (empty). once at the limit of its buffers, it yields...
...threads. these threads are controlled by the nsfiletransportservice. each file transport object is given time on one of the file transport threads. during which it reads (writes) until its buffers are full (empty). once at the limit of its buffers, it yields the thread to another pending file transport object. as with the socket transport thread, the nsistreamlistener passed to a file transport's asyncread method can operate partially on the file transport's thread before proxying data to the main thread. the file transport is confusingly named since it is not restricted to loading files. it simply promises to read from a nsiinputstream (or write to a nsioutputstream) on a background thread. the implementation of the stream should be blocking; however, there is limited support for non-blocking ...
...service. the jar protocol handler, for rexample, passes a special nsiinputstream impl that does gzip decoding on the fly. dns thread (0-1) on most platforms dns requests a processed on a background thread. however, the details of the implementation are heavily platform dependent. for example, on xp_win an invisible window is created with a message pump on a background thread for processing wsa asynchronous dns events. in this way, necko takes advantage of the platforms specific routines for dns lookups. the default implementation does not spawn a worker thread, and instead simply calls pr_getipnodebyname (essentially equivalent to gethostbyname). original document information author(s): darin fisher last updated date: december 10, 2001 copyright information: portions of this content a...
Gecko events
efined in nsiaccessibleevent interface. event_dom_create an object has been created. is supported: yes event_dom_destroy an object has been destroyed. is supported: yes event_dom_significant_change an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated. ...
...eated. is supported: yes event_dom_destroy an object has been destroyed. is supported: yes event_dom_significant_change an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated. ...
...stroy an object has been destroyed. is supported: yes event_dom_significant_change an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated. is supported: yes event_asynch_show a hidden object is shown -- this is a layout occurance and is thus asynchronous is supported: yes event_asynch_hide an object is hidden -- this is a layout occurance and is thus asynchronous is supported: yes event_asynch_significant_change an object had a significant layout change which could affect the type of accessible object -- this is a layout occurance and is thus asynchronous is supported: yes event_active_decendent_changed the active descendant of a component has changed. the active descend...
Making cross-thread calls using runnables
typically, thread activities are triggered and managed using an xpcom event-passing framework that uses the nsirunnable interface. each runnable represents a task which can then be dispatched to another thread for execution. note: javascript code cannot use the techniques described in this article. chrome javascript should instead use workers. ...
...hould be asynchronous. for example, let's say we have a function, calculatepi(int digits), which will calculate π to an arbitrary number of digits: void calculatepi(int digits, nscstring& result); // this is synchronous this can take a while, so we don't want to run this on the main thread. instead, we want to run it on a new thread and be notified when the result is available. so we declare an asynchronous version of the same function: typedef void (*picallback)(const nscstring& result); // callback function void calculatepiasynchronously(int digits, picallback callback); creating a runnable nsrunnable is a helper class: it already implements threadsafe refcounting, so all you need to do is override the run() function. in our example, we actually need two runnables: one dispatched to the wo...
...) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable = new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(...
mozIVisitStatusCallback
implement this method to determine the results of the request. void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. ...
...implement this method to determine the results of the request. void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. ...
...rivisited() method's check to determine whether a given uri has been visited has completed. implement this method to determine the results of the request. void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified uri has been visited; otherwise false. see also moziasynchistory ...
nsIFeedProcessor
introduced gecko 1.8.1 inherits from: nsistreamlistener last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by: @mozilla.org/feed-processor;1. ...
... void parseasync(in nsirequestobserver requestobserver, in nsiuri uri); void parsefromstream(in nsiinputstream stream, in nsiuri uri); void parsefromstring(in astring str, in nsiuri uri); attributes attribute type description listener nsifeedresultlistener the feed result listener that will respond to feed events. methods parseasync() parses a feed asynchronously. the caller must then call the processor's nsistreamlistener methods to drive the parsing process. you must not call any of the other parsing methods on the nsifeedprocessor interface during an asynchronous parse. ...
...this can be null. uri the base uri against which any uris in the feed are resolved. ...
nsIHttpUpgradeListener
alled when an http protocol upgrade is finished. 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) this is used, for example, by websockets in order to upgrade an http channel to use the websocket protocol. method overview void ontransportavailable(in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout); methods ontransportavailable() called when an http protocol upgrade attempt is completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by http. note: to begin a protocol upgrade, call nsihttpchannelinternal.httpupgrade(). void ontransportavailable( in nsisockettr...
...iasyncoutputstream asocketout); methods ontransportavailable() called when an http protocol upgrade attempt is completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by http. note: to begin a protocol upgrade, call nsihttpchannelinternal.httpupgrade(). void ontransportavailable( in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout ); parameters atransport the nsisockettransport describing the socket connection between the browser and the server; this socket can now be used for the new protocol instead of http. asocketin the nsiasyncinputstream object representing the input stream for data coming from the server over the socket connection. asoc...
...tin, in nsiasyncoutputstream asocketout ); parameters atransport the nsisockettransport describing the socket connection between the browser and the server; this socket can now be used for the new protocol instead of http. asocketin the nsiasyncinputstream object representing the input stream for data coming from the server over the socket connection. asocketout the nsiasyncoutputstream object representing the out stream for sending data to the server over the socket. ...
nsIInputStreamCallback
xpcom/io/nsiasyncinputstream.idlscriptable this is a companion interface for nsiasyncinputstream.asyncwait(). inherits from: nsisupports last changed in gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready() called to indicate that the stream is either readable or closed. void oninputstreamready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was called. ...
... last changed in gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready() called to indicate that the stream is either readable or closed. ...
...gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready() called to indicate that the stream is either readable or closed. void oninputstreamready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was called. ...
nsIPipe
eam and written using nsioutputstream. inherits from: nsisupports last changed in gecko 1.6 method overview void init(in boolean nonblockinginput, in boolean nonblockingoutput, in unsigned long segmentsize, in unsigned long segmentcount, in nsimemory segmentallocator); attributes attribute type description inputstream nsiasyncinputstream the pipe's input end, which also implements nsisearchableinputstream. read only. outputstream nsiasyncoutputstream the pipe's output end. read only. methods init() initialize this pipe. void init( in boolean nonblockinginput, in boolean nonblockingoutput, in unsigned long segmentsize, in unsigned long segmentcount, in nsimemory segme...
... if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the error condition. however, if that pipe's input end is blocking, then the read call will not return until the pipe has data or until the pipe is closed. ...
...osed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the error condition. however, if that pipe's input end is blocking, then the read call will not return until the pipe has data or until the pipe is closed. this example presumes that the pipe is being filled asynchronously on some background thread. the pipe supports nsiasyncinputstream and nsiasyncoutputstream, which give the user of a non-blocking pipe the ability to wait for the pipe to become ready again. for example, in the case of an empty non-blocking pipe, the user can call nsiasyncinputstream.asyncwait() on the input end of the pipe to be notified when the pipe has data to read (or when the pipe becomes closed). ns_newpipe2() and ns_newpipe() provide convenie...
nsIProcess
s = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); method overview void init(in nsifile executable); void initwithpid(in unsigned long pid); obsolete since gecko 1.9.2 void kill(); void run(in boolean blocking, [array, size_is(count)] in string args, in unsigned long count); void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); void runw(in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count); void runwasync([array, size_is(count)] in wstring args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); ...
... in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using the native character set, to be passed to the executable on its command line. count the number of arguments in the args array. runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set. thi...
...ith. void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using utf-16, to be passed to the executable on its command line. count the number of arguments in the args array. runwasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runwasync( [array, size_is(count)] in wstring args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using utf-16. this array must hav...
nsIProcess2
.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) gecko 1.9.2 note this interface was removed in gecko 1.9.2 and its method added to nsiprocess. implemented by: @mozilla.org/process/util;1. ...
...emented by: @mozilla.org/process/util;1. to create an instance, use: var process2 = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2); method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); methods runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. ...
...this array must have count entries. ...
nsIProtocolProxyCallback
netwerk/base/public/nsiprotocolproxycallback.idlscriptable this interface serves as a closure for nsiprotocolproxyservice.asyncresolve(). 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onproxyavailable(in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus); methods onproxyavailable() this method is called when proxy info is available or when an error in the proxy resolution occurs. void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve. auri the uri...
...info, in nsresult astatus); methods onproxyavailable() this method is called when proxy info is available or when an error in the proxy resolution occurs. void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve. auri the uri passed to asyncresolve. aproxyinfo the resulting proxy info or null if there is no associated proxy info for auri. as with the result of nsiprotocolproxyservice's resolve method, a null result implies that a direct connection should be used. astatus the status of the callback. this is a failure code if the request could not be satisfied, in which case the value of astatus indicates th...
... no associated proxy info for auri. as with the result of nsiprotocolproxyservice's resolve method, a null result implies that a direct connection should be used. astatus the status of the callback. this is a failure code if the request could not be satisfied, in which case the value of astatus indicates the reason for the failure and aproxyinfo will be null. the value returned from asyncresolve. see also nsicancelable nsiuri nsiproxyinfo nsiprotocolproxyservice ...
nsISupports proxies
this technology has been removed in firefox 12 because it was very complex and often lead to strange deadlock conditions. ...
... only use an object remotely, but also have it created remotely, use the second api. the iid that you are requesting must be in the typelib. these means that you should have had to create and idl for it and have generated a typelib. if you haven't, or you've never heard of these things, see http://www.mozilla.org/scriptable/ . the proxytype parameter can be either two flags: proxy_sync or proxy_async. these two flags can also be ored with proxy_always. proxy_always will ensure that a proxy object is always created no matter what thread you currently are on. if this flag is not specified, the proxy object manager will compare the eventq which you pass to the eventq which is on the current thread. if they match, it will return the real non-proxied object. most of the time you will want to set ...
...he proxy object manager will compare the eventq which you pass to the eventq which is on the current thread. if they match, it will return the real non-proxied object. most of the time you will want to set this flag. proxy_sync acts just like a function call in that it blocks the calling thread until the the method is invoked on the destination thread. this is the normal and default case. proxy_async, on the other hand, is a "fire and forget" method call. calls on object created with this flag will return immediately and you will lose all return information. ns_ok will be returned to you. warning about proxy_async: you must take very special care when using this flag. as soon as the calling function or method exits, there is no guarantee about the data at the location that used to be part ...
nsIWebProgressListener
inherits from: nsisupports last changed in gecko 15 (firefox 15 / thunderbird 15 / seamonkey 2.12) nsiwebprogress describes the parent-child relationship of nsiwebprogress instances. ...
...esslistener", "nsisupportsweakreference"]), onstatechange: function(awebprogress, arequest, aflag, astatus) { let win = awebprogress.domwindow; let outerwindowid = win.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindowutils) .outerwindowid; sendasyncmessage("myaddonmessage", { name: "onstatechange", flag: aflag, status: astatus, }); }, onlocationchange: function(aprogress, arequest, auri, aflag) { let win = awebprogress.domwindow; let outerwindowid = win.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindowutils) ...
..."onstatechange", flag: aflag, status: astatus, }); }, onlocationchange: function(aprogress, arequest, auri, aflag) { let win = awebprogress.domwindow; let outerwindowid = win.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindowutils) .outerwindowid; sendasyncmessage("myaddonmessage", { name: "onlocationchange", outerwindowid: outerwindowid, uri: auri.spec, charset: auri.charset, flag: aflag, }); }, // for definitions of the remaining functions see related documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuscha...
nsIWebSocketChannel
gecko 8.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by: ?????????????????????????????????????. ...
...t is, with no close frame being sent) when a status code is expected. 1007-1999 reserved for future use by the websocket standard. 2000-2999 reserved for use by websocket extensions. 3000-3999 available for use by libraries and frameworks. may not be used by applications. 4000-4999 available for use by applications. methods asyncopen() asynchronously opens the websocket connection. received messages are fed to the socket listener as they arrive. the socket listener's methods are called on the thread that calls asyncopen() and are not called until after asyncopen() returns. if asyncopen() returns successfully, the protocol implementation promises to call at least onstart and onstop of the listener. note: implementations sh...
... aorigin the uri of the originating resource. ...
nsIXmlRpcClient
null ...
... if asked to authenticate clearauthentication() clear authentication info void setauthentication ( in string username, in string password ) ; parameters username password setencoding() set character encoding. the default charset if this function is not called is "utf-8" void setauthentication ( in string encoding ) ; parameters encoding encoding charset to be used asynccall() call remote method methodname asynchronously with given arguments. supported arguments are: nsisupportspruint8, nsisupportspruint16, nsisupportsprint16, nsisupportsprint32: i4, nsisupportsprbool: boolean, nsisupportschar, nsisupportscstring: string, nsisupportsfloat, nsisupportsdouble: double, nsisupportsprtime: datetime.iso8601, nsiinputstream: base64, nsisupportsarray: array, nsidictionar...
...by returning ns_error_failure. via nsixpconnect::getpendingexception()->data a nsixmlrpcfault object can be retreieved with more information on the fault. parameters listener a nsixmlrpcclientlistener that will get notified of xml-rpc events ctxt a context to be passed on to the listener methodname remote method to call arguments array of arguments to pass to the remote method count void asynccall ( in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, [array, size_is(count)] in nsisupports arguments, in pruint32 count ); createtype() convenience: return the correct nsisupportsprimitive for a given xml-rpc type, or nsisupportsarray or nsidictionary. 'base64' isn't supported. no queryinterface call is needed, the object has been quer...
Mail composition back end
s implemented by the caller. the caller has the ability to add or remove listener interfaces to the nsimsgsend object and the interface can support multiple listeners. (for detailed information on the listener interfaces, see the listener interfaces section of this document) nsimsgsend the following describes the methods of the nsimsgsend interface. all of these methods are asynchronous operations. createandsendmessage the createandsendmessage method will create an rfc822 message and send it all in one operation as well as providing the ability to save disk files for later use. the mode of delivery can also be specified for the "send later", "drafts" and "templates" operations. (note: this method could easily be broken in to a few different calls. c...
...move listeners to the sending interface. ns_imethod addlistener(nsimsgsendlistener *alistener) = 0; ns_imethod removelistener(nsimsgsendlistener *alistener) = 0; sending listener interfaces the nsimsgsendlistener interface will let a caller keep track of the progress and any status of a send operation. these are critical for message delivery since message sending is asynchronous. it is the only way to determine if the operation was successful or not. an important item to note is the fact that this interface should also implement the nsimsgcopyservicelistener interface if it wants to be notified of the progress and completion of the copy operation. nsimsgsendlistener the following describes the methods of the nsimsgsendlistener interface: ...
...er defined "unsent messages or drafts" folder. (see send later above) the nsimsgsendlater is the interface that allows the caller to send all of the files previously stored. the caller will implement an nsimsgsendlaterlistener interface to monitor the progress of the send operations. the following describes the methods of the nsimsgsendlater interface. this method is performs the send operations asynchronously. the sendunsentmessages method will send all queued messages. ns_imethod sendunsentmessages(nsimsgidentity *identity, - the user identity for the person doing the send operation. this will be needed to determine the appropriate folder for copy operations. nsimsgsendlaterlistener **listenerarray) = 0; - an array of listeners for the send...
CacheStorage - Web APIs
vent.request, responseclone); }); return response; }).catch(function () { return caches.match('/sw-test/gallery/mylittlevader.jpg'); }); } })); }); this snippet shows how the api can be used outside of a service worker context, and uses the await operator for much more readable code. // try to get data from the cache, but fall back to fetching it live. ...
... cachename, url ); if ( cacheddata ) { console.log( 'retrieved cached data' ); return cacheddata; } console.log( 'fetching fresh data' ); const cachestorage = await caches.open( cachename ); await cachestorage.add( url ); cacheddata = await getcacheddata( cachename, url ); await deleteoldcaches( cachename ); return cacheddata; } // get data from the cache. ...
...cachedresponse || ! ...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
turn value returns a promise that resolves with undefined exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent. if the id, title, description or url are missing, not of type string, or an empty string. if icons images are not of image type. examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; ...
... function which uses the add method to register it with the content index. ...
...er it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope. // our cont...
Using files from web applications - Web APIs
age, so that doesn't need to be done here. each image has the css class obj added to it, making it easy to find in the dom tree. we also add a file attribute to each image specifying the file for the image; this will let us fetch the images for actual upload later. we use node.appendchild() to add the new thumbnail to the preview area of our document. next, we establish the filereader to handle asynchronously loading the image and attaching it to the img element. after creating the new filereader object, we set up its onload function and then call readasdataurl() to start the read operation in the background. when the entire contents of the image file are loaded, they are converted into a data: url which is passed to the onload callback. our implementation of this routine sets the img element...
...g the url.revokeobjecturl() method and passing in the object url string as specified by img.src. append the new list item to the list. here is a live demo of the code above: example: uploading a user-selected file another thing you might want to do is let the user upload the selected file or files (such as the images selected using the previous example) to a server. this can be done asynchronously very easily. creating the upload tasks continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the css class obj with the corresponding file attached in a file attribute. this allows us to select all of the images the user has chosen for uploading using document.queryselectorall(), like this: function sendfiles() { const im...
...e type for the upload is set by calling the xmlhttprequest function overridemimetype(). in this case, we're using a generic mime type; you may or may not need to set the mime type at all depending on your use case. the filereader object is used to convert the file to a binary string. finally, when the content is loaded the xmlhttprequest function send() is called to upload the file's content. asynchronously handling the file upload process this example, which uses php on the server side and javascript on the client side, demonstrates asynchronous uploading of a file. <?php if (isset($_files['myfile'])) { // example: move_uploaded_file($_files['myfile']['tmp_name'], "uploads/" . $_files['myfile']['name']); exit; } ?><!doctype html> <html> <head> <title>dnd binary upload</ti...
History - Web APIs
Web › API › History
allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. state read only returns an any value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. methods the history interface doesn't inherit any methods. ...
... popstate event. methods the history interface doesn't inherit any methods. back() this asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's back button. equivalent to history.go(-1). calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception. forward() this asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's forward button; this is equivalent to history.go(1). calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception. ...
...e in the session history has no effect and doesn't raise an exception. forward() this asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's forward button; this is equivalent to history.go(1). calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception. go() asynchronously loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1 for the next page. if you specify an out-of-bounds value (for instance, specifying -1 when there are no previously-visited pages in the session history), this method silently has no effect. calling go() without parameters or a value of 0 reloads the cu...
IndexedDB API - Web APIs
ipt-based object-oriented database. indexeddb lets you store and retrieve objects that are indexed with a key; any objects supported by the structured clone algorithm can be stored. you need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of transactions. read more about the concepts behind indexeddb. learn to use indexeddb asynchronously from first principles with our using indexeddb guide. combine indexeddb for storing data offline with service workers for storing assets offline, as outlined in making pwas work offline with service workers. note: like most web storage solutions, indexeddb follows a same-origin policy. so while you can access stored data within a domain, you cannot access data across different domain...
...principles with our using indexeddb guide. combine indexeddb for storing data offline with service workers for storing assets offline, as outlined in making pwas work offline with service workers. note: like most web storage solutions, indexeddb follows a same-origin policy. so while you can access stored data within a domain, you cannot access data across different domains. synchronous and asynchronous operations performed using indexeddb are done asynchronously, so as not to block applications. indexeddb originally included both synchronous and asynchronous apis. the synchronous api was intended for use only with web workers but was removed from the spec because it was unclear whether it was needed. however, the synchronous api may be reintroduced if there is enough demand from web dev...
... out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. browser storage limits and eviction criteria attempts to explain how this works, at least in the case of firefox. interfaces to get access to a database, call open() on the indexeddb attribute of a window object. this method returns an idbrequest object; asynchronous operations communicate to the calling application by firing events on idbrequest objects. connecting to a database idbenvironment provides access to indexeddb functionality. it is implemented by the window and worker objects. this interface isn't part of the 2.0 specification. idbfactory provides access to a database. this is the interface implemented by the global object indexeddb ...
PaymentRequest.shippingOption - Web APIs
option. syntax // returns the id of the selected paymentshippingoption var shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched. in each calls to updatedetails() are made, one using a promise, and the other with a plain js object. ...
...ption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched. in each calls to updatedetails() are made, one using a promise, and the other with a plain js object. this demotrates synchrounous and asynchronous updates to a payment sheet. ...
...we can't ship to your address.` }; } } specifications specification status ...
RTCPeerConnection.setLocalDescription() - Web APIs
the rtcpeerconnection method setlocaldescription() changes the local description associated with the connection. this description specifies the properties of the local end of the connection, including the media format. the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously. if setlocaldescription() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setlocaldescription() does not immediately take effect. instead, the current connection configuration remains in place until negotiation ...
...examples implicit descriptions one of the advantages of the parameter-free form of setlocaldescription() is that it lets you simplify your negotiation code substantially. this is all your negotiationneeded event handler needs to look like, for the most part. just add the signaling server code, which here is represented by the call to signalremotepeer(). ...
...listener("negotiationneeded", async (event) => { await pc.setlocaldescription(); signalremotepeer({ description: pc.localdescription }); }); other than error handling, that's about it! providing your own offer or answer the example below shows the implementation of a handler for the negotiationneeded event that explicitly creates an offer, rather than letting setlocaldescription() do it. async function handlenegotiationneededevent() { try { await offer = pc.createoffer(); pc.setlocaldescription(offer); signalremotepeer({ description: pc.localdescription }); } catch(err) { reporterror(err); } } this begins by creating an offer by calling createoffer(); when that succeeds, we call setlocaldescription(). we can then send the newly-created offer along to the other pe...
Screen Wake Lock API - Web APIs
('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object. ...
....textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object. the wakelock.request method is promise based and so we can create an asynchronous function, which in turn updates the ui to reflect the wake lock is active. ...
...} requesting a wake lock the following example demonstrates how to request a wakelocksentinel object. the wakelock.request method is promise based and so we can create an asynchronous function, which in turn updates the ui to reflect the wake lock is active. ...
WakeLockSentinel - Web APIs
are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. event handlers onrelease fired when the release() method is called or the wake lock is released by the user agent. methods release() releases the wakelocksentinel, returning a promise that is resolved once the sentinel has been successfully released. ...
...olved once the sentinel has been successfully released. examples in this example we create an asynchronous function which requests a wakelocksentinel. once acquired we listen for the onrelease event which can be used to give appropriate ui feedback. the sentinel can be acquired or released via appropriate interactions. ...
...ples in this example we create an asynchronous function which requests a wakelocksentinel. once acquired we listen for the onrelease event which can be used to give appropriate ui feedback. the sentinel can be acquired or released via appropriate interactions. ...
WritableStream.WritableStream() - Web APIs
yingsink an object containing methods and properties that define how the constructed stream instance will behave. underlyingsink can contain the following: start(controller) optional this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the underlying sink. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a writablestreamdefaultcontroller. this can be used by the developer to control the stream during set up. write(chunk, controller) optional this method, also defined by the developer, will be called when a new chunk of data (specified in the chunk parameter) is ready to be written...
...ed only after previous writes have succeeded, and never after the stream is closed or aborted (see below). close(controller) optional this method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. the contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. if this process is asynchronous, it can return a promise to signal success or failure. this method will be called only after all queued-up writes have succeeded. the controller parameter passed to this method is a writablestreamdefaultcontroller, which can be used to control the stream at the end of writing. abort(reason) optional this method, also defined by the developer, will be called if the app signals that it w...
... used to control the stream at the end of writing. abort(reason) optional this method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. it can clean up any held resources, much like close(), but abort() will be called even if writes are queued up — those chunks will be thrown away. if this process is asynchronous, it can return a promise to signal success or failure. the reason parameter contains a domstring describing why the stream was aborted. queuingstrategy optional an object that optionally defines a queuing strategy for the stream. this takes two parameters: highwatermark a non-negative integer — this defines the total number of chunks that can be contained in the internal queu...
HTML in XMLHttpRequest - Web APIs
ly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but before calling send(). var xhr = new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature. when you try to set responsetype of an xmlhttprequest object after it is opened as "sync". this throws an error in the browsers that implement the feature and works on others. function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'docum...
...true; } return false; } view on jsfiddle this method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. method 2 there are two challenges to detecting exactly if a browser supports html parsing in xmlhttprequest. first, the detection result is obtained asynchronously, because html support is only available in the asynchronous mode. second, you have to actually fetch a test document over http, because testing with a data: url would end up testing data: url support at the same time. thus, to detect html support, a test html file is needed on the server. this test file is small and is not well-formed xml: <title>&amp;&<</title> if the file is named d...
... view on jsfiddle character encoding if the character encoding is declared in the http content-type header, that character encoding is used. failing that, if there is a byte order mark, the encoding indicated by the byte order mark is used. failing that, if there...
Using XMLHttpRequest - Web APIs
ect will contain useful information such as the response body and the http status of the result. function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://www.example.org/example.txt"); oreq.send(); types of requests a request made via xmlhttprequest can fetch the data in one of two ways, asynchronously or synchronously. the type of request is dictated by the optional async argument (the third argument) that is set on the xmlhttprequest.open() method. if this argument is true or not specified, the xmlhttprequest is processed asynchronously, otherwise the process is handled synchronously. a detailed discussion and demonstrations of these two types of requests can be found on the synchron...
...do not use synchronous requests outside web workers. note: starting with gecko 30.0 (firefox 30.0 / thunderbird 30.0 / seamonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience. ...
...sts outside web workers. note: starting with gecko 30.0 (firefox 30.0 / thunderbird 30.0 / seamonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience. note: the constructor function xmlhttprequest isn't limited to only xml documents. it starts with "xml" because when it was created the main format that was originally used for asynchronous data exchange were xml handling responses there are several types of response attributes defined by the living standard specification for the xmlhttprequest() constructor. these tell the client making the xmlhttprequest important information about the status of the response. some cases where dealing with non-text response types may involve some manipulation and analysis are outlined in t...
Getting Started - Developer guides
this article guides you through the ajax basics and gives you some simple hands-on examples to get you started. what's ajax? ajax stands for asynchronous javascript and xml. in a nutshell, it is the use of the xmlhttprequest object to communicate with servers. it can send and receive information in various formats, including json, xml, html, and text files. ajax’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. the two major features of ajax allow you to do the following: make requests to the server without reloading the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server ...
...arty domains by default. be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call open(). a common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. if you really need to send a request to another domain, see http access control (cors). the optional third parameter sets whether the request is asynchronous. if true (the default), javascript execution will continue and the user can interact with the page while the server response has yet to arrive. this is the first a in ajax. the parameter to the send() method can be any data you want to send to the server if post-ing the request. form data should be sent in a format that the server can parse, like a query string: "name=value&anothername=...
...the http status code of the response, you can do whatever you want with the data the server sent. you have two options to access that data: httprequest.responsetext – returns the server response as a string of text httprequest.responsexml – returns the response as an xmldocument object you can traverse with javascript dom functions note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). if you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience. step 3 – a simple example let's put it all together with a simple http request. our javascript will request an html document, test.html, which contains the text "i'm a tes...
Array.prototype.forEach() - JavaScript
array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. ...
...find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. kindly make sure you are aware of the implications while using promises(or async functions) as foreach callback. ...
...dicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. kindly make sure you are aware of the implications while using promises(or async functions) as foreach callback. ...
Promise.any() - JavaScript
ors. essentially, this method is the opposite of promise.all(). warning! the promise.any() method is experimental and not fully supported by all browsers and platforms. it is currently in stage 4 of the tc39 process. syntax promise.any(iterable); parameters iterable an iterable object, such as an array. return value an already resolved promise if the iterable passed is empty. an asynchronously resolved promise if the iterable passed contains no promises. a pending promise in all other cases. this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected. description this method is useful for returning the first promise that fulfils. it short-circuits...
...n be beneficial if we need only one promise to fulfil but we do not care which one does. also, unlike promise.race(), which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value. this method will ignore all rejected promises up until the first promise that fulfils. fulfilment if any of the passed-in promises fulfil, the returned promise asynchronously fulfils with the value of the promise that fulfilled, whether or not the other promises have fulfilled or rejected. if an empty iterable is passed, then this method returns (synchronously) an already resolved promise. if any of the passed-in promises fulfill or are not promises, the promise returned by promise.any is fulfilled asynchronously. rejection if all of the passed-in prom...
...e value of the promise that fulfilled, whether or not the other promises have fulfilled or rejected. if an empty iterable is passed, then this method returns (synchronously) an already resolved promise. if any of the passed-in promises fulfill or are not promises, the promise returned by promise.any is fulfilled asynchronously. rejection if all of the passed-in promises reject, promise.any asynchronously rejects with an aggregateerror object, which extends error, and contains an errors property with an array of rejection values. examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first. this is in contrast to promise.race(), which resolves or rejects with the first promise to settle. const perr = new promise((resolve, reject) =>...
Promise.race() - JavaScript
e or reason from that promise. the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.race(iterable); parameters iterable an iterable object, such as an array. see iterable. return value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject. description the race function returns a promise that is settled the same way (and takes the same value) as the first promise that settles amongst the promises of the iterable passed as an argument. if the iterable passed is empty, the promise returned will be forever pending. if the iterable contains on...
... the same way (and takes the same value) as the first promise that settles amongst the promises of the iterable passed as an argument. if the iterable passed is empty, the promise returned will be forever pending. if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the iterable. ...
...es amongst the promises of the iterable passed as an argument. if the iterable passed is empty, the promise returned will be forever pending. if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the iterable. ...
Populating the page: how browsers work - Web Performance
hierarchies between different tags. tags nested within other tags are child nodes. the greater the number of dom nodes, the longer it takes to construct the dom tree. when the parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. parsing can continue when a css file is encountered, but <script> tags—particularly those without an async or defer attribute—block rendering, and pause the parsing of html. though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck. preload scanner while the browser builds the dom tree, this process occupies the main thread. as this happens, the preload scanner will parse through the content available and request high priority resources like...
...t have to wait until the parser finds a reference to an external resource to request it. it will retrieve resources in the background so that by the time the main html parser reaches requested assets, they may possibly already be in flight, or have been downloaded. the optimizations the preload scanner provides reduce blockages. ...
... retrieve resources in the background so that by the time the main html parser reaches requested assets, they may possibly already be in flight, or have been downloaded. the optimizations the preload scanner provides reduce blockages. <link rel="stylesheet" src="styles.css"/> <script src="myscript.js" async></script> <img src="myimage.jpg" alt="image description"/> <script src="anotherscript.js" async></script> in this example, while the main thread is parsing the html and css, the preload scanner will find the scripts and image, and start downloading them as well. to ensure the script doesn't block the process, add the async attribute, or the defer attribute if javascript parsing and execution order is not important. waiting to obtain css doesn't block html parsing or downloading, but it d...
Web Performance
ond, and time to become interactive, and subjective experiences of how long it felt like it took the content to load. the longer it takes for a site to respond, the more users will abandon the site. it is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. there are tools, apis, and best practices that help us measure and improve web performance. we cover them in this section: key performance guides animation performance and frame rateanimation on the web can be done via svg, javascript, including <canvas> and webgl, css animation, <video>, animated gifs and even animated pngs and...
...events. resource timings are detailed network timing measurements regarding the loading of an application's resources.optimizing startup performanceregardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single event handler on the app's main thread.performance budgetsa performance budget is a limit to prevent regressions. it can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. time to interactive), a custom metric (e.g. time to hero element), or a threshold over a period of time. performanc...
... used to help identify an application's performance bottlenecks. user timing api create application specific timestamps using the user timing api's "mark" and "measure" entry types - that are part of the browser's performance timeline. frame timing api the performanceframetiming interface provides frame timing data about the browser's event loop. beacon api the beacon interface schedules an asynchronous and non-blocking request to a web server. intersection observer api learn to time element visibility with the intersection observer api and be asynchronously notified when elements of interest becomes visible. other documentation developer tools performance features this section provides information on how to use and understand the performance features in your developer tools, incl...
content/worker - Archive of obsolete content
to a 'message' events. onerror function functions that will registered as a listener to an 'error' events. worker worker is composed from the eventemitter trait, therefore instances of worker and their descendants expose all the public properties exposed by eventemitter along with additional public properties that are listed below. methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object that allows you to: send customi...
...ssages to the worker using the port.emit function receive events from the worker using the port.on function url the url of the content. tab if this worker is attached to a content document, returns the related tab. events message this event allows the content worker to receive messages from its associated content scripts. calling the self.postmessage() function from a content script will asynchronously emit the message event on the corresponding worker. arguments value : the event listener is passed the message, which must be a json-serializable value. error this event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. arguments error : the event listener is passed a single argument which is an error object. detach ...
test/httpd - Archive of obsolete content
}) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox). ...
... }) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox). ...
Appendix D: Loading Scripts - Archive of obsolete content
ely limited, can't be passed javascript objects, and have no access to the dom. all communication between these contexts and outer contexts is marshalled through json encoding and decoding. chromeworkers also have access to ctypes and a limited number of thread safe xpcom classes, but are otherwise limited to simple computation based on data passed via messages and xmlhttprequests. advantages asynchronous: workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. they may safely perform synchronous xmlhttprequests or other intensive computation which would normally need to be broken up into multiple callbacks. safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly ...
...ted risk of interfering with the main thread. they may safely perform synchronous xmlhttprequests or other intensive computation which would normally need to be broken up into multiple callbacks. safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous execution. disadvantages limited scoping: as data from the main thread may only be accessed via json message passing, there are significant difficulties in performing many operations in worker scopes. dom access: as there is no dom access in worker scopes, xmlhttprequests may not easily be used with xml or html sources, and should instead only be used with json or other text-based so...
Performance best practices in extensions - Archive of obsolete content
defines a function on a specified object that acts as a getter which will be created the first time it's used. see examples. definelazyservicegetter() defines a function on a specified object which acts as a getter for a service. the service isn't obtained until the first time it's used. look through the source for examples. many common services are already cached for you in services.jsm. use asynchronous i/o this cannot be stressed enough: never do synchronous i/o on the main thread. any kind of i/o on the main thread, be it disk or network i/o, can cause serious ui responsiveness issues. never use synchronous xmlhttprequests. netutils.jsm provides helpers for asynchronous reading and copying of files. never access a sqlite database synchronously. use the asynchronous api instead. ...
...t be stressed enough: never do synchronous i/o on the main thread. any kind of i/o on the main thread, be it disk or network i/o, can cause serious ui responsiveness issues. never use synchronous xmlhttprequests. netutils.jsm provides helpers for asynchronous reading and copying of files. never access a sqlite database synchronously. use the asynchronous api instead. performing sequential, asynchronous operations can often be greatly simplified using promises. avoid mouse movement events avoid using mouse event listeners, including mouseover, mouseout, mouseenter, mouseexit, and especially mousemove. these events happen with high frequency, so their listeners can trivially create very high cpu overhead. when these events cannot be avoided, computation during the listeners should be k...
Helper Apps (and a bit of Save As) - Archive of obsolete content
o so. nsexternalapphandler::onstartrequest creates a temporary file with a salted name to hold the data. decides on a suggested filename for the data in case it will be saved. decides whether the data should be content-decoded (based on some not-so-great heuristics). decides whether the user should be prompted (based on a preference). calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog. nsexternalapphandler::ondataavailable here we just copy the newly arrived data over into our temporary file. if any read or write errors occur, abort the whole process: cancel the channel. pull down the helper app dialog (if any). remove the temp file. nsexternalapphandler::onstoprequest set a flag that we're done, then do whatever the user want...
...rom launching such files via ::shellexecute(). checks happen in onstartrequest, in the helper app dialog, and as a last ditch in the launching code. limitations of nsimimeinfo no way to say "do whatever the os default is." no support for command-line arguments. no support for multiple commands connected by pipes (mostly useful on unix). ongoing work support synchronous dialogs, not just asynchronous ones (fixes many issues related to pre-downloading, content-decoding, etc). reworking the nsimimeservice api to improve the quality of the mimeinfo we get. reworking the helper app dialog to save user choices better. gnome integration for unix. future work fix the deficiencies in nsimimeinfo. better support for mailcap syntax. possible kde integration. possibly reflecting the os ...
Mozilla Application Framework in Detail - Archive of obsolete content
tensible, platform-independent api for several layers of networking from transport to presentation layers. its provides a generic and extensible framework for fetching urls with support for common protocols (http, ftp, file, etc.) and a way to plug in custom protocol handlers. necko also provides an abstract "file descriptor" interface for low-level data access. necko features include support for asynchronous i/o, a generic disk and memory cache service, asynchronous caching dns resolution, web proxies, and https. the following architectural diagram depicts necko and its interaction with subsystems: necko is powerful, stable and robust, with current development focused on performance and standards-compliance. it has gone through extensive field testing and revision to maximize web site compati...
...tions you can extend and learn from. documentation. web services mozilla includes built-in support for popular web services standards xml-rpc, soap, and wsdl as well as a simple xmlhttprequest object similar to the one in ie. all services are available from javascript code, which allows even simple xul+js applications to take advantage of them. mozilla's xml-rpc support includes synchronous and asynchronous requesting and downloading of data from a server. its soap support is broad and includes.... mozilla has introductory support for wsdl... mozilla engineers have written and are in the process of refining a new security model for web services that will ease the deployment of applications using web services while maintaining the security of sites inside the user's firewall. more information...
XML in Mozilla - Archive of obsolete content
we treat xhtml documents differently depending on the mime type (or file suffix if files are loaded from local discs). files that go through the html code path are not checked for well-formedness. you will also notice not all xhtml features are supported when...
... with fixptr) that will select the link target when you traverse it. there is no ui for setting this pref yet, so you will need to manually edit the preferences file. add this line: pref("layout.selectanchor", true); dom load and save methods document.load() is a part of an old version of the w3c dom level 3 load & save module. mozilla currently implements only the load() method and the document.async property. outside supported xml w3c recommendations specification or technology documentation mozilla project xslt w3c recommendation xslt xpath w3c recommendation xslt xmlhttprequest w3c recommendation xml extras request api (no longer supported) mozilla add-...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
either due to a successful io completion or an error. if the io operation cannot complete before the specified timeout, the io function returns with <tt>pr_io_timeout_error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function returns with <tt>pr_pending_interrupt_error</tt>. on windows nt, nspr io is implemented using nt's overlapped (also called asynchronous) io. when a thread calls an io function, the thread issues an overlapped io request using the overlapped buffer in its <tt>prthread</tt> structure. then the thread is put to sleep. in the meantime, there are dedicated internal threads (called the idle threads) monitoring the io completion port for completed io requests. if a completed io request appears at the io completion port, an idle t...
...e get io timeout or interrupt errors. if <tt>cancelio()</tt> really works as advertised, that should fundamentally solve this problem. if these limitations with io timeout and interrupt are not acceptable to the needs of your programs, you can consider using the win95 version of nspr. the win95 version runs without trouble on nt, but you would lose the better performance provided by nt fibers and asynchronous io. original document information author: larryh@netscape.com last updated date: december 1, 2004 ...
Archived JavaScript Reference - Archive of obsolete content
hat invoked the currently executing function. this property has been removed and no longer works.array comprehensionsthe array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one. however, it has been removed from the standard and the firefox implementation. do not use it!array.observe()the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects. it provided a stream of changes in order of occurrence. it's equivalent to object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead.array.unobserve()the array.unobserve() m...
...it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead.object.prototype.__count__the __count__ property used to store the count of enumerable properties on the object, but it has been removed.object.prototype.__nosuchmethod__the...
Techniques for game development - Game development
this article explains how. optimizing startup performance how to make sure your game starts up quickly, smoothly, and without appearing to lock up the user's browser or device. ...
...this article explains how. optimizing startup performance how to make sure your game starts up quickly, smoothly, and without appearing to lock up the user's browser or device. ...
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
plies to) messages instantly (or as near to instantly as possible). ...
...or as near to instantly as possible). ...
How do you set up a local testing server? - Learn web development
s being used. in contrast, if you view one of our examples hosted on github (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via http. the problem with testing local files some examples won't run if you open them as local files. this can be due to a variety of reasons, the most likely being: they feature asynchronous requests. some browsers (including chrome) will not run async requests (see fetching data from the server) if you just run the example from a local file. this is because of security restrictions (for more on web security, read website security). they feature a server-side language. server-side languages (such as php or python) require a special server to interpret the code and deliver the...
...s (see fetching data from the server) if you just run the example from a local file. this is because of security restrictions (for more on web security, read website security). they feature a server-side language. server-side languages (such as php or python) require a special server to interpret the code and deliver the results. running a simple local http server to get around the problem of async requests, we need to test such examples by running them through a local web server. one of the easiest ways to do this for our purposes is to use python's simplehttpserver (or http.server, depending on the version of python installed.) to do this: install python. if you are using linux or macos, it should be available on your system already. if you are a windows user, you can get an instal...
Sending forms through JavaScript - Learn web development
he data was sent, which means the browser window navigates with a full page load. avoiding a full page load can provide a smoother experience by avoiding network lag, and possible visual issues like flickering. many modern uis only use html forms to collect input from the user, and not for data submission. when the user tries to send the data, the application takes control and transmits the data asynchronously in the background, updating only the parts of the ui that require changes. sending arbitrary data asynchronously is generally called ajax, which stands for "asynchronous javascript and xml". how is it different? the xmlhttprequest (xhr) dom object can build http requests, send them, and retrieve their results. historically, xmlhttprequest was designed to fetch and send xml as an excha...
...ze our script at page load. window.addeventlistener( 'load', function () { // these variables are used to store the form data const text = document.getelementbyid( "thetext" ); const file = { dom : document.getelementbyid( "thefile" ), binary : null }; // use the filereader api to access file content const reader = new filereader(); // because filereader is asynchronous, store its // result when it finishes to read the file reader.addeventlistener( "load", function () { file.binary = reader.result; } ); // at page load, if a file is already selected, read it. if( file.dom.files[0] ) { reader.readasbinarystring( file.dom.files[0] ); } // if not, read the file once the user selects it. file.dom.addeventlistener( "change", function ...
Client-side storage - Learn web development
uest = window.indexeddb.open('notes_db', 1); this line creates a request to open version 1 of a database called notes_db. if this doesn't already exist, it will be created for you by subsequent code. you will see this request pattern used very often throughout indexeddb. database operations take time. you don't want to hang the browser while you wait for the results, so database operations are asynchronous, meaning that instead of happening immediately, they will happen at some point in the future, and you get notified when they're done. to handle this in indexeddb, you create a request object (which can be called anything you like — we called it request so it is obvious what it is for). you then use event handlers to run code when the request completes, fails, etc., which you'll see in...
...pet is taken from inside fetchvideofromnetwork() — here we fetch mp4 and webm versions of the video using two separate windoworworkerglobalscope.fetch() requests. we then use the body.blob() method to extract each response's body as a blob, giving us an object representation of the videos that can be stored and displayed later on. we have a problem here though — these two requests are both asynchronous, but we only want to try to display or store the video when both promises have fulfilled. fortunately there is a built-in method that handles such a problem — promise.all(). this takes one argument — references to all the individual promises you want to check for fulfillment placed in an array — and is itself promise-based. when all those promises have fulfilled, the all() promise...
Multimedia: Images - Learn web development
paying by the megabyte. this isn't an emerging market problem either. as of 2018, 24% of the united kingdom still use pay-as-you-go. you also need to be considerate of memory as many mobile devices have limited ram. it's important to remember that when images are downloaded, they need to be stored in memory. optimizing image delivery despite being the largest consumer of bandwidth, images load asynchronously so the visitor can see the page as they download and therefore, their impact on perceived performance is far lower than many expect. however, images are mostly used for content, so it's important that a visitor can see them as soon as possible for a good experience. loading strategy one of the biggest improvements to most websites is lazy-loading images beneath-the-fold, rather than do...
...ced in <img> elements are assigned a higher loading priority than background images. secondly, with the adoption of priority hints, you can control the priority further by adding an importance attribute to your image tags. an example use case for priority hints on images are carousels where the first image is a higher priority than the subsequent images. rendering strategy as images are loaded asynchronously and continue to load after the first paint, if their dimensions aren't defined before load, they can cause reflows to the page content. for example, when text gets pushed down the page by images loading. for this reason, it's critical that you set width and height attributes so that the browser can reserve space for them in the layout. for any background images, it's important you set a...
Web performance resources - Learn web development
ly important to your users. it might not be absolute timing, but user perception. quick wins css web performance is all about user experience and perceived performance. as we learned in the critical rendering path document, linking css with a tradional link tag with rel="stylesheet" is synchronous and blocks rendering. optimize the rendering of your page by removing blocking css. to load css asynchronously one can simpy set the media type to print and then change to all once loaded. the following snippet includes an onload attribute, requiring javascript, so it is important to include a noscript tag with a traditional fallback. <link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'"> <noscript><link rel="stylesheet" href="/path/to/my.css"></noscript> the do...
...nstyled text (fout.) the simplist way to address this is by inlining css that is required for any content that is rendered above the fold, or what you see in the browser viewport before scrolling. these styles will improve perceived performance as the css does not require a file request. <style type="text/css"> // insert your css here </style> javascript avoid javascript blocking by using the async or defer attributes, or link javascript assets after the page's dom elements. javascript only block rendering for elements that appear after the script tag in the dom tree. web fonts eot and ttf formats are not compressed by default. apply compression such as gzip or brotli for these file types. use woff and woff2. these formats have compression built in. within @font-face use font-display: sw...
Application cache implementation overview
g back on a resource load failure when a resource previously matching a fallback namespace failed to load from the network, we perform fallback to the previously remembered fallback entry. it's actually a redirect to the fallback url loading from the associated nsiapplicationcache. updating an existing cache or first download of an offline cache the process of updating or first caching is invoked asynchronously from nscontentsink::processofflinemanifest() using nsofflinecacheupdateservice. the implementation of offline cache update is in /uriloader/prefetch. nsofflinecacheupdateservice is used to collect, schedule and generally take care of updates and its queue. only one update is running at the time. nsofflinecacheupdate it self is the core of the update process. during initiation the update ...
...s listed in the manifest by call to nsofflinecacheupdate::processnexturi(). if the new hash is identical, update invokes onnoupdate event and is 'finished'. then it associates any documents waiting for this update to finish with the current existing nsiapplicationcache. if the manifest load failed, onerror event is invoked and the update 'finishes'. the parallel load is implemented by asynchronous recursive calls to processnexturi(), a method searching always a single entry that is scheduled to load. when found, channel is open for it (+onprogress event is invoked). processnexturi then invokes it self asynchronously via dispatch to a main thread when not already on the concurrency limit of 15 loads. when concurrency limit is reached, the processnexturi self-invocation cycle is stopp...
Process scripts
this example also figures out whether it is running in the chrome or in a content process by looking at the process type in services.appinfo. in just about every respect, using process scripts is like using frame scripts: you can pass the allowdelayedload to loadproces...
... out whether it is running in the chrome or in a content process by looking at the process type in services.appinfo. in just about every respect, using process scripts is like using frame scripts: you can pass the allowdelayedload to loadprocessscript(). if you do, you must call removedelayedprocessscript() when your extension is disabled or removed the message-passing apis are the same: sendasyncmessage() is available in both directions, while sendsyncmessage() is available from content to chrome only process scripts are system-privileged, and have access to the components object. however, process scripts are subject to the same kinds of limitations as frame scripts (for example, no file system access). process scripts stay loaded until their host process is closed. the environment for...
mozbrowserscrollviewchange
apcz) starts or stops. ...
...ript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped. ...
Browser API
evices. events in order to allow an application to manage the browser <iframe>, the application can listen for new events about what's happening within the browser <iframe>. the following new events can be listened for: mozbrowseractivitydone sent when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. mozbrowserasyncscroll sent when the browser <iframe> content scrolls (the apcz version.) see also mozbrowserscroll. note that this is obsolete. mozbrowseraudioplaybackchange sent when audio starts or stops playing within the browser <iframe> content. mozbrowsercaretstatechanged sent when the text selected inside the browser <iframe> content changes. mozbrowserclose sent when window.close() is called withi...
...or example ctrl/cmd + click.) mozbrowserresize sent when the browser <iframe>'s window size has changed. mozbrowserscroll sent when the browser <iframe> content scrolls. mozbrowserscrollareachanged sent when the available scrolling area in the browser <iframe> changes. this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange sent when asynchronous scrolling (i.e. apcz) starts or stops. mozbrowsersecuritychange sent when the ssl state changes within a browser <iframe>. mozbrowserselectionstatechanged sent when the text selected inside the browser <iframe> content changes. note that this is obsolete, and newer implementations use mozbrowsercaretstatechanged instead. mozbrowsershowmodalprompt sent when alert(), confirm(), or prom...
HTML parser threading
t returning to the event loop. if too much time has been spent, a runnable for calling runflushloop() again is dispatched and an early return made before all tree ops have been executed. (only the already executed ops are destructed and the rest are left in the queue.) the last op in the queue may be an op for attempting to execute a script that may block the parser (ops for attempting to execute async and defer scripts are normal tree ops and don't need to be the last op in a queue). the parts of the parser that drive the tokenizer/tree builder pairs guarantee to flush tree ops immediately if a script execution tree op is generated. (the tree builder makes the tokenizer return immediately when such an op is generated.) thus, a tree op that may cause the parser to block can only occur as the la...
...mmediately if a script execution tree op is generated. (the tree builder makes the tokenizer return immediately when such an op is generated.) thus, a tree op that may cause the parser to block can only occur as the last op in a queue that runflushloop sees. preparing the parser thread for script execution when the parser thread sees that it has generated a tree op that attempts to execute a (non-async, non-defer) script, it starts speculating. it acquires mspeculationmutex and while holding it, it creates a new speculation and adds it to the queue of speculations, flushes the tree ops to the main thread, marks the nshtml5streamparser as being in a speculating state and sets the newly created speculation object as the tree op sink (instead of the tree op stage described earlier) of the tree bui...
IME handling guide
ing composition. in order to put it into practice, we need to handle the following four scenarios: the composition is committed with non-empty string synchronously this is the most usual case. in this case, textcomposition handles widgetcompositionevent instances during a request normally. however, in a remote process in e10s mode, this case never occurs since requests to native ime is handled asynchronously. the composition is not committed synchronously but later this is the only case in a remote process in e10s mode or occurs on linux even in non-e10s mode if the native ime is ibus. the callers of notifyime(request_tocommit_composition) may expect that composition string is committed immediately for their next job. for such a case, textcomposition::requesttocommit() synthesizes dom comp...
... at this time, tsftextstore saves the requests of modification into the queue called pendingaction. finally, after unlocking the contents, it flushes the pending actions with dispatches widgetcompositionevents via texteventdispatcher. then, imecontentobserver will notify some changes caused by the dispatched widgetcompositionevents (they are notified synchronously in chrome or non-e10s mode, but asynchronously from a remote process in e10s mode). at this time, tsftextstore may receive notifications which indicates web application changes the content differently from cache in tsftextstore. however, tsftextstore ignores such fact temporarily until the composition is finished completely. the reason is that, notifying unexpected text or selection changes to tsf and/or tip during composition may be...
Introduction to Layout in Mozilla
trics n.b. ...
... damage to frames later “in the flow” incremental reflow multiple reflow commands are batched nsreflowpath maintains a tree of target frames amortize state recovery and damage propagation cost painting as reflow proceeds through the frame hierarchy, areas are invalidated via nsiviewmanager::updateview unless immediate, invalid areas are coalesced and processed asynchronously via os expose event native expose event dispatched to widget; widget delegates to the view manager view manager paints views back-to-front, invoking presshell’s paint method presshell::paint walks from the view to the frame; invokes nsiframe::paint for each layer incrementalism single-threaded simple (no locking) can’t leave event queue unattended co...
Add-on Manager
the add-on manager is responsible for managing all of the add-ons installed in the application. through its apis information about all installed add-ons can be retrieved and new add-ons can be installed. the apis are designed to be generic and support many different types of add-ons. many functions in the add-on manager interface operate asynchronously returning results through callbacks passed to the functions. ...
...the callback may well only be called after the api function returns. ...
DownloadLastDir.jsm
downloadlastdir object to determine or set the path into which the last download occurred: // file is an nsifile var file = downloadlastdir.file; downloadlastdir.file = file; you can also set and retrieve this information on a site-by-site basis. ...
...ermine or set the path into which the last download occurred: // file is an nsifile var file = downloadlastdir.file; downloadlastdir.file = file; you can also set and retrieve this information on a site-by-site basis. to set the path, use setfile: // file is an nsifile downloadlastdir.setfile(uri, file); to retrieve the path in firefox 26 or later, use getfileasync: downloadlastdir.getfileasync(uri, function (file) { // file is an nsifile console.log(file); }); deprecated since gecko 26.0 to retrieve the path in firefox 25 or earlier, use getfile: // file is an nsifile var file = gdownloadlastdir.getfile(uri); console.log(file); private browsing mode when browsing normally, the browser uses the browser.download.lastdir preference to store the last download directory path. howev...
OS.File for the main thread
ile.jsm") promises before using os.file from the main thread, you need some understanding of the promise library. see the promise object documentation for details. also, os.file plays very nicely with task.jsm. example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). the content is read asynchronously. the result is a promise. let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. ...
... not a directory } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // the file does not exist } else { // some other error throw reason; } } ); example: copy a file by chunks the following snippet writes a (presumably large) buffer by chunks. note that this snippet is useful as a demonstration of complex asynchronous programming with os.file – in most cases, function os.file.writeatomic is a better choice. let writestream = function writestream(data, outfile, chunksize) { let view = new uint8array(data); let loop = function loop(pos) { // define a recursive asynchronous loop. if (pos <= view.bytelength) { // note: should this be pos >= view.bytelengt...
JavaScript code modules
utils.jsm provides routines to convert between javascript date objects and iso 8601 date strings. log.jsm (formerly log4moz) provides a log4j style api for logging, log messages to various endpoints, such as the browser console or a file on disk. netutil.jsm provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously. openlocationlasturl.jsm provides access to the last url opened using the "open location" option in the file menu. osfile.jsm allows routines to access files. to which can be read, write, rename, create directories,etc. perfmeasurement.jsm provides access to low-level hardware and os performance measurement tools. pluralform.jsm supplies an easy way to get the correct plural form...
... of using an event to do so. services.jsm provides getters for conveniently obtaining access to commonly-used services. source-editor.jsm the source editor is used by developer tools such as, the style editor; this interface implements the editor and lets you interact with it. sqlite.jsm a promise-based api to mozistorage/sqlite. task.jsm implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator. timer.jsm a pure js implementation of window.settimeout. webapps.jsm provides an interface to manage open web apps. webrequest.jsm provides an api to add event listeners for the various stages of making an http request. the event listener receives detailed information about the request, and can modify or cancel the re...
Nonblocking IO In NSPR
in nspr, blocking sockets on nt are associated with an i/o completion port. once associated with an i/o completion port, we can't disassociate the socket from the i/o completion port. i have seen some strange problems with using a nonblocking socket associated with an i/o completion port. so the first constraint is: the blocking/nonblocking io mode of a new socket is comm...
... and <tt>pr_transmitfile(),</tt> and do not include <tt>pr_bind()</tt> and <tt>pr_listen()</tt>. in blocking mode, any of these potentially-blocking functions requires the use of the nt i/o completion port. so at that point we must determine whether to associate the socket with the i/o completion or not, and that decision cannot be changed later. there is a second constraint, due to the use of nt asynchronous i/o and the recycling of used sockets: the new socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> inherits the blocking/nonblocking io mode of the listening socket and this cannot be changed. the socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> on a blocking, listening socket may be a recycled socket previously used in a <tt>pr_transmitfile()</tt> call.
HTTP delegation
e implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications. specifying an ocsp proxy the remainder of this document is a short howto. one might expect the api defines a simple function that accepts the uri and data to be sent, and returns the result data. but there is no such simple interface. the api should allow nss to use the http client either asynchronously or synchronously. in addition, during an application session with ocsp enabled, a large number of ocsp requests might have to be sent. therefore the api should allow for keep-alive (persistent) http connections. http uris consist of host:port and a path, e.g. http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, it will request that an "http server sess...
...iate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is a (versioned) table of function pointers. create an instance of th...
HTTP delegation
e implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications. specifying an ocsp proxy the remainder of this document is a short howto. one might expect the api defines a simple function that accepts the uri and data to be sent, and returns the result data. but there is no such simple interface. the api should allow nss to use the http client either asynchronously or synchronously. in addition, during an application session with ocsp enabled, a large number of ocsp requests might have to be sent. therefore the api should allow for keep-alive (persistent) http connections. http uris consist of host:port and a path, e.g. http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, it will request that an "http server sess...
...iate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is a (versioned) table of function pointers. create an instance of th...
History Service Design
s mainly dedicated to not locking ui. since places is actually not thread-safe and doing most of the work in the main-thread, adding visits (the most common action usually executed on user interaction) could end up locking the ui till the database i/o to save data is complete. for this reason visits and favicons are added lazily on a timer. in future this will probably change in favour of storage asynchronous statements, so that the inserts will be queued-up by mozstorage itself in a separate thread. sql queries are built with performance in mind, and constantly tested against large databases. database indexes are quite important, and a good query can make the difference between minutes or seconds. many queries are especially optimized, for example limited history queries, often used to build ...
...nowledge on the actual implementation. expiration expiration is an important part of data management for two reasons: privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal database maintenance: having cleaner and smaller tables helps queries performances expiration is done at certain moments, but in future will most likely be moved to async queries, to be executed on a separate thread. actually pages and visits are expired: on page added (lazily) on idle on shutdown expiration of pages happens when a page is no more referenced, so there are no more visits, nor bookmarks associated with it. visits are expired based on user preferences, there is an hard limit on the minimum number of days that should be retained, visits in that...
mozIPlaceInfo
warning: this interface is experimental and will change after gecko 2.0. toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides additional info for a places entry 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) attributes attribute type description frecency long read only: the frecency of the place. guid string read only: the globally unique id of the place. placeid long read only: the machine-local (internal) id of the place. title string read only: the title associated with the place. ...
... frecency long read only: the frecency of the place. ...
mozIStorageAggregateFunction
void onstep(in mozistoragevaluearray afunctionarguments); nsivariant onfinal(); methods onstep() this is called for each row of results returned by the query. the implementation should store or perform some work to prepare to return a value. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! void onstep( in mozistoragevaluearray afunctionarguments ); parameters afunction...
...zistoragevaluearray holding the arguments passed in to the function. onfinal() this is called after all results have been obtained and notified via mozistorageaggregatefunction. the implementation should finish its calculations on the data, and return a result. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfinal() return value an nsivariant this is the return value of the func...
mozIStorageBindingParamsArray
storage/public/mozistoragebindingparamsarray.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.newbindingparamsarray(). ...
...dingparams aparameters); mozistoragebindingparams newbindingparams(); attributes attribute type description length unsigned long the number of mozistoragebindingparams objects in the array. methods addparams() adds the specified set of parameters to the end of the array. the appended parameters will be used when mozistoragestatement.executeasync() is called. void addparams( in mozistoragebindingparams aparameters ); parameters aparameters the mozistoragebindingparams object containing the parameters to append to the array. newbindingparams() creates and returns a new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding. mozistoragebindingparams newbindingparams(); parameters ...
mozIStorageStatementCallback
storage/public/mozistoragestatementcallback.idlscriptable please add a summary to this article. ...
...lled when a statement finishes executing. void handlecompletion( in unsigned short areason ); parameters areason the reason the statement stopped executing; see the list of possible values in the constants section. handleerror() called when an error occurs while executing a statement. this function may be called more than once with a different storageierror each time for any given asynchronous statement, and handlecompletion will be called once the statement is complete. void handleerror( in mozistorageerror aerror ); parameters aerror a mozistorageerror object describing the error that occurred. handleresult() called when results from the statement are available. generally, this method will be called several times, each time providing one or more results. once t...
mozIVisitInfo
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) attributes attribute type description referreruri nsiuri read only: the referring uri of this visit. this may be null. sessionid long read only: the sessionid of this visit. transitiontype long read only: the transition type used to get to this visit. one of the nsinavbookmarksservice.constants on nsinavhistory. visitdate prtime read only: the time the visit occurred. ...
... sessionid long read only: the sessionid of this visit. transitiontype long read only: the transition type used to get to this visit. one of the nsinavbookmarksservice.constants on nsinavhistory. visitdate prtime read only: the time the visit occurred. visitid long read only: the machine-local (internal) id of the visit. see also moziasynchistory ...
nsIAccessibleEvent
dow_resize 0x0124 event_atk_window_restore 0x0125 event_dom_create 0x0001 an object has been created. event_dom_destroy 0x0002 an object has been destroyed. event_dom_significant_change 0x0003 an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated. ...
...n object has been created. event_dom_destroy 0x0002 an object has been destroyed. event_dom_significant_change 0x0003 an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated. event_asynch_show 0x0004 a hidden object is shown -- this is a layout occurrence and is thus asynchronous. event_asynch_hide 0x0005 an object is hidden -- this is a layout occurrence and is thus asynchronous. event_asynch_significant_change 0x0006 an object had a significant layout change which could affect the type of accessible object -- this is a layout occurrence and is thus asynchronous. event_document_load_start 0x002a event_internal_load 0x005b used internally ...
nsIAuthPromptCallback
netwerk/base/public/nsiauthpromptcallback.idlscriptable interface for callback methods for the asynchronous nsiauthprompt2 method. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) callers must call exactly one method if nsiauthprompt2.asyncpromptauth() returns successfully. they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns. method overview void onauthavailable(in nsisupports acontext, in nsiauthinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel); methods onauthavailable() authentication information is available. note: any exceptions thrown from this method should be ignored. void onauthavailable( in nsisupp...
...authinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel); methods onauthavailable() authentication information is available. note: any exceptions thrown from this method should be ignored. void onauthavailable( in nsisupports acontext, in nsiauthinformation aauthinfo ); parameters acontext the context as passed to nsiauthprompt2.asyncpromptauth(). aauthinfo authentication information. must be the same object that was passed to nsiauthprompt2.asyncpromptauth(). onauthcancelled() notification that the prompt was cancelled. void onauthcancelled( in nsisupports acontext, in boolean usercancel ); parameters acontext the context that was passed to nsiauthprompt2.asyncpromptauth(). usercancel if false, ...
nsIBrowserHistory
he count attribute was removed in gecko 15.0 because it was only used to determine if there were any entries at all anyway, so the nsinavhistoryservice.hashistoryentries attribute is better for this. methods addpagewithdetails() obsolete since gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) note: this method was removed in gecko 15.0. you should use moziasynchistory.updateplaces() instead. this method adds a page to the history with specific time stamp information. it is called by history importing code and is used in the history migration tool. void addpagewithdetails( in nsiuri auri, in wstring atitle, in long long alastvisited ); parameters auri the page that will be added to the history. atitle the title of the page. alastvisited...
...lias for moziplacesautocomplete.registeropenpage(), which still exists and can be used instead. void registeropenpage( in nsiuri auri ); parameters auri the page that is to be marked as currently open. removeallpages() this method removes all the pages from the global history. void removeallpages(); parameters none. remarks visits are removed synchronously, but pages are expired asynchronously, off the main thread. note: removals are handled in a batch. single removals are not subject to individual notification; instead, nsinavhistoryobserver.onclearhistory() is called on the history observer. removepage() this method removes all visits for a page from the history. the page itself is only deleted when it is not bookmarked and when it is not a place: uri. this method is call...
nsICacheEntryDescriptor
ns the string value containing the meta data for the provided key. markvalid() this method means that a writer must validate this cache object before any readers are given a descriptor to the object. void markvalid(); parameters none. openinputstream() this method opens blocking input stream to cache data. this will fail if the cache entry is not stream based. use the stream transport service to asynchronously read this stream on a background thread. the returned stream may implement nsiseekablestream. nsiinputstream openinputstream( in unsigned long offset ); parameters offset read starting from this offset into the cached data. an offset beyond the end of the stream has undefined consequences. return value returns blocking, unbuffered input stream. openoutputstream() this method opens b...
...stream( in unsigned long offset ); parameters offset read starting from this offset into the cached data. an offset beyond the end of the stream has undefined consequences. return value returns blocking, unbuffered input stream. openoutputstream() this method opens blocking output stream to cache data. this will fail if the cache entry is not stream based. use the stream transport service to asynchronously write to this stream on a background thread. the returned stream may implement nsiseekablestream. if opening an output stream to existing cached data, the data will be truncated to the specified offset. nsioutputstream openoutputstream( in unsigned long offset ); parameters offset write starting from this offset into the cached data. an offset beyond the end of the stream has undefin...
nsIContentPrefService2
specifically, a content preference is a structure with three values: a domain with which the preference is associated, a name that identifies the preference within its domain, and a value. ...
...e. pass an nsiloadcontext to use storage appropriate to the context's useprivatebrowsing attribute: if useprivatebrowsing is true, temporary private-browsing storage is used, and otherwise permanent storage is used. a context can be obtained from the window or channel whose content pertains to the preferences being modified or retrieved. callbacks the methods of callback objects are always called asynchronously. see nsicontentprefcallback2 for more information about callbacks. method overview void addobserverforname(in astring name, in nsicontentprefobserver observer); void getbydomainandname(in astring domain, in astring name, in nsiloadcontext context, in nsicontentprefcallback2 callback); void getbysubdomainandname(in astring domain, in astring ...
nsIFrameMessageManager
4) this interface is obsolete and was removed in firefox 17. you should use nsimessagelistenermanager or nsimessagesender instead. method overview void addmessagelistener(in astring amessage, in nsiframemessagelistener alistener, [optional] in boolean listenwhenclosed); void removemessagelistener(in astring amessage, in nsiframemessagelistener alistener); void sendasyncmessage(in astring amessage, in astring json); methods addmessagelistener() adds a message listener to the local frame. this listener will receive messages sent from the remote frame. void addmessagelistener( in astring amessage, in nsiframemessagelistener alistener [optional in boolean listenwhenclosed ); parameters amessage the name of the message for which to add a listene...
...ations :: message manager. removemessagelistener() removes a message listener previously added by calling addmessagelistener(). void removemessagelistener( in astring amessage, in nsiframemessagelistener alistener ); parameters amessage the name of the message for which to remove a listener. alistener an object implementing nsiframemessagelistener to stop receiving messages. sendasyncmessage() asynchronously sends a message to the listeners. void sendasyncmessage( in astring amessage, in astring json ); parameters amessage the name of the message to send to the listeners. json optional a json object containing data to be delivered to the listeners. see also content process event handling nsiframemessagelistener nsisyncmessagesender ...
nsIJetpack
astring amessagename /* [optional] in jsval v1, [optional] in jsval v2, ... */); void registerreceiver(in astring amessagename, in jsval areceiver); void unregisterreceiver(in astring amessagename, in jsval areceiver); void unregisterreceivers(in astring amessagename); void evalscript(in astring ascript); nsivariant createhandle(); void destroy(); methods sendmessage() this method asynchronously sends a message to the jetpack process. void sendmessage( in astring amessagename, [optional] in jsval v1, optional [optional] in jsval v2, optional ... ); parameters amessagename the name of the message to send. v1, v2, ... optional javascript values to send with the message; they must be either json-serializable types or handles. registerreceiver() this registers a callback ...
...h the callback should no longer be triggered. areceiver the javascript function that should no longer be triggered. unregisterreceivers() this unregisters all callbacks previously registered with registerreceiver() for a particular message. void unregisterreceivers( in astring amessagename ); parameters amessagename the name of the message to unregister all callbacks from. evalscript() this asynchronously sends code to the jetpack process for evaluation. the code will be evaluated using at least javascript 1.8.1. when evaluated, the script's global scope will include all privileged apis. individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. void evalscript( in astring ascript ); parameters ascript the full c...
nsIMessageSender
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsimessagelistenermanager message senders enable clients to send asynchronous messages to a single "other side". for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. to send messages to multiple "other sides", you would use nsimessagebroadcaster. see message manager interfaces for more details on the distinction between message senders and message broadcasters. ...
...nchronous messages to a single "other side". for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. to send messages to multiple "other sides", you would use nsimessagebroadcaster. see message manager interfaces for more details on the distinction between message senders and message broadcasters. methods void sendasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); sendasyncmessage() send messagename and obj to the "other side" of this message manager. this invokes listeners who registered for messagename using a nsimessagelistenermanager. ...
nsIMsgFilterCustomAction
readonly attribute boolean needsbody; }; ...
...er, in nsmsgfiltertypetype filtertype, in nsimsgwindow msgwindow); /* does this action start an async action? if so, a copy listener must * be used to continue filter processing after the action. this only * applies to after-the-fact (manual) filters. call onstopcopy when done * using the copylistener to continue. */ readonly attribute boolean isasync; /// does this action need the message body? readonly attribute boolean needsbody; }; ...
nsIRequest
is flag indicates that no user-specific data should be added to the request when opened. this means that things like authorization tokens or cookie headers should not be added. note: this will prevent proxy authentications from working, so use this flag with caution. methods cancel() cancels the current request. this will close any open input or output streams and terminate any async requests. users should normally pass ns_binding_aborted, although other errors may also be passed. the error passed in will become the value of the status attribute. implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function. similarly, removal from the load group (if any) must also happen asynchronously. requests that use nsistreamlist...
...sirequest implementations expect astatus to be a failure code; however, some implementations may allow astatus to be a success code such as ns_ok. in general, astatus should be a failure code. void cancel( in nsresult astatus ); parameters astatus the reason for canceling this request. ispending() indicates whether the request is pending. ispending is true when there is an outstanding asynchronous event that will make the request no longer be pending. requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsichannel implementations are only pending once asyncopen returns successfully). requests can become pending multiple times during their lifetime. note: suspended requests are still considered pending. boolean ispendi...
nsITextInputProcessorNotification
acstring the type of request or notification to ime. see type values below. types "request-to-commit" this is required to be handled. when this is requested, the callback should commit composition synchronously, i.e., nsitextinputprocessor.commitcomposition() should be called. if the callback doesn't want to commit the composition synchronously, it's okay to commit it later (i.e., asynchronously). however, gecko will commit the composition with the last composing string internally. this is typically notified when user clicks somewhere, focus is moved, or web contents modify the value of the editor during composition. "request-to-cancel" this is required to be handled. when this is requested, the callback should cancel composition synchronously, i.e., nsitextinputprocessor.ca...
...somewhere, focus is moved, or web contents modify the value of the editor during composition. "request-to-cancel" this is required to be handled. when this is requested, the callback should cancel composition synchronously, i.e., nsitextinputprocessor.cancelcomposition() should be called. if the callback doesn't want to cancel the composition synchronously, it's okay to cancel it later (i.e., asynchronously). however, gecko will cancel the composition with empty string internally. this is typically notified when the editor is being removed from the dom tree during composition. "notify-detached" when the nsitextinputprocessor instance loses the rights to create composition, this is notified. "notify-focus" when an editable editor gets focus, this is notified. "notify-blur" when an edi...
nsITransport
losed, then reading from it will block the calling thread until at least one byte is available or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream has no data and is not closed, then reading from it returns ns_base_stream_would_block. in addition, in non-blocking mode, the stream is guaranteed to support nsiasyncinputstream. this interface allows the consumer of the stream to be notified when the stream can again be read. open_unbuffered if specified, the resulting stream may not support readsegments. readsegments is only guaranteed to be implemented when this flag is not specified. asegmentsize if open_unbuffered is not set, then this parameter specifies the size of each buffer segment (pass 0 to use de...
...s not closed, then writing to it will block the calling thread until all of the data can be written or until the stream is closed. if this flag is not specified, then the stream has non-blocking stream semantics. this means that if the stream is full and is not closed, then writing to it returns ns_base_stream_would_block. in addition, in non- blocking mode, the stream is guaranteed to support nsiasyncoutputstream. this interface allows the consumer of the stream to be notified when the stream can again accept more data. open_unbuffered if specified, the resulting stream may not support writesegments and writefrom. writesegments and writefrom are only guaranteed to be implemented when this flag is not specified. asegmentsize if open_unbuffered is not set, then this parameter specifies the size...
XPCOM Interface Reference
iaccessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstallcallbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletioncallbackmozistorageconnectionmozistorageerrormozistoragefunctionmozistoragependingstatem...
...ntnsiaccessibletextnsiaccessibletextchangeeventnsiaccessibletreecachensiaccessiblevaluensiaccessiblewin32objectnsialertsservicensiannotationobservernsiannotationservicensiappshellnsiappshellservicensiappstartupnsiappstartup_mozilla_2_0nsiapplicationcachensiapplicationcachechannelnsiapplicationcachecontainernsiapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirectcallbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthpromptcallbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertlistener2n...
XPCOM Interface Reference by grouping
kreference nsivariant do not use nsienumerator nsiinprocesscontentframemessagemanager nsiscriptableio nsixpcscriptable future nsixmlhttprequestupload obsolete nsixmlrpcclient nsixmlrpcfault security auth nsiauthmodule nsiauthprompt nsiauthpromptprovider nsiauthpromptwrapper nsiasyncverifyredirectcallback content nsicontentpolicy credentials nsilogininfo nsiloginmanager using nsiloginmanager nsiloginmanagerstorage nsiloginmetainfo history nsiglobalhistory nsiglobalhistory2 nsiglobalhistory3 ssl nsibadcertlistener2 ...
... filesystem nsidirectoryenumerator nsidirectoryiterator nsidirectoryservice nsidirectoryserviceprovider nsidirectoryserviceprovider2 nsidirindex nsidirindexlistener nsidirindexparser nsifile nsilocalfile stream nsiasyncinputstream nsiasyncoutputstream nsiasyncstreamcopier nsibinaryinputstream nsibinaryoutputstream nsicontentsniffer nsiconverterinputstream nsifileinputstream nsifileoutputstream nsiinputstream nsiinputstreamcallback nsioutputstream nsioutputstreamcallback ...
Performance
h each transaction. when you execute a sql statement in isolation, an implicit transaction is created around that statement. when transactions are committed, sqlite does journaling which requires syncing data to disk. this operation is extremely slow. therefore, if you are doing many transactions in a row, you will get significant performance improvements by surrounding them in a transaction. the asynchronous writes discussed below removes most of the immediate penalty of a commit, so you will not notice the problem as much. however, there is still overhead, and using a transaction will still be faster. one major problem is that the queue of file operations will get very long if there are many transactions. some operations require walking this queue to see what operations have been pending, and...
...um except to reclaim disk space, and makes many operations much faster. zero-filling can have significant performance overhead in some situations. for example, the history service used to delete many database items at shutdown when expiring old history items. this operation is not necessarily slow, but writing 0s to disk in an "aci" database is still slow. this made shutdown very slow because the asyncio thread would block shutdown (bug 328598). shutdown times of more than 30 seconds were seen. as a result, this bug introduced incremental history expiration eliminating the need to write many 0s to disk on shutdown. unfortunately, this operation cannot be controlled on a per-transaction or per-connection basis. some operations will benefit, while others will be hurt. ...
Mail and RDF
to their respective widgets by setting the database property on each rdf template's parent element. reflecting data to rdf in order to have a dynamic ui that updates when the underlying content changes, a datasource must implement two key methods of reflecting data into rdf. answering queries: when rdf asks for information about a resource, datasources answer with the results of the query. asynchronously notifying rdf when the data itself changes, rdf needs to be notified. the details answering queries mail uses rdf resource factories to attach mail-specific information to rdf resources. (the details of rdf resource factories will be left to rdf documentation for now.) from an rdf resource, it is possible to queryinterface() to the appropriate mail/news object, and then access inform...
... in the example of mail folders, each folder datasource first registers itself with the mail session as a nsifolderlistener because it wants information about when a folder changes. each template registers itself as an rdf observ...
Debugger.Object - Firefox Developer Tools
efined instead. isgeneratorfunction if the referent is a debuggee function, returns true if the referent was created with a function* expression or statement, or false if it is some other sort of function. if the referent is not a debuggee function, or not a function at all, this is undefined. ...
... if the referent was created with a function* expression or statement, or false if it is some other sort of function. if the referent is not a debuggee function, or not a function at all, this is undefined. (this is always equal to obj.script.isgeneratorfunction, assuming obj.script is a debugger.script.) isasyncfunction if the referent is a debuggee function, returns true if the referent is an async function, defined with an async function expression or statement, or false if it is some other sort of function. if the referent is not a debuggee function, or not a function at all, this is undefined. (this is always equal to obj.script.isasyncfunction, assuming obj.script is a debugger.script.) ispromise true if the referent is a promise; false otherwise. boundtargetfunction if the referent...
Console messages - Firefox Developer Tools
takes you to the javascript error reference containing additional advice for fixing issues: source maps the web console understands source maps. this means that if your javascript sources are compressed, you can supply a source map for them. then any messages or errors your source generates will show up in the web console with a link back to the original source, not the compressed version. async stack frames stack traces show stack frames for async functions separately from those for synchronous functions. when you run code containing an async function, its traces (console.trace or thrown error) are shown with an async: prefix. css note: css warnings and reflow messages are not shown by default, for performance reasons (see bug 1452143). use the filtering feature to show them. so...
... default, they are disabled. you can enable them by clicking the "css" button in the toolbar and selecting "reflows". each message is labeled "reflow" and shows the time taken to execute the reflow. if the reflow is a synchronous reflow triggered from javascript, it also shows a link to the line of code that triggered the reflow. click the link to open the file in the debugger. synchronous and asynchronous reflows if a change is made that invalidates the current layout — for example, the browser window is resized or some javascript modifies an element's css — the layout is not recalculated immediately. instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). in this way the browser can save up a co...
Beacon API - Web APIs
beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). example use cases of the beacon api are logging activity and sending analytics data to the server. example code of the interfaces described in this document is included in using the beacon api. why use beacon? the beacon interface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. ...
...rface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. sending the data any sooner may result in a missed opportunity to gather data. however, ensuring that the data is sent during the unloading of a document is something that has traditionally been difficult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data. the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower. there is nothing the next page can do to avoid this per...
Clipboard - Web APIs
Web › API › Clipboard
thods of the clipboard object will not succeed if the user hasn't granted the needed permissions using the permissions api and the "clipboard-read" or "clipboard-write" permission as appropriate. note: in reality, at this time browser requirements for access to the clipboard vary significantly. please see the section clipboard availability for details. all of the clipboard api methods operate asynchronously; they return a promise which is resolved once the clipboard access has been completed. the promise is rejected if clipboard access is denied. the clipboard is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications it is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, t...
...trary data (such as images) from the clipboard, returning a promise. when the data has been retrieved, the promise is resolved with a datatransfer object that provides the data. readtext() requests text from the system clipboard; returns a promise which is resolved with a domstring containing the clipboard's text once it's available. write() writes arbitrary data to the system clipboard. this asynchronous operation signals that it's finished by resolving the returned promise. writetext() writes text to the system clipboard, returning a promise which is resolved once the text is fully copied into the clipboard. clipboard availability the asynchronous clipboard api is a relatively recent addition, and the process of implementing it in browsers is not yet complete. due to both potential s...
ClipboardItem - Web APIs
interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found. 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. ...
...w clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. ...
Clipboard API - Web APIs
access to the contents of the clipboard is gated behind the permissions api: the clipboard-write permission is granted automatically to pages when they are in the active tab. the clipboard-read permission must be requested, which you can do by trying to read data from the clipboard. this api is designed to supersede accessing the clipboard using document.execcommand(). ...
...ppet fetches the text from the clipboard and appends it to the first element found with the class editor. since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe. interfaces clipboard secure context provides an interface for reading and writing text and data to or from the system clipboard. the specification refers to this as the 'async clipboard api.' clipboardevent secure context represents events providing information related to modification of the clipboard, that is cut, copy, and paste events. the specification refers to this as the 'clipboard event api'. clipboarditem secure context represents a single item format, used when reading or writing data. specifications specification status comment ...
ContentIndex.delete() - Web APIs
) method of the contentindex interface unregisters an item from the currently indexed content. calling delete() only affects the index. it does not delete anything from the cache. syntax contentindex.delete(id).then(...); parameters this method receives no parameters. return value returns a promise that resolves with undefined exceptions no exceptions are thrown. ...
...).then(...); parameters this method receives no parameters. return value returns a promise that resolves with undefined exceptions no exceptions are thrown. examples below is an asynchronous function, that removes an item from the content index. we receive a reference to the current serviceworkerregistration, which allows us to access the index property and thus access the delete method. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete method can also be used within the service worker scope. self.registration.index.delete('my-id'); ...
ContentIndex.getAll() - Web APIs
tional an array of image resources, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image. exceptions no exceptions are thrown. if there are no items in the content index, an empty array is returned. ...
...izes: optional a string representation of the image size. type: optional the mime type of the image. exceptions no exceptions are thrown. if there are no items in the content index, an empty array is returned. examples the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface. ...
HTMLImageElement.complete - Web APIs
ied, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. the image element has previously determined that the image is fully available and ready for use. the image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running. examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. these photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background. but imagine that you have...
...deyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ... */ function fixredeyecommand()...
HTMLMediaElement.play() - Web APIs
nd autoplay blocking, see our article autoplay guide for media and web audio apis. ...
...it tries to play the video, and if successful sets the class name of the playbutton element to "playing". if playback fails to start, the playbutton element's class is cleared, restoring its default appearance. this ensures that the play button matches the actual state of playback by watching for the resolution or rejection of the promise returned by play(). ...
Basic concepts - Web APIs
orage limits and eviction criteria. overview of indexeddb indexeddb lets you store and retrieve objects that are indexed with a "key." all changes that you make to the database happen within transactions. like most web storage solutions, indexeddb follows a same-origin policy. so while you can access stored data within a domain, you cannot access data across different domains. indexeddb is an asynchronous api that can be used in most contexts, including web workers. it used to include a synchronous version also, for use in web workers, but this was removed from the spec due to lack of interest by the web community. indexeddb used to have a competing spec, websql database, but the w3c deprecated it on november 18, 2010. while both indexeddb and websql are solutions for storage, they do not ...
...consider what might happen if a user opened two instances of your web app in two different tabs simultaneously. without transactional operations, the two instances could interfere with each other's modifications. if you are not familiar with transactions in a database, read the wikipedia article on transactions. also see transaction under the definitions section. the indexeddb api is mostly asynchronous. the api doesn't give you data by returning values; instead, you have to pass a callback function. you don't "store" a value into the database, or "retrieve" a value out of the database through synchronous means. instead, you "request" that a database operation happens. you get notified by a dom event when the operation finishes, and the type of event you get lets you know if the operation...
Intersection Observer API - Web APIs
historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. as the web has matured, the need for this kind of information has grown. intersection information is needed for many reasons, such as: lazy-loading of images or other content as a page is scrolled. ...
...ntersecting) { let elem = entry.target; if (entry.intersectionratio >= 0.75) { intersectioncounter++; } } }); } interfaces intersectionobserver the primary interface for the intersection observer api. provides methods for creating and managing an observer which can watch any number of target elements for the same intersection configuration. each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level document's viewport. the ancestor or viewport is referred to as the root. intersectionobserverentry describes the intersection between the target element and its root container at a specific moment of transition. objects of this type can only be obtained in two ...
MediaDevices.getDisplayMedia() - Web APIs
e getting captured and shown to other users. example in the example below, a startcapture() method is created which initiates screen capture given a set of options specified by the displaymediaoptions parameter. the options are specified in the form of a mediastreamconstraints object which specifies the preferred stream configuration and the display surface from which video is to be captured. ...
...ts object which specifies the preferred stream configuration and the display surface from which video is to be captured. async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } this uses await to asynchronously wait for getdisplaymedia() to resolve with a mediastream which contains the display contents as requested by the specified options. the stream is then returned to the caller for use, perhaps for adding to a webrtc call using rtcpeerconnection.addtrack() to add the video track from the stream. specifications specification status comment screen capturethe definiti...
MediaRecorder: error event - Web APIs
xample because recording wasn't allowed or was attempted using an unsupported codec. bubbles no cancelable no interface mediarecordererrorevent event handler property onerror for details of the all the possible errors see the documentation for the event handler property: onerror. ...
... listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.onerror = (event) => { console.error(`error recording stream: ${event.error.name}`) }; recorder.start(); } record(); specifications specification status mediastream recording working draft ...
NavigationPreloadManager - Web APIs
of the service-worker-navigation-preload header and returns an empty promise. navigationpreloadmanager.getstate() returns a promise that resolves to an object with properties indicating whether preload is enabled and the contents of the service-worker-navigation-preload. ...
...vate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads! await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response. 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 ...
PaymentRequest.canMakePayment() - Web APIs
o true if the user agent supports any of the payment methods supplied when instantiating the request using the paymentrequest constructor. if the payment can't be processed, the promise receives a value of false. note: if you call this too often, the browser may reject the returned promise with a domexception. ...
... you call this too often, the browser may reject the returned promise with a domexception. parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards. it wraps the call to canmakepayment() in feature detection, and calls an appropriate callback depending on the resolution of the promise. ...
PaymentRequest: merchantvalidation event - Web APIs
t uses the fetch() to send a request to its own server with an argument of the payment method's validation url, obtained from the event's validationurl property. the merchant server should access the validation url in accordance with the payment method documention. typically, a client should not access the validation url. ...
...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. this response lets the payment handler know if the merchant is validated. you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. related e...
PaymentResponse: payerdetailchange event - Web APIs
rname: true, requestpayerphone: true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid. if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpay...
...} specifications specification status comment payment request apithe definition of 'payerdetailchange event' in that specification. candidate recommendation ...
RTCPeerConnection.addTrack() - Web APIs
eam with an audio track and a video track, you don't need to deal with managing what track is in what stream, so you might as well just let the transceiver handle it for you. here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations. the handler for the track event on the remote peer will be responsible for determining what stream...
...create streams for you, the streams' track associations are automatically managed for you by the webrtc infrastructure. this includes things like changes to the transceiver's direction and tracks being halted using removetrack(). ...
RTCPeerConnection.peerIdentity - Web APIs
cription() cannot resolve until any target peer identity that's been set is validated. if the identity hasn't been validated yet, the promise returned by setremotedescription() will be rejected. if there's no target peer identity, setremotedescription() doesn't need to wait for validation to occur before it resolves. ...
...ed to wait for validation to occur before it resolves. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. if an error occurs and the promise is rejected, this logs the error to the console and returns null to the caller. let pc = new rtcpeerconnection(); /* ... */ async function getidentityassertion(pc) { try { const identity = await pc.peeridentity; return identity; } catch(err) { console.log("error identifying remote peer: ", err); return null; } } specifications specification status comment identity for webrtc candidate recommendation initial specification. ...
RTCPeerConnection.setRemoteDescription() - Web APIs
the rtcpeerconnection method setremotedescription() sets the specified session description as the remote peer's current offer or answer. the description specifies the properties of the remote end of the connection, including the media format. the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously. this is typically called after receiving an offer or answer from another peer over the signaling server. keep in mind that if setremotedescription() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). because descriptions will be exchanged until the two peers agree on a configuration, the description submitted...
...distinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated. return value a promise which is fulfilled once the value of the connection's remotedescription is successfully changed or rejected if the change cannot be applied (for example, if the specifie...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
nctions: the first, networkteststart(), captures an initial report, and the second, networkteststop(), captures a second report, then uses the two reports to output some information about the network conditions... xxx ... networkteststart() this function simply calls the rtcpeerconnection method getstats() to request an rtcstatsreport and store it in the variable startreport. let startreport; async function networkteststart(pc) { if (pc) { startreport = await pc.getstats(); } } given an rtcpeerconnection, pc, this calls its getstats() method to obtain a statistics report object, which it stores in startreport for use once the end-of-test data has been collected by networkteststop(). networkteststop() the networkteststop() function obtains a second report, endreport, then uses the...
... networkteststop() function now let's look at the networkteststop() function itself. it takes as input the rtcpeerconnection being tested, calls getstats() to get a new rtcstatsreport with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate html to the contents of the <div> element whose class is stats-box. ...
ReadableStream.ReadableStream() - Web APIs
at define how the constructed stream instance will behave. underlyingsource can contain the following: start(controller) this is a method, called immediately when the object is constructed. the contents of this method are defined by the developer, and should aim to get access to the stream source, and do anything else required to set up the stream fuctionality. if this process is to be done asynchronously, it can return a promise to signal success or failure. the controller parameter passed to this method is a readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream during set up. pull(controller) optional this method, also defined by the developer, will be called repeatedly ...
...lue of the type property. this can be used by the developer to control the stream as more chunks are fetched. cancel(reason) optional this method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if readablestream.cancel() is called). the contents should do whatever is necessary to release access to the stream source. if this process is asynchronous, it can return a promise to signal success or failure. the reason parameter contains a domstring describing why the stream was cancelled. type optional this property controls what type of readable stream is being dealt with. if it is included with a value set to "bytes", the passed controller object will be a readablebytestreamcontroller capable of handling a byob (bring your own buffe...
ReadableStream - Web APIs
rties readablestream.locked read only the locked getter returns whether or not the readable stream is locked to a reader. methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestream.getiterator() creates a readablestream async iterator instance and locks the stream to it. while the stream is locked, no other reader can be acquired until this one is released. readablestream.getreader() creates a reader and locks the stream to it. while the stream is locked, no other reader can be acquired until this one is released. readablestream.pipethrough() provides a chainable way of piping the current stream through a trans...
...estream to a given writablestream and returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestrea...
SourceBuffer - Web APIs
r.onupdatestart fired whenever the value of sourcebuffer.updating transitions from false to true. methods inherits methods from its parent interface, eventtarget. sourcebuffer.abort() aborts the current segment and resets the segment parser. sourcebuffer.appendbuffer() appends media segment data from an arraybuffer or arraybufferview object to the sourcebuffer. sourcebuffer.appendbufferasync() starts the process of asynchronously appending the specified buffer to the sourcebuffer. returns a promise which is fulfilled once the buffer has been appended. sourcebuffer.appendstream() appends media segment data from a readablestream object to the sourcebuffer. sourcebuffer.changetype() changes the mime type that future calls to appendbuffer() will expect the new data to conform to. ...
...is fulfilled once the buffer has been appended. sourcebuffer.appendstream() appends media segment data from a readablestream object to the sourcebuffer. sourcebuffer.changetype() changes the mime type that future calls to appendbuffer() will expect the new data to conform to. sourcebuffer.remove() removes media segments within a specific time range from the sourcebuffer. sourcebuffer.removeasync() starts the process of asynchronously removing media segments in the specified range from the sourcebuffer. returns a promise which is fulfilled once all matching segments have been removed. examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. this example was written by nick desaulniers and can be viewed live here (you can a...
SubtleCrypto.deriveBits() - Web APIs
equested for the derived key doesn't define a key length. supported algorithms see the supported algorithms section of the derivekey() documentation. examples note: you can try the working examples on github. ecdh in this example alice and bob each generate an ecdh key pair. we then use alice's private key and bob's public key to derive a shared secret. see the complete code on github. ...
...ebits method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user. ...
SubtleCrypto.deriveKey() - Web APIs
e to encrypt messages. see the complete code on github. ...
...ete code on github. /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. ...
SubtleCrypto.digest() - Web APIs
2 bits long. hint: if you are looking here for how to create an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead. examples basic example this example encodes a message, then calculates its sha-256 digest and logs the digest length: const text = 'an obscure body in the s-k system, your majesty. ...
...text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings. this example calculates a digest, then converts the arraybuffer to a hex string: const text = 'an obscure body in the s-k system, your majesty. ...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
een. return value a promise that resolves with a wakelocksentinel object. exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. ...
...o use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. examples the following asynchronous function requests a wakelocksentinel object. the request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. ...
WakeLock - Web APIs
Web › API › WakeLock
the wakelock interface of the screen wake lock api prevents device screens from dimming or locking when an application needs to keep running. the system wake lock is exposed through the global navigator.wakelock property. methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object. ...
...al navigator.wakelock property. methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object. examples the following asynchronous function requests a wakelocksentinel object. the wakelock.request method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
addeventlistener("click", handlestartbuttonclick); }); outputcanvas.addeventlistener("webglcontextlost", (event) => { /* the context has been lost but can be restored */ event.canceled = true; }); /* when the gl context is reconnected, reload the resources for the current scene. ...
...ch(err) { switch(err) { case aborterror: showsimplemessagebox("unable to transfer the game to your xr headset.", "cancel"); break; case invalidstateerror: showsimplemessagebox("you don't appear to have a compatible xr headset available.", "cancel"); break; default: handlefatalerror(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr = true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { currentscene = "scene1"; loadsceneresources(currentscene); /* a...
Migrating from webkitAudioContext - Web APIs
n of createbuffer() was potentially expensive, because it had to decode the audio buffer synchronously, and with the buffer being arbitrarily large, it could take a lot of time for this method to complete its work, and no other part of your web page's code could execute in the mean time. because of these problems, this version of the createbuffer() method has been removed, and you should use the asynchronous decodeaudiodata() method instead. the example below shows old code which downloads an audio file over the network, and then decoded it using createbuffer(): var xhr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { var decodedbuffer = context.createbuffer(xhr.response, false); if (decodedbuffer...
... this means that you may need to restructure your code to run the part which happened after the createbuffer() call in the success callback, as you can see in the example above. renaming ...
Functions and classes available to Web Workers - Web APIs
ing, for example), and an ongoing operation over a list of results. 41 (41) ? ? ? fetch the fetch spec provides an up-to-date definition of, and api for, fetching resources (e.g. across the network.) 39 (39) (mostly in 34 (34) behind pref, although a few features are later.) no support 42 41 behind pref 10.1 filereader this api allows asynchronous read of blob and file objects. 46 (46) no support (yes) no support filereadersync this api allows synchronous read of blob and file objects. this is an api that works only in workers. 8 (8) no support no support no support formdata formdata objects provide a way to easily construct a set of key/value pairs representing form fields and their v...
... for the given page. 34.0 (34.0) no support 33.0 no support performanceentry, performancemeasure, performancemark, performanceobserver, performanceresourcetiming enables retrieval and analysis of detailed data regarding various aspects of an application's network performance. (yes) (yes) (yes) (yes) promise javascript objects that allow you to write asynchronous functions. 28 (28) (yes) (yes) (yes) server-sent events allows a server to push data to a web page at any point, after a connection has been opened to it. 53 (53) (currently only available in dedicated and shared workers; not service workers.) ? (yes) ? serviceworkerregistration you can register a service worker from inside a standard worker,...
XMLDocument - Web APIs
methods also inherits methods from: document xmldocument.load() loads an xml document. specifications specification status comment domthe definition of 'xmldocument' in that specification. living standard no changes. dom4the definition of 'xmldocument' in that specification.
...4dde4" stroke-width="2px" /><text x="441" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">xmldocument</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} property also inherits properties from: document xmldocument.async used with xmldocument.load() to indicate an asynchronous request. methods also inherits methods from: document xmldocument.load() loads an xml document. specifications specification status comment domthe definition of 'xmldocument' in that specification. living standard no changes. dom4the definition of 'xmldocument' in that specification. obsolete initial definition. ...
Event reference
ice is rotated. mozaudioavailable event mozilla specific the audio buffer is full and the corresponding raw samples are available. mozbeforeresize mozilla specific a window is about to be resized. mozbrowseractivitydone firefox os browser api-specific sent when some activity has been completed (complete description tbd.) mozbrowserasyncscroll firefox os browser api-specific sent when the scroll position within a browser <iframe> changes. mozbrowseraudioplaybackchange firefox os browser api-specific sent when audio starts or stops playing within the browser <iframe> content. mozbrowsercaretstatechanged firefox os browser api-specific sent when the text selected inside the browser <i...
... os browser api-specific sent when the browser <iframe> content scrolls. mozbrowserscrollareachanged firefox os browser api-specific sent when the available scrolling area in the browser <iframe> changes. this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange firefox os browser api-specific sent when asynchronous scrolling (i.e. apcz) starts or stops. mozbrowsersecuritychange firefox os browser api-specific sent when the ssl state changes within a browser <iframe>. mozbrowserselectionstatechanged firefox os browser api-specific sent when the text selected inside the browser <iframe> content changes. note that this is deprecated, and newer implementations use ...
Ajax - Developer guides
Web › Guide › AJAX
when these technologies are combined in the ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and more responsive to user actions. ...
... strings, javascript object trees (jxon) or files. xpath xpath stands for xml path language, it uses a non-xml syntax that provides a flexible way of addressing (pointing to) different parts of an xml document. as well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. filereader api the filereader api lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using file or blob objects to specify the file or data to read. file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement. html in x...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
erently racy, as the content was inserted into a timing-dependent point in the source stream. if the call happened after the parser was done, the inserted content replaced the document. in ie, such calls are either ignored or imply a call to document.open(), replacing the document. ...
...scripts that serve racy code to firefox, perhaps while serving safe code to ie, will see a difference due to this change. ...
Index - Developer guides
Web › Guide › Index
found 43 pages: # page tags and summary 1 developer guides api, guide, landing, web these articles provide how-to information to help make use of specific web technologies and apis. 2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here. 4 getting started ajax, api, advanced, javascript, webmechanics, xmlhttprequest this article guides you through the ajax ...
...ixed version of the spec. 16 audio and video manipulation audio, canvas, examples, guide, html5, media, video, web audio api, webgl, developer recommendation the ability to read the pixel values from each frame of a video can be very useful. 17 event developer guide dom, event, guide, needsupdate, events events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types. 18 creating and triggering events advanced, dom, guide, javascript, needscontent, events this article demonstrates how to create and dispatch dom events. such events are commonly called synthetic events,...
Private class fields - JavaScript
// syntax error } } const instance = new classwithprivatefield() instance.#privatefield === 42 // syntax error private methods private static methods like their public equivalent, private static methods are called on the class itself, not instances of the class. like private static fields, they are only accessible from inside the class declaration. private static methods may be generator, async, and async generator functions. class classwithprivatestaticmethod { static #privatestaticmethod() { return 42 } static publicstaticmethod1() { return classwithprivatestaticmethod.#privatestaticmethod(); } static publicstaticmethod2() { return this.#privatestaticmethod(); } } console.assert(classwithprivatestaticmethod.publicstaticmethod1() === ...
...stances whose access is restricted in the same manner as private instance fields. class classwithprivatemethod { #privatemethod() { return 'hello world' } getprivatemessage() { return this.#privatemethod() } } const instance = new classwithprivatemethod() console.log(instance.getprivatemessage()) // expected output: "hello worl​d" private instance methods may be generator, async, or async generator functions. private getters and setters are also possible: class classwithprivateaccessor { #message get #decoratedmessage() { return `✨${this.#message}✨` } set #decoratedmessage(msg) { this.#message = msg } constructor() { this.#decoratedmessage = 'hello world' console.log(this.#decoratedmessage) } } new classwithprivateaccessor(); // expe...
Deprecated and obsolete features - JavaScript
o longer be used as of the indicated version of javascript. object property description __count__ returns the number of enumerable properties directly on a user-defined object. __parent__ points to an object's context. object.prototype.eval() evaluates a string of javascript code in the context of the specified object. ...
... array.unobserve() remove observers. number number.tointeger() parallelarray parallelarray statements for each...in is deprecated. use for...of instead. destructuring for...in is deprecated. use for...of instead. let blocks and let expressions are obsolete. e4x see e4x for more information. ...
Function.caller - JavaScript
this property replaces the obsolete arguments.caller property of the arguments object. the special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons. ...
... this property replaces the obsolete arguments.caller property of the arguments object. the special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons. ...
Promise.allSettled() - JavaScript
the promise.allsettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. it is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. ...
... the result of each promise. in comparison, the promise returned by promise.all() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting. syntax promise.allsettled(iterable); parameters iterable an iterable object, such as an array, in which each member is a promise. return value a pending promise that will be asynchronously fulfilled once every promise in the specified collection of promises has completed, either by successfully being fulfilled or by being rejected. at that time, the returned promise's handler is passed as input an array containing the outcome of each promise in the original set of promises. however, if and only if an empty iterable is passed as an argument, promise.allsettled() returns a ...
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a new instance object which is a stateful, executable instance of a webassembly.module. syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times. new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is thrown.
...e: 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 defi...
import - JavaScript
s. import { reallyreallylongmoduleexportname as shortname, anotherlongmodulename as short } from '/modules/my-module.js'; import a module for its side effects only import an entire module for side effects only, without importing anything. this runs the module's global code, but doesn't actually import any values. import '/modules/my-module.js'; this works with dynamic imports as well: (async () => { if (somethingistrue) { // import module for side effects await import('/modules/my-module.js'); } })(); if your project uses packages that export esm, you can also import them for side effects only. this will run the code in the package entry point file (and any files it imports) only. importing defaults it is possible to have a default export (whether it is an object, a f...
...rt will have to be declared first. for instance: import mydefault, * as mymodule from '/modules/my-module.js'; // mymodule used as a namespace or import mydefault, {foo, bar} from '/modules/my-module.js'; // specific, named imports when importing a default export with dynamic imports, it works a bit differently. you need to destructure and rename the "default" key from the returned object. (async () => { if (somethingistrue) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time. in situations where you wish to load a module conditionally or on demand, you can use a dynamic import instead. the following are...
Statements and declarations - JavaScript
ould an exception be thrown. declarations var declares a variable, optionally initializing it to a value. let declares a block scope local variable, optionally initializing it to a value. const declares a read-only named constant. functions and classes function declares a function with the specified parameters. function* generator functions enable writing iterators more easily. async function declares an async function with the specified parameters. return specifies the value to be returned by a function. class declares a class. iterations do...while creates a loop that executes a specified statement until the test condition evaluates to false. the condition is evaluated after executing the statement, resulting in the specified statement executing at least once. f...
...t is executed. for...in iterates over the enumerable properties of an object, in arbitrary order. for each distinct property, statements can be executed. for...of iterates over iterable objects (including arrays, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property. for await...of iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property. while creates a loop that executes a specified statement as long as the test condition evaluates to true. the condition is evaluated before executing the statement. others debugger invokes any available debugging functiona...
JavaScript reference - JavaScript
ndexed collections array int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array keyed collections map set weakmap weakset structured data arraybuffer sharedarraybuffer atomics dataview json control abstraction promise generator generatorfunction asyncfunction reflection reflect proxy internationalization intl intl.collator intl.datetimeformat intl.displaynames intl.listformat intl.locale intl.numberformat intl.pluralrules intl.relativetimeformat webassembly webassembly webassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly...
...ebassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly.linkerror webassembly.runtimeerror statements javascript statements and declarations control flowblock break continue empty if...else switch throw try...catch declarations var let const functions and classes function function* async function return class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators. primary expressionsthis function class function* yield yield* async function await [] {} /ab+c/i ( ) null left-hand-sid...
Compiling an Existing C Module to WebAssembly - WebAssembly
ct. many projects rely on autoconf/automake to generate system-specific code before compilation. emscripten provides emconfigure and emmake to wrap these commands and inject the appropriate parameters. you can find more in the emscripten documentation. now you only need some html and javascript to load your new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> and you will see the correct version number in the output: note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc. for example, v0.6.1 is encoded as 0x000601 = 1537. get an image from javascript into wasm getting the encoder's version ...
...oding an actual image would be more impressive. how do we do that? the first question you need to answer is: how do i get the image into wasm? looking at the encoding api of libwebp, you'll find that it expects an array of bytes in rgb, rgba, bgr or bgra. ...
Communicating using "port" - Archive of obsolete content
this page is now obsolete, and its content has been incorporated into the main page on content scripts. to enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port object. to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing. here's a simple add-on that sends a message to a content script using port: var tabs = require("sdk/tabs"); var alertcontentscript = "self.port.on('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("ready", fun...
Content Scripts - Archive of obsolete content
message); }; anotherelement.addeventlistener("click", function() { alert(themessage); }); communicating with the add-on to enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port object. to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing. here's a simple add-on that sends a message to a content script using port: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.on("ready", function(tab) { var worker = tab.attach({ contentscriptfile: self.data.url("content-script.js")...
passwords - Archive of obsolete content
oncomplete is called when the operation has completed successfully and onerror is called when the function encounters an error. because the search function is expected to return a list of matching credentials, its oncomplete option is mandatory. because the other functions don't return a valu...
content/symbiont - Archive of obsolete content
you map optionally pass a frame into the symbiont's constructor: if you don't, then a new hidden frame will be created to host the content. this trait is composed from the loader and worker traits. ...
io/text-streams - Archive of obsolete content
true if the stream is closed. textwriter methods close() flushes the backing stream's buffer and closes both the stream and the backing stream. if the stream is already closed, an exception is thrown. flush() flushes the backing stream's buffer. write(str) writes a string to the stream. if the stream is closed, an exception is thrown. parameters str : string the string to write. writeasync(str, callback) writes a string on a background thread. after the write completes, the backing stream's buffer is flushed, and both the stream and the backing stream are closed, also on the background thread. if the stream is already closed, an exception is thrown immediately. parameters str : string the string to write. callback : callback callback, if given, must be a function. it's called...
places/bookmarks - Archive of obsolete content
e bookmarks. usage this module exports: three constructors: bookmark, group, and separator, corresponding to the types of objects, referred to as bookmark items, in the bookmarks database in firefox two additional functions, save() to create, update, and remove bookmark items, and search() to retrieve the bookmark items that match a particular set of criteria. save() and search() are both asynchronous functions: they synchronously return a placesemitter object, which then asynchronously emits events as the operation progresses and completes. each retrieved bookmark item represents only a snapshot of state at a specific time. the module does not automatically sync up a bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user. ...
places/favicon - Archive of obsolete content
helper functions for working with favicons. globals functions getfavicon(object, callback) takes an object that represents a page's url and returns a promise that resolves with the favicon url for that page. the object can be a url string or a tab. the platform service (moziasyncfavicons) retrieves favicon data stored from previously visited sites, and as such, will only return favicon urls for visited sites. let { getfavicon } = require("sdk/places/favicon"); // string example getfavicon("http://mozilla.org").then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); // tab example require("sdk/tabs").open({ url: "http://mozilla.org", onready: function (tab) { getfavicon(tab).then(function (url) { console.log(url); // http://moz...
places/history - Archive of obsolete content
access the user's browsing history. usage this module exports a single function, search(), which synchronously returns a placesemitter object which then asynchronously emits data and end or error events that contain information about the state of the operation. example let { search } = require("sdk/places/history"); // simple query search( { url: "https://developers.mozilla.org/*" }, { sort: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with '...
remote/parent - Archive of obsolete content
onst { frames, remoterequire } = require("sdk/remote/parent"); remoterequire("./remote.js", module); // the first argument is the frame the message came from frames.port.on("pageshow", (frame) => { console.log(frame.frameelement.currenturi.host + ": pageshow"); }); globals functions remoterequire(id, module = null) loads a module in any existing and future child processes. the module loads asynchronously but you can start sending messages to the module immediately. you can use an absolute path to the module or a relative path. if you use a relative path, you must use the module parameter. const { remoterequire } = require("sdk/remote/parent"); remoterequire("./my-module.js", module); note that even single-process applications have a process that contains content frames. for consistenc...
ui/frame - Archive of obsolete content
r the content loaded into the frame. this is read-only. it's only accessible after the attach event has occurred for this frame. events attach this event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar containing this frame. since the event is dispatched asynchronously, the document may already be loaded by the time the event is received. at this point, you should not try to send messages to scripts hosted in the frame, because the frame scripts may not have been loaded. arguments event : this contains two properties: source, which defines a postmessage() function which you can use to send messages back to this particular frame instance. but note...
Low-Level APIs - Archive of obsolete content
scripts to it. content/worker used in the internal implementation of sdk modules which use content scripts to interact with web content. core/heritage helper functions for inheritance. core/namespace provides an api for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public api. core/promise implementation of promises to make asynchronous programming easier. dev/panel enables you to extend the firefox developer tools. event/core the event/core module allows the creation of apis to broadcast and subscribe to events. event/target create objects that broadcast events. frame/hidden-frame creates firefox frames (i.e. xul <iframe> elements) that are not displayed to the user. frame/utils provides helper functions for wo...
Open a Web Page - Archive of obsolete content
to do this, pass a callback function into open(). ...
JavaScript Debugger Service - Archive of obsolete content
however, jsd has been removed in favor of the debugger api. see the tracking bug bug 800200 for more details. snippets acquiring the service we acquire the service by calling the xpcom object. var jsd = components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getservice(components.interfaces.jsdidebuggerservice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism. next, we add code to the various hooks. jsd.scripthook = { onscriptcreated: function(script) { // your function here }, onscriptdestroyed: function(script) { // your function here } }; jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { // ...
Miscellaneous - Archive of obsolete content
e application running us services.appinfo.name; // returns "firefox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see around here: http://mxr.mozilla.org/mozilla1.8/so...pdates.js#1631 bug 338039 tracks improving this situatio...
How to convert an overlay extension to restartless - Archive of obsolete content
n 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) returnresult(request.response); else request.onerror(event); }; request.send(); } loadfile("chrome://myaddon/content...
Jetpack Processes - Archive of obsolete content
ovided to jetpack processes as of bug 588563. a mechanism to optionally disable this feature has been proposed in bug 614351. privileged apis when script is evaluated in a jetpack process via a call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process. callmessage(amessagename [, v1 [, v2 [, ...]]]) this function is like sendmessage() but sends the message synchronously. it returns an array whose elements are the return values of each receiver in the chrome process that was triggered by the message. registerreceiver(amessagename, areceiver) similar to nsijetpack.registerreceiver(), this function r...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
, aoverwrite) restores the browser window indicated by the parameter awindow to the state indicated by astate. if aoverwrite is true, the currently open tab is overwritten; otherwise, a new tab is created for the restored content. javascript debugging methods alert the easiest way to debug javascvript is using the window.alert method to display variables in a dialog (listing 29). except for asynchronous processes, all processing stops while the dialog is up, so this technique is useful when you want to pin down a value that can vary during a process. listing 29: check the value of variable foo alert(foo); dump in a windows environment, you can launch firefox with the -console argument, which opens a dump console. using the dump method, you can send text to the dump console (listing 30...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
her ways that made web pages less useful to users, the language acquired a reputation as having little practical use and lacking in functionality. also, because a series of security holes were discovered in javascript and the compatible technology jscript, there was an initial reluctance to use javascript at all. nevertheless, the rise of web services like google maps, which used javascript and asynchronous communications, created an awareness of a set of technologies nicknamed ajax (asynchronous javascript and xml); that plus the advent of a number of libraries that paper over implementation differences between different web browsers has more recently led to a re-evaluation of javascript as a programming language. javascript is a prototype-based object-oriented language, and as shown in lis...
Adding menus and submenus - Archive of obsolete content
you should follow the standard used in firefox: show a single disabled item with an "(empty)" label. if filling your menu takes a noticeable amount of time, you should not make firefox (and your users) wait for it to fill up before displaying anything. it's best to show an item with a throbber image (see chrome://global/skin/icons/loading_16.png) so the user knows there's something going on, and asynchronously fill its contents. we'll look into some asynchronous techniques further ahead in the tutorial. adding elements to existing menus just as explained in the previous sections, the best place to overlay your extension menu is inside the tools menu. that is, unless there's a place inside the menu structure where your extension menus make more sense. if you're overlaying the tools menu, you...
Custom XUL Elements with XBL - Archive of obsolete content
way you reduce your dependency on specific scripts, and your tag behaves more like the rest. just like fields and properties, methods are easy to invoke if you have a reference to the object that corresponds to the node. we have experienced problems when calling methods and setting properties on xbl nodes right after they are created and inserted to the document. this is likely due to some asynchronous operation related to node insertion. if you need to perform an operation to a node right after insertion, we recommend using a timeout to delay the operation (a timeout set to 0 works well). handlers the handlers and handler xbl elements are used to define event handlers for the element. we have a "click" handler that displays the greeting when the "person" element is clicked: <hand...
Local Storage - Archive of obsolete content
ating the local database you'll be using for your extension: generate the database file (through mozistorageservice.opendatabase(), all tables (through mozistorageconnection.createtable(), and initial data when your extension starts up for the first time. if you need a complex database this can be heavy in terms of time and code, but this will only happen once and this can be done in a lazy or asynchronous way. have an initial database file in your defaults directory that you can copy to the user's profile. this way you just need to do a file copy. you can reach the defaults directory at profd/extensions/your_extension_id.xpi/defaults for packed extensions or profd/extensions/your_extension_id/defaults for unpacked extensions. packed extensions have appear with gecko 2.0 (firefox 4.0). this...
Creating a dynamic status bar extension - Archive of obsolete content
bol goog). refreshinformation() embeds another function, inforeceived(), which we'll look at separately shortly. the first thing we do is create a new xmlhttprequest object to use for processing our request. we open the request, specifying that we wish to perform an http "get" command with the url fullurl. the true boolean value in the third parameter indicates that we want to process the request asynchronously. setting the httprequest.onload property to our inforeceived() function configures the request to call inforeceived() when the response is received from the server. finally, we send the request to the server and return. inforeceived() when the server responds to our request, our the inforeceived() function, which is embedded inside refreshinformation(), gets called automatically. we embe...
Index of archived content - Archive of obsolete content
y npn_getvalue npn_getvalueforurl npn_hasmethod npn_hasproperty npn_identifierisstring npn_intfromidentifier npn_invalidaterect npn_invalidateregion npn_invoke npn_invokedefault npn_memalloc npn_memflush npn_memfree npn_pluginthreadasynccall npn_posturl npn_posturlnotify npn_releaseobject npn_releasevariantvalue npn_reloadplugins npn_removeproperty npn_requestread npn_retainobject npn_setexception npn_setproperty npn_setvalue npn_setvalueforurl npn_status npn_utf8f...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
3,163" href="#stream-converter"> <area alt="(11)" coords="485,133,537,163" href="#contenthandler"> <area alt="(9)" coords="445,132,484,165" href="#nsdocumentopeninfo::dispatchcontent"> <area alt="(8)" coords="405,133,439,162" href="#onstartrequest-innards"> <area alt="(7) onstartrequest()" coords="639,129,703,129,703,165,833,165,833,204,639,204" href="#onstartrequest" shape="poly"> <area alt="(6) asyncopen()" coords="637,121,709,121,709,96,783,96,783,58,637,58" href="#asyncopen" shape="poly"> <area alt="(5) open()" coords="311,306,432,371" href="#open"> <area alt="(4)" coords="90,384,127,417" href="#openuri-innards"> <area alt="(0) registercontentlistener()" coords="37,474,346,474,346,505,88,505,88,535,37,535" href="#registercontentlistener" shape="poly"> <area alt="(3) openuri() (nsuriloader)"...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
pack.me.onfirstrun() allows jetpacks to be notified after they are successfully installed. onfirstrun() accepts a callback which is called after installation. note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jquery ready callback. onfirstrun() may be called anywhere in your jetpack, but if it is called as the result of some asynchronous operation such as a timeout or xmlhttprequest, it is ignored. if you call it multiple times, all but the final call are ignored. funca function. it takes no paramenters. inside the function, this is the jetpack's content.function example jetpack.me.onfirstrun(function(){ jetpack.notifications.show("oh boy, i'm installed!");}); ...
Tuning Pageload - Archive of obsolete content
d time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the event loop, which allows layout and painting to happen. if the parser gets a large chunk of data, it will try to parse it all, building the corresponding content model. since layout and painting happen asynchronously, while the parser is working there is no layout or painting. so this preference is used to increase responsiveness, especially on cached loads (where data comes into the parser in large chunks) content.max.tokenizing.time controls how often the sink interrupts the parser. the parser is interrupted at least every content.max.tokenizing.time microseconds, if it can be interrupted at al...
visuallyselected - Archive of obsolete content
if your code needs to apply some styling to the currently selected tab, this is the attribute you should use from firefox 40 onwards. ...
Using the Editor from XUL - Archive of obsolete content
ute on the content frame was set to about:blank (our default 'blank page' url). we can't set that before xul parsing, so we have to force a load of the page we now want to edit. we get the url to load from the args element, then kick off the load: var url = document.getelementbyid("args").getattribute("value"); editorshell.loadurl(url); loading the document in the <iframe> of course happens asynchronously, so we need to know when we have a document that we can start editing. nseditorshell is able to observe the document load on the <iframe>, because it implements nsidocumentloaderobserver, and registered itself as a doc loader when it was assigned the content window. it thus gets callbacks for the start, progress, and end of the document load. note: these callbacks also fire for eve...
2006-10-27 - Archive of obsolete content
ith firefox 2.0 out the door, it's time to make sure that all 1.5.0.x users are updated with the latest and greatest in stability and security fixes! testers are needed. discussions need to unit test innerhtml - someone needs to unit test innerhtml. he recommends that a non-xpcshell environment is needed really badly, but the big issue is that the xpcshell doesn't have an event loop, so nothing asynchronous can be tested. cross-domain testing - someone is suggesting that there needs to be some way of running cross-domain tests (security, web compat, etc), and is wondering if it's possible with the current test http server? update welcome page - a bug has been discovered when updating to firefox 2.0. when the special homepage comes up after updating firefox, the "go to your homepage" butto...
2006-11-10 - Archive of obsolete content
meetings none during this week. ...
2006-12-01 - Archive of obsolete content
lightning, broken accessibility discussions refering several accessibility issues regarding interface of the sunbird client and the lightning plug-in for thunderbird. tasks in sunbird & lightning discussion about how to accessing the tasks in view in sunbird and lightning. ...
Browser-side plug-in API - Archive of obsolete content
e introduction. warning: you must only call these from the main thread; calling them from other threads is not supported and may have unpredictable results. ...
NPN_GetURL - Archive of obsolete content
nother blank window is opened along with the mail or news window. when the plug-in uses a _self target, no other instance is created; the plug-in usually continues to operate successfully in its own window. the safest target is _blank, even though this creates an extra blank the browser instance. the plug-in developer cannot influence the way that the browser handles npn_geturl(). it is typically asynchronous but this is not guaranteed. the plug-in could call npn_geturl() and receive data from the url right away, but more often the data arrives later. the rest of the the browser interface keeps running until the data is available. see also npn_geturlnotify() npn_posturl() npn_posturlnotify() npp_urlnotify() npp ...
NPN_GetURLNotify - Archive of obsolete content
nction returns an error code. for possible values, see error codes. description npn_geturlnotify() works just like npn_geturl(), with one exception: npn_geturlnotify() notifies the plug-in instance upon successful or unsuccessful completion of the request by calling the plug-in's npp_urlnotify() function and passing it the notifydata value. npn_geturlnotify() typically handles the url request asynchronously. it returns immediately and only later handles the request and calls npp_urlnotify(). this notification is the only way the plug-in can tell whether a request with a null target failed, or that a request with a non-null target completed. for requests that complete unsuccessfully, the browser calls npp_urlnotify() as soon as possible. for requests that complete successfully: if the ta...
NPN_InvalidateRect - Archive of obsolete content
he plug-in's content area. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidaterect() causes the npp_handleevent() method to pass an update event or a paint message to the plug-in. after calling this method, the plug-in receives a paint message asynchronously. the browser redraws invalid areas of the document and any windowless plug-ins at regularly timed intervals. to immediately send a paint message, the plug-in can call npn_forceredraw() after calling this method. see also npn_forceredraw() npn_invalidateregion() nprect npp ...
NPN_PostURL - Archive of obsolete content
to specify headers (even a blank line) in a memory buffer. to do this, use npn_posturlnotify. for protocols in which the headers must be distinguished from the body, such as http, the buffer or file should contain the headers, followed by a blank line, then the body. if no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. npn_posturl is typically asynchronous: it returns immediately and only later handles the request. for this reason, you may find it useful to call npn_posturlnotify instead; this function notifies your plug-in upon successful or unsuccessful completion of the request. see also npn_geturl, npn_geturlnotify, npn_posturlnotify, npp ...
NPN_PostURLNotify - Archive of obsolete content
turns an error code. for possible values, see error codes. description npn_posturlnotify functions identically to npn_posturl, with these exceptions: npn_posturlnotify supports specifying headers when posting a memory buffer. npn_posturlnotify calls npp_urlnotify upon successful or unsuccessful completion of the request. for more information, see npn_posturl. npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify. if this function is called with a target parameter value of _self or a parent to _self, this function should return an invalid_param nperror. this is the only way to notify the plug-in once it is deleted. see npn_geturl for information about this parameter. see also npn_geturl, npp_urlnotify, npn_posturl...
NPAPI plugin reference - Archive of obsolete content
repainting or refreshing a windowless plug-in. npn_invoke invokes a method on the given npobject. npn_invokedefault invokes the default method, if one exists, on the given npobject. npn_memalloc allocates memory from the browser's memory space. npn_memflush requests that the browser free a specified amount of memory. npn_memfree deallocates a block of allocated memory. npn_pluginthreadasynccall thread safe way to request that the browser calls a plug-in function on the browser or plugin thread (the thread on which the plug-in was initiated). npn_posturl posts data to a url. npn_posturlnotify posts data to a url, and receives notification of the result. npn_releaseobject decrements the reference count of the given npobject. if the reference count reaches 0, the npobject is dea...
SAX - Archive of obsolete content
below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this call results in the following output (assuming the content handler from the example above is used): startdocument startelement: namespace='g', localname='a', qname='f:a', attributes={d='1'} startelement: namespace='', lo...
Using JavaScript Generators in Firefox - Archive of obsolete content
you can opt in in html as follows: <script type="text/javascript;version=1.7" src="myscript.js"></script> then your myscript.js file might look like this: // need to stash the generator in a global variable. var generator; // simple event listener function to pass the received event to the generator. function grabevent(event) { generator.send(event); } // when we're all done we can close the generator, but that must happen outside // of the generator so we use a timeout. ...
Array.observe() - Archive of obsolete content
it provided a stream of changes in order of occurrence. it's equivalent to object.observe() invoked with the accept type list ["add", "update", "delete", "splice"]. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax array.observe(arr, callback) parameters arr the array to be observed. callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. ...
Object.observe() - Archive of obsolete content
it provided a stream of changes in the order in which they occur. however, this api has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax object.observe(obj, callback[, acceptlist]) parameters obj the object to be observed. callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. object: the changed object after the change was made. type: a string indicating the type of change taking place. ...
Archived open Web documentation - Archive of obsolete content
pecific code, it may be time to upgrade: stopiteration the stopiteration object was used to tell the end of the iteration in the legacy iterator protocol. do not use this ancient feature. styling the amazing netscape fish cam page using javascript generators in firefox generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later. you can opt in in html as follows: window.importdialog() because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a new window, it merges the specified xul dial...
Anatomy of a video game - Game development
th a 60 hz display. browsers invoke your code as early as possible to give it maximum computation time. your main thread will often start workloads that are not even on the main thread (such as rasterization or shaders in webgl). long calculations can be performed on a web worker or a gpu at the same time as the browser uses its main thread to manage garbage collection, its other tasks, or handle asynchronous events. while we are on the topic of budgeting time, many web browsers have a tool called high resolution time. the date object is no longer the recognised method for timing events because it is very imprecise and can be modified by the system clock. high resolution time, on the other hand, counts the number of milliseconds since navigationstart (when the previous document is unloaded). t...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest. ajax allows you to update parts of the dom of an html page instead without the need for a full page refresh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard. ...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
d of routine or action. here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately. note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. this structure is used in many modern web apis, such as fetch(). learn more general knowledge callback on wikipedia ...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
lues. if the document is well-formed, parsing it is straightforward and faster. the parser parses tokenized input into the document, building up the document tree. when the html parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. parsing can continue when a css file is encountered, but <script> tags—particularly those without an async or defer attribute—blocks rendering, and pauses parsing of html. when the browser encounters css styles, it parses the text into the css object model (or cssom), a data structure it then uses for styling layouts and painting. the browser then creates a render tree from both these structures to be able to paint the content to the screen. javascript is also downloaded, parsed, and then execute. ...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
ade, through the downloading, parsing and execution of all resources, and the final paint. while increased performance generally increases perceived performance, there are some techniques that can be used to increase perceived performance while marginally decreasing actual performance. there are front end optimization techniques that can improve perceived performance, such as adding the defer or async attribute to scripts, or placing scripts at the end of documents, and placing css in the head of documents. learn more perceived performance ...
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
a promise is an object that's returned by a function that has not yet completed its work. the promise literally represents a promise made by the function that it will eventually return a result through the promise object. when the called function finishes its work asynchronously, a function on the promise object called a resolution (or fulfillment, or completion) handler is called to let the original caller know that the task is complete. learn more to learn more, have a look at these links. general knowledge futures and promises technical reference promise in the javascript reference. using promises ...
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
xmlhttprequest (xhr) is a javascript api to create ajax requests. its methods provide the ability to send network requests between the browser and a server. learn more general knowledge xmlhttprequest on wikipedia synchronous vs. asynchronous communications technical information the xmlhttprequest object. the documentation on mdn about how to use xmlhttprequest. ...
beacon - MDN Web Docs Glossary: Definitions of Web-related terms
dded in markup, used to communicate information back to the web server or to 3rd party servers. beacons are generally included to provide information about the user for statistical purposes. beacons are often included within third party scripts for collecting user data, performance metrics and error reporting. there is a w3c draft beacon specification to standardize the beacon as an interface to asynchronously transfer http data from user agent to a web server prior to page load without negative performance impact. see also real user monitoring (rum) ...
MDN Web Docs Glossary: Definitions of Web-related terms
abstraction accessibility accessibility tree (aom) adobe flash ajax algorithm alignment container alignment subject alpha (alpha channel) alpn api apple safari application context argument aria arpa arpanet array ascii asynchronous atag attribute b bandwidth base64 baseline beacon bézier curve bidi bigint blink block block (css) block (scripting) block cipher mode of operation boolean boot2gecko bootstrap bounding box breadcrumb ...
Front-end web developer - Learn web development
in each module are designed to test your knowledge of the subject matter. completing the assessments confirms that you are ready to move on to the next module. modules javascript first steps (30–40 hour read/exercises) javascript building blocks (25–35 hour read/exercises) introducing javascript objects (25–35 hour read/exercises) client-side web apis (30–40 hour read/exercises) asynchronous javascript (25–35 hour read/exercises) web forms — working with user data time to complete: 40–50 hours prerequisites forms require html, css, and javascript knowledge. given the complexity of working with forms, it is a dedicated topic. how will i know i'm ready to move on? the assessments in each module are designed to test your knowledge of the subject matter. completing t...
Tips for authoring fast-loading HTML pages - Learn web development
nts should be based on the consideration of modern browsers that support the relevant standards. this can include recent versions of firefox, internet explorer, google chrome, opera, and safari. note, however, that many of the tips listed in this article are common-sense techniques which apply to any user agent, and can be applied to any web page, regardless of browser-support requirements. use async and defer, if possible make the javascript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script tags. with that, the page can stop rendering while javascript is still loading. otherwise, the browser will not render anything that is after the script tags that do not have these attributes. no...
Use JavaScript within a webpage - Learn web development
cal order. if you use pointer events (like mouse events or touch events), duplicate the functionality with keyboard events. test your site using a keyboard only. don't set nor even guess time limits. it takes extra time to navigate with the keyboard or hear content read out. you can hardly ever predict just how long it will take for users or browsers to complete an process (especially asynchronous actions such as loading resources). keep animations subtle and brief with no flashing. flashing is annoying and can cause seizures. additionally, if an animation lasts more than a couple seconds, give the user a way to cancel it. let users initiate interactions. that means, don't update content, redirect, or refresh automatically. don't use carousels or display popups without warning. h...
Test your skills: JSON - Learn web development
those details to the kitteninfo variable string. the last mother cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why are the para1.textcontent = motherinfo; and para2.textcontent = kitteninfo; lines inside the displaycatinfo() function, and not at the end of the script? this has something to do with async code. try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above. the example won't work locally, or in an environment like codepen or jsfiddle, because of something called cross-origin security. this basically means that you can't request a file from one origin using code on a different...
JavaScript — Dynamic client-side scripting - Learn web development
ons and variables into efficient packages. the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it. asynchronous javascript in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. client-side web apis when writing client-side javascript for web sites or applications, you won't go very far before you start to use apis — interfaces for manipulating differe...
HTML performance features - Learn web development
of client-side web technologies. objective: to learn about the impact of html elements and attributes on web performance optimization. elements & attributes impacting performance the <picture> element the <video> element the <source> element the <img> srcset attribute responsive images preloading content with rel="preload" - (https://w3c.github.io/preload/ ) async / defer attributes <iframe> <object> <script> rel attribute conclusion previous overview: performance next in this module the "why" of web performance what is web performance? how do users perceive performance? measuring performance multimedia: images multimedia: video javascript performance best practices. html performance features css performance features fonts and p...
What is web performance? - Learn web development
dule. to summarize, many features impact performance including latency, application size, the number of dom nodes, the number of resource requests made, javascript performance, cpu load, and more. it is important to minimize the loading and response times, and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. note: web performance includes both objective measurements like time to load, frames per second, and time to interactive, and subjective experiences of how long it felt like it took the content to load. how content is rendered to effectively understand web performance, the issues behind it, and the major topic areas we mentioned ab...
Server-side web frameworks - Learn web development
ameworks) are based on express, including feathers, itemsapi, keystonejs, kraken, loopback, mean, and sails. a lot of high profile companies use express, including: uber, accenture, ibm, etc. (a list is provided here). deno (javascript) deno is a simple, modern, and secure javascript/typescript runtime and framework built on top of chrome v8 and rust. deno is powered by tokio — a rust-based asynchronous runtime which lets it serve web pages faster. it also has internal support for webassembly, which enables the compilation of binary code for use on the client-side. deno aims to fill in some of the loop-holes in node.js by providing a mechanism that naturally maintains better security. deno's features include: security by default. deno modules restrict permissions to file, network, or ...
Ember resources and troubleshooting - Learn web development
problems that any app dealing with data will run in to, it is possible to roll your own front-end data client. a common alternative is to any fully-featured front-end data client is the fetch api. using the design patterns provided by the framework, a route using fetch() would look something like this: import route from '@ember/routing/route'; export default class myroute extends route { async model() { let response = await fetch('some/url/to/json/data'); let json = await response.json(); return { data: json }; } } see more information on specifying the route's model here. why can't i just use javascript? this is the most common question ember folks hear from people who have previous experience with react. while it is technically possible to use jsx, or any...
Getting started with Svelte - Learn web development
lue of the name prop right after the hello text. <main> <h1>hello {name}!</h1> <p>visit the <a href="https://svelte.dev/tutorial">svelte tutorial</a> to learn how to build svelte apps.</p> </main> svelte also supports tags like {#if...}, {#each...}, and {#await...} — these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively. the <style> section if you have experience working with css, the following snippet should make sense: <style> main { text-align: center; padding: 1em; max-width: 240px; margin: 0 auto; } h1 { color: #ff3e00; text-transform: uppercase; font-size: 4em; font-weight: 100; } @media (min-width: 640px) { main { max-width: non...
Introducing a complete toolchain - Learn web development
and the command line. to start parcel off in the background, go to your terminal and run the following command: npx parcel src/index.html you should see an output like this (once the dependencies have been installed): server running at http://localhost:1234 ✨ built in 129ms. parcel also installs the dependencies that we will use in our code, including react, react-dom, react-async-hook, date-fns, and format-number. this first run will therefore be longer than a typical run of parcel. note: if you run parcel on this project and are faced with an error that reads error: enoent: no such file or directory, stop the process using ctrl + c and then try re-running it. the server is now running on the url that was printed (in this case localhost:1234). go to this...
Gecko info for Windows accessibility vendors
gh msaa events, rather than dom events. xul: extensible user-interface language the xml-based language used by firefox and mozilla to develop the ui. similar to html in that it can be combined with css and javascript to make powerful applications. contains more desktop-style widgets than html and follows a box layout model, rather than being text-flow based. ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load. data is therefore stored and retrieved dynamically much faster. roles, states and events: please read the ms...
Benchmarking
ol that causes crashes to happen sooner and produce much more actionable information, but also slow down regular usage substantially. in particular, "gc poisoning" is used in all debug builds, and in optimized nightly builds (but not opt developer edition or beta builds). the poisoning can be disabled by setting the environment variable jsgc_disable_poisoning=1 before starting the browser. async stacks async stacks no longer impact performance since firefox 78, as bug 1601179 limits async stack capturing to when devtools is opened. another option that is on by default in non-release builds is the preference javascript.options.asyncstack, which provides better debugging information to developers. set it to false to match a release build. (this may be disabled for many situations in th...
Browser chrome tests
sing a descriptive file name is strongly encouraged instead of just using a bug number. you can collect common utils and helpers in a file called head.js, that must live in the same folder as the browser-chrome tests. this file will be injected into the test scope for each test living in the same folder. notice that any function call in head.js main scope will run before the main test() method. asynchronous tests when writing async tests, you can use the add_task method with promises. the test suite also supports asynchronous tests, using the same function names as mochitest. call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned. call finish() once the test is complete. be aware that the test harness will mark tests that take too lo...
Experimental features in Firefox
ta useful for presenting a user interface for managing media playback, and to obtain media file metadata. see bug 1112032 for more details. release channel version added enabled by default? nightly 71 yes developer edition 71 no beta 71 no release 71 no preference name dom.media.mediasession.enabled asynchronous sourcebuffer add and remove this adds the promise-based methods appendbufferasync() and removeasync() for adding and removing media source buffers to the sourcebuffer interface. see bug 1280613 and bug 778617 for more information. release channel version added enabled by default? nightly 62 no developer edition 62 no beta 62 ...
Frame script environment
aded in the browser. may be null (see below) docshell the nsidocshell associated with the browser. addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. dump() print a message to the console. atob() base64 decode. btoa() base64 encode. components the usual components object. in particular, note that a frame script accesses the dom window using content, not window: // frame ...
Limitations of chrome scripts
necessary: define and register nsicontentpolicy in the content process. if you need to ensure that the policy is only registered once, use a process script to register the policy. nsiwebprogresslistener this api will work in the chrome process. there is a shim that gives you access to the domwindow property of the nsiwebprogress object passed into onstatechange. however, the domwindow is passed asynchronously, so by the time the chrome process receives it, the dom might have changed (for example, because code running in the content process modified it or we navigated to a different page). we're working on fixing this issue in bug 1118880. also note that unlike other shims, this shim is always active. alternatively, you can use nsiwebprogresslistener in the content process. observers in the...
Frame script environment
oaded in the browser may be null (see below) docshell the nsidocshell associated with the browser. addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. dump() print a message to the console. atob() base64 decode. btoa() base64 encode. components the usual components object. in particular, note that a frame script accesses the dom window using content, not window: // frame ...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
nt. these use htmliframeelement.getcangoback() and htmliframeelement.getcangoforward(), which return a boolean defining whether backward/forward navigation is possible at this point in the history. if true is returned, the relevant button is disabled, and if false is returned, the relevant button is enabled. note that promise versions of browser api dom request methods also exist, so you can use async promise style syntax if you so wish. for example: function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }); } implementing the url bar th...
mozbrowserclose
bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. ...
mozbrowsercontextmenu
which item has been selected. items an array of further menu objects, which indicate the menu options available in a menu, if the context menu being accessed is a menu. ...
mozbrowserdocumentfirstpaint
the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. ...
mozbrowsererror
notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfailure remotexul unsafecontenttype corruptedcontenterror certerror other example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsererror", function( event ) { console.log("an error occurred:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserfindchange
hordinal a number indicating the position of the currently highlighted search result, e.g. 3 out of 5. ...
mozbrowserfirstpaint
the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. ...
mozbrowsericonchange
". the any keyword can also be used, to represent "any size." rel a domstring representing the rel attribute value from the <link> element used to link to the icon. ...
mozbrowserloadend
alue reported is rgb(0, 83, 159). ...
mozbrowserloadstart
wserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (r), as appropriate. ...
mozbrowserlocationchange
defines whether it's possible to go forward in the navigation history (true) or not (false). example this example updates the url bar so that it will always display the correct url for the current location. ...
mozbrowsermanifestchange
object a custom object. details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest. ...
mozbrowsermetachange
e attribute value, if included. if not included, the value returned is undefined. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermetachange", function(event) { console.log("a meta tag has been " + event.details.type + ". ...
mozbrowseropensearch
pt object with the following properties: title a domstring representing the title of the search engine. href a domstring representing url of the search engine. ...
mozbrowseropentab
erty returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded. ...
mozbrowseropenwindow
list of possible features, see window.open(). frameelement an object representing the new browser <iframe> that will embed the new content. ...
mozbrowserresize
width of the <iframe> viewport, in device pixels. height a number representing the new height of the <iframe> viewport, in device pixels. ...
mozbrowserscroll
the new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport. ...
mozbrowserscrollareachanged
, in css pixels. height a number representing the new scroll area height of the <iframe> viewport, in css pixels. ...
mozbrowsersecuritychange
acking content is present on the current page (true) or not (false). mixedcontent a boolean indicating if mixed content is present on the current page (true) or not (false). ...
mozbrowserselectionstatechanged
e (true) or not (false). states the current state of the selection. ...
mozbrowsershowmodalprompt
presenting the type of message. for that event, it's always showmodalprompt. initialvalue a string representing the initial value for the window.prompt() methods. ...
mozbrowsertitlechange
bubbles or not. cancelable read only boolean whether the event is cancellable or not. detail read only string the title of the document. ...
mozbrowserusernameandpasswordrequired
ead. it needs to take two parameters — the username and password to authenticate. cancel() a function that is called to cancel the authentication. ...
mozbrowservisibilitychange
: visible a boolean that indicates whether the browser iframe is visible (true) or not (false). ...
Implementing Download Resuming
then, you can check if it implements nsiresumablechannel. if it does not, the protocol does not support resuming. otherwise, call resumeat with the desired start position, and the previously stored entity id. (it is possible to pass an empty string as the id; however, this means that you have no assurance that the file remained unchanged) now, you can open the channel as usual (using nsichannel.asyncopen() in the common case) and write to the file in the ondataavailable notifications. you may want to use nsisimplestreamlistener to simplify this task; to get progress notifications, you can implement nsiprogresseventsink and set an interface requester as the notificationcallbacks of the channel that gives out such an event sink (this needs to be done before calling asyncopen). note: in version...
Addon
ds iscompatiblewith() tests whether this add-on is known to be compatible with a particular application and platform version. void iscompatiblewith( in string appversion, in string platformversion ) parameters appversion an application version to test against platformversion a platform version to test against findupdates() starts an update check for this add-on. this will perform asynchronously and deliver results to the given listener. void findupdates( in updatelistener listener, in integer reason, in string appversion, in string platformversion ) parameters listener an updatelistener for the update process reason a reason code for performing the update appversion an application version to check for updates for platformversion a platform version to check f...
Add-on Repository
t provides an interface for interacting with the addons.mozilla.org (amo) site. its api provides urls that can be visited to browse the repository's add-ons. the api also offers two ways to search for and retrieve an array of addon instances: retrieverecommendedaddons(), which returns a list of recommended add-ons, and searchaddons(), which performs a search of the repository. these searches are asynchronous; results are passed to the provided searchcallback object when the search is completed. results passed to the searchcallback object only include add-ons that are compatible with the current application and are not already installed or in the process of being installed. addonrepository can only process one search at a time. a new search will immediately fail if the addonrepository is alread...
OS.File.Info
lable depends on the platform. instances of os.file.info may be obtained by: calling global method os.file.stat() either from the main thread or from a worker thread; calling instance method stat() of os.file either from the main thread or from a worker thread. ...
OSFile.jsm
more i/o than they think) and, since not all platforms have the same features, offer system-specific information that the developer can use to optimize his algorithms for a platform. using os.file ... from the main thread most uses of os.file are from the main thread. in this mode, main thread clients use the api to request off main thread file i/o. calling os.file from the main thread asynchronous, off-main thread file i/o, main thread api. calling os.file.directoryiterator from the main thread asynchronous, off-main thread file directory access, main thread api. ... from a worker thread in some cases, the main thread api for os.file is not appropriate as it would require too much message passing, or because the code that requires file i/o is already executed on a worker thread...
Examples
makeinfallible/<@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/devtoolsutils.js:84:7 */ intermediate of user defined promise function 1 components.utils.import("resource://gre/modules/promise.jsm"); // this function creates and returns a new promise. function promisevalueaftertimeout(avalue, atimeout) { let deferred = promise.defer(); try { // an asynchronous operation will trigger the resolution of the promise. // in this example, we don't have a callback that triggers a rejection. settimeout(function () { deferred.resolve('rawr my success value'); }, atimeout); } catch (ex) { // generally, functions returning promises propagate exceptions through // the returned promise, though they may also choose to fail early. ...
Promise
once you have a reference to a promise, you can call its then() method to execute an action when the value becomes available, or when an error occurs. promises may also be created using the new promise() constructor. you don't need to import the promise.jsm module to use a promise object to which you already have a reference. ...
Promise.jsm
ue, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api. in this case, the state of the promise can be observed but not directly controlled. to observe the state of a promise, its then method must be used. this method registers callback functions that are called as soon as the promise is either fulfilled or rejected. the method returns a new promise that, in turn, is fulfilled or rejected depending on the state of the original promise and ...
BloatView
g leaked broken down by class. here's a sample of the bloatview output. ...
Investigating leaks using DMD heap scan mode
cious. the first thing i did to try to confirm that this was the source of the leak was pass the address of this object into the cycle collector analysis log, find_roots.py, that we used at an earlier step. that gave a result that contained this: 0x7f0882fe3230 [fragmentorelement (xhtml) script [...] --[mnodeinfo]--> 0x7f0897431f00 [nodeinfo (xhtml) script] [...] --[mloadingasyncrequests]--> 0x7f0892f29630 [scriptloadrequest] this confirms that this block is actually a scriptloadrequest. secondly, notice that the load request is being held alive by the very same script element that is causing the window leak! this strongly suggests that there is a cycle of strong references between the script element and the load request. i then added the missing field to the traverse an...
GPU performance
tools pix - can do timing of direct3d calls. works reasonably well with firefox. see also debugging with pix. nvidia perfhud - last i checked required a special build to be used. nvidia parallel nsight - haven't tried. amd gpu shaderanalyzer - will compile a shader and show the machine code and give static pipeline estimations. not that useful for firefox because all of our shaders are pretty simple. amd gpu perfstudio - i had trouble getting this to work, and can't remember whether i actually did or not. intel graphics performance analyzers - haven't tried. ...
MailNews automated testing
ent / module level. xpcshell-tests are the quickest tests to run. mailnews provides additional facilities as described on the mailnews automated testing page (see below). "make check" is used to run compiled code tests. these tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators. in the long term we would like to lose this extra complexity in favor of the event-loop-spinning style of operation used by mozmill. message synthesis: create messages by specifying what properties the messages should have.
MailNews
mailnews stands for "mail and newsgroups". mailnews is the back end of the messaging parts of seamonkey and thunderbird. it provides a number of functions and capabilities, including: communications protocols - smtp, pop3, imap, nntp message management, including search and filtering message composition address book the mailnews code lives in the mailnews/ directory of comm-central. asynctestutils extended framework the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. leak and bloat tests this page describes how to perform tests that measure memory leaks and bloat for mailnews and its sub-components. mailnews automated testing automate...
NSS 3.44 release notes
package() crash with netscape certificate sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variable...
Hacking Tips
4-bits distribution and you want to build a 32-bits browser, it might be hard to find the relevant 32-bits dependencies. you can use padenot's scripts which will magically setup a chrooted 32-bits environment and do all the things (c) for you (you just need to modify the mozconfig file). using rr on a test get the command line for your test run using -s: ./jit_test.py -s $js_shell saved-stacks/async.js insert 'rr' before the shell invocation: rr $js_shell -f $js_src/jit-test/lib/prolog.js --js-cache $js_src/jit-test/.js-cache -e "const platform='linux2'; const libdir='$js_src/jit-test/lib/'; const scriptdir='$js_src/jit-test/tests/saved-stacks/'" -f $js_src/jit-test/tests/saved-stacks/async.js (note that the above is an example; simply setting js_shell and js_src will not work). or if thi...
JS::CompileOptions
if the source code can be parsed lazily (check only syntax for first time, and fully parse when it's really needed). strictoption bool true if the code is strict mode ("use strict"). extrawarningsoption bool show extra warning. werroroption bool treat warning as error. asmjsoption bool true if asm.js is allowed in the code. forceasync bool false means js::cancompileoffthread may returns false depends on the length of the code. installedfile bool true iff pre-compiling js file in packaged app. sourceislazy bool true indicates that, after compilation, script source should not be cached by the js engine and should be lazily loaded from the embedding as-needed. introductiontype const...
JS_SetInterruptCallback
e internally triggers interrupt callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setinterruptcallback sets a callback that can be called asynchronously. some common uses for an interrupt callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning false.) js_...
JS_SetOperationCallback
e internally triggers operation callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setoperationcallback sets a callback that can be called asynchronously. some common uses for an operation callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning js_false.) ...
SpiderMonkey 45
1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::exceptionstackornull (bug 814497) js::copyasyncstack (bug 1160307) js::getsavedframesource (bug 1216819) js::getsavedframeline (bug 1216819) js::getsavedframecolumn (bug 1216819) js::getsavedframefunctiondisplayname (bug 1216819) js::getsavedframeasynccause (bug 1216819) js::getsavedframeasyncparent (bug 1216819) js::getsavedframeparent (bug 1216819) js::buildstackstring (bug 1133191) js::flushperformancemonitoring (bug 1181175) js::...
Shell global objects
capture a stack back to the first frame whose principals are subsumed by the object's compartment's principals. if shouldignoreselfhosted is given, control whether self-hosted frames are considered when checking principals. callfunctionfromnativeframe(function) call function with a (c++-)native frame on stack. required for testing that savestack properly handles native frames. callfunctionwithasyncstack(function, stack, asynccause) call function, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws. the function is called with no arguments, and this is undefined. the specified asynccause is attached to the provided stack frame. enabletrackallocations() start capturing the js stack at every allocation. note that th...
TPS Tests
test fails. logger.assertequal(val1, val2, msg) asserts that val1 is equal to val2, otherwise an exception is thrown and the test fails. custom functions you can also write your own functions to be called as actions. for example, consider the first action in the phase above: [bookmarks.add, bookmarks_initial] you could rewrite this as a custom function so as to add some custom logging: [async () => { logger.loginfo("adding bookmarks_initial"); await bookmarks.add(bookmarks_initial); }] note that this is probably best used for debugging, and new tests that want custom behavior should add it to the tps addon so that other tests can use it. example test here's an example tps test to tie it all together. // phase declarations var phases = { "phase1": "profile1", "p...
Redis Tips
is-py there are some gotchas with the python api: https://github.com/andymccurdy/redis-py#api-reference select statement not implemented del is 'delete' in python zadd argument order is wrong setex argument order is wrong the default redis port is 6379. in node, create client with explicit host and port like so: > var r = require('redis').createclient(6379, '127.0.0.1') commands are asynchronous. in standard node fashion, first return value is error or null; second return value is result of redis command. > r.set('foo', 42, console.log) null 'ok' > r.get('foo', console.log) null '42' for the rest of this, i'm going to use the synchronous redis-cli for demonstrations. lines beginning with redis> are input to the redis-cli. things are strings, mostly as you can see from tha...
Feed content access API
oreceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring() method. however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a method called handleresult() on the feedtestresultlistener object. that code looks like this: feedtestresultlistener.prototype = { handleresult: function(result) { var feed = result.doc; feed.queryinterface(components.interfaces.nsifeed); // open a new window var win = window.open("", "feedtest_w...
Places Developer Guide
while (sql_stmt.executestep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } note: the <cdata><![cdata[ xxx ]]></cdata>.tostring() notation is e4x and it makes possible to write multi-line strings in javascript. this is very useful when writing long sql statements.
Places Expiration
expiration is handled in toolkit/components/places/nsplacesexpiration.js. algorithm expiration is based on hardware specs, specifically on memory size and available disk space. this means on mobile and old systems expiration will be more aggressive than on high-end hardware, to try keep the database size at a reasonable (and performant) value. all of expiration uses the storage async api, that ensures i/o is in a separate thread, plus it won't block any read thanks to the use of the wal journaling system. common expiration runs on a timer, every 3 minutes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries, otherwise if the previous step completed the cleanup the next step will be delayed. this ensures expi...
xpcshell
language features, such as the let statement introduced in javascript 1.7, are not available. to rectify this, run xpcshell with the -v 180 command-line option, which tells xpcshell to use javascript 1.8. example you can input javascript, straight to mozilla. js> 5+7 12 js> print("hello, world!") hello, world! js> see also howto for common problems in writing xpcshell scripts, e.g., doing async network calls or using js modules. pretty much all mozilla programs use xpcom components via xpconnect. read xpconnect:using components to get started with that. see the xpcshell reference for information on command line arguments and extension functions. learn how to write xpcshell-based unit tests. read xpcshell:profiling for information on how to profile scripts. ...
Observer Notifications
hannel as the subject parameter. topic description http-on-modify-request called as a http request is made. the channel is available to allow you to modify headers and such. see this code snippet to learn how to get the tab that issued the request. http-on-opening-request similar to http-on-modify-request, but called earlier (synchronously during the channel's asyncopen() call), and some channel attributes (proxyinfo) may be missing. use only if your observer must be called before asyncopen returns. http-on-examine-response called after a response has been received from the web server. headers are available on the channel. the response can be accessed and modified via nsitraceablechannel. http-on-examine-cached-response called instea...
imgIEncoder
modules/libpr0n/public/imgiencoder.idlscriptable please add a summary to this article. ...
imgIRequest
gin usage with cors, and, if successful, will have its cors mode set to the relevant type. cors_anonymous 2 cors_use_credentials 3 methods cancelandforgetobserver() cancels this request as in nsirequest.cancel(); further, also nulls out decoderobserver so it gets no further notifications from us. note: you should not use this in any new code; instead, use cancel(). note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest(). this means that, if you're the observer, you can not call cancel() from your destructor. void cancelandforgetobserver( in nsresult astatus ); parameters astatus clone() clone this request; the returned request will have aobserver as the observer. aobserver will be notified synchronously ...
mozIStorageBindingParams
storage/public/mozistoragebindingparams.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create mozistoragebindingparams objects by calling the mozistoragebindingparamsarray.newbindingparams(). ...
mozIStorageCompletionCallback
this interface should be implemented to handle callbacks from asynchronous storage api routines. storage/public/mozistoragecompletioncallback.idlscriptable please add a summary to this article. last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports method overview void complete(); methods complete() called when an asynchronous storage routine has completed. void complete(); parameters none. ...
mozIStorageFunction
gevaluearray afunctionarguments); methods onfunctioncall() the implementation of the function. this is called by the database engine when the function registered with mozistorageconnection.createfunction() is used in an executing sql statement or trigger. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfunctioncall( in mozistoragevaluearray afunctionarguments ); paramet...
mozIStoragePendingStatement
storage/public/mozistoragependingstatement.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports method overview void cancel(); methods cancel() cancels the pending statement. fails only if you attempt to cancel the operation more than once. note: for read statements, such as select, once you cancel the statement, you will receive no further notifications about results. void cancel(); parameters none. ...
nsIApplicationCacheChannel
ecacheentryasforeign(); attributes attribute type description chooseapplicationcache boolean when true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification callbacks. the default value is false. this attribute will not be transferred through a redirect. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. inheritapplicationcache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. the default value is true. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. loadedfromapplicationcache prbool true if the resource was loaded from the application cache, otherwi...
nsIAuthInformation
netwerk/base/public/nsiauthinformation.idlscriptable a object that holds authentication information. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the caller of nsiauthprompt2.promptusernameandpassword() or nsiauthprompt2.promptpasswordasync() provides an object implementing this interface; the prompt implementation can then read the values here to prefill the dialog. after the user entered the authentication information, it should set the attributes of this object to indicate to the caller what was entered by the user. attributes attribute type description authenticationscheme autf8string the authentication scheme used for this request, if applicable. if the protocol fo...
nsIAutoCompleteSearch
toolkit/components/autocomplete/nsiautocompletesearch.idlscriptable this interface is implemented by search providers to start and stop autocomplete. inherits from: nsisupports last changed in gecko 1.7 users call startsearch() and pass in an nsiautocompleteobserver when the search starts. results can be sent to the listener either synchronously or asynchronously, depending on the implementation. method overview void startsearch(in astring searchstring, in astring searchparam, in nsiautocompleteresult previousresult, in nsiautocompleteobserver listener); void stopsearch(); methods startsearch() search for a given string and notify a listener (either synchronously or asynchronously) of the result. void startsearch( in astring searchstring, in astring searchparam, in...
nsICacheService
gecko 1.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is no longer supported and planned to be removed soon: use nsicachestorageservice instead. at the time of writing there is no documentation for nsicachestorageservice but comments are available in the source. note: starting in gecko 2.0, cache i/o is handled asynchronously. method overview nsicachesession createsession(in string clientid, in nscachestoragepolicy storagepolicy, in boolean streambased); acstring createtemporaryclientid(in nscachestoragepolicy storagepolicy); obsolete since gecko 1.9.2 void evictentries(in nscachestoragepolicy storagepolicy); void init(); obsolete since gecko 1.8 void shutdow...
nsICachingChannel
1 << 30 this load flag inhibits fetching from the net if the data in the cache has been evicted. an error of ns_error_document_not_cached will be sent to the listener's onstoprequest in this case. this flag is set automatically when the application is offline. load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a call to asyncopen. if this attribute is set to true, then the document will not be loaded from the cache. a stream listener can check isfromcache() to determine if the asyncopen will actually result in data being streamed. if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only see onstartrequest followed by onstopreques...
nsIContentFrameMessageManager
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisyncmessagesender this interface provides the environment for scripts that are loaded into content frames using the nsiframescriptloader interface. it enables these scripts to receive messages from the chrome process and send messages back to the chrome process. frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging apis see the documentation for the nsicontentframemessagemanager's parent classes nsisyncmessagesender and nsimessagesender. methods void dump(in domstring astr); domstring atob(in domstring aasciistring); domstring btoa(in domstring abase64data); dump() prints the specified string to standa...
nsIContentPrefService
provides a way for extensions and browser code to save preferences for specific websites. preferences are saved as key/value pairs on a per-website basis. dom/interfaces/base/nsicontentprefservice.idlscriptable please add a summary to this article. last changed in gecko 2 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports implemented by: @mozilla.org/content-pref/service;1. ...
nsIDNSListener
netwerk/dns/nsidnslistener.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void onlookupcomplete(in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus); methods onlookupcomplete() called when an asynchronous host lookup completes. void onlookupcomplete( in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus ); parameters arequest the value returned from asyncresolve. arecord the dns record corresponding to the hostname that was resolved. this parameter is null if there was an error. astatus if the lookup failed, this parameter gives the reason. ...
nsIDNSRequest
netwerk/dns/nsidnsrequest.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void cancel(); methods cancel() called to cancel a pending asynchronous dns request. the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort. void cancel(); parameters none. ...
nsIDOMMozNetworkStatsManager
ed in the database. read only. maxstorageage long long time in milliseconds recorded by the api until present time. all samples older than maxstorageage from now are deleted. read only. constants constant type description wifi long constant for wifi, set to 0 mobile long constant for mobile, set to 1 methods getsamples() asynchronously queries network interface statistics. the query may be filtered by connection type and date. nsidomdomrequest getsamples(in nsisupports network, in jsval start, in jsval end, [optional] in jsval options /* networkstatsgetoptions */); parameters network the origin of the data. it can specify wifi, m...
nsIDownloadManager
browserpersist object, call this method, set the progresslistener to the returned nsidownload object, and then call the nsiwebbrowserpersist.saveuri() method. note: prior to gecko 12.0, this was a synchronous operation; that is, once this method returned, you knew that the download was in the download manager's list. that is no longer the case. adding downloads to the download manager is now an asynchronous operation. nsidownload adddownload( in short adownloadtype, in nsiuri asource, in nsiuri atarget, in astring adisplayname, in nsimimeinfo amimeinfo, in prtime astarttime, in nsilocalfile atempfile, in nsicancelable acancelable, in boolean aisprivate ); parameters adownloadtype the download type for the transfer. should always be set to nsidownloadmanager.download_...
nsIEventTarget
run on the current thread (that is, the thread calling this method). if events dispatched to this target will be processed on another thread, returns false. native code only!postevent obsolete since gecko 1.9 (firefox 3)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. method for posting an asynchronous event to the event target. if this method succeeds, then the event will be dispatched on the target thread. void postevent( in pleventptr aevent ); parameters aevent the event to dispatched. ...
nsIFilePicker
called. void init( in nsidomwindow parent, in astring title, in short mode ); parameters parent the nsidomwindow parent. this dialog will be dependent on this parent. must be non-null. title the file picker dialog title. if this is null, the dialog will have the default title. mode one of the mode constants, indicating the type of picker to create. open() opens the file dialog asynchrounously. the passed in object's done method will be called upon completion. void open( in nsifilepickershowncallback afilepickershowncallback ); parameters afilepickershowncallback the nsifilepickershowncallback to be called on completion. show() obsolete since gecko 57.0 (firefox 57.0 / thunderbird 57.0 / seamonkey 2.54) displays the file picker dialog. th...
nsIHttpServer
* behavior is undefined if this method is called after stop() has been * called on this but before the provided callback function has been * called. */ void start(in long port); /** * shuts down this server if it is running (including the period of time after * stop() has been called but before the provided callback has been called). ...
nsIMessageBroadcaster
t have a single "other side" that they send messages to, but rather a set of subordinate message managers. for example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window. see message manager interfaces for more details on the distinction between message senders and message broadcasters. methods void broadcastasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects); nsimessagelistenermanager getchildat(in unsigned long aindex); broadcastasyncmessage() like sendasyncmessage(), but also broadcasts this message to all "child" message managers of this message manager. see nsimessagelistener::receiveme...
nsIMessageListener
is used to receive messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces. listeners are attached using the nsimessagelistenermanager interface. methods void receivemessage(); receivemessage() this is for js only. this function receives a message from one of the three message-sending functions in the message manager framework: broadcastasyncmessage sendasyncmessage sendsyncmessage. the received message is an object with the following properties: target the target of the message. either an element owning the message manager, or the message manager itself if no element owns it. if the message was sent from a frame script using a nsicontentframemessagemanager, then this property is the xul <browser> element for t...
nsIMsgFolder
. displayrecipients boolean readonly: should we be displaying recipients instead of the sender. for example, in the sent folder, recipients are more relevant than the sender. manyheaderstodownload boolean readonly: used to determine if it will take a long time to download all the headers in this folder - so that we can do folder notifications synchronously instead of asynchronously. requirescleanup boolean readonly hasnewmessages boolean does this folder have new messages. firstnewmessage nsimsgdbhdr readonly: the first new message in the folder. prettiestname astring readonly folderurl acstring readonly: url for this folder. showdeletedmessages boolean readonly serv...
nsIMsgMessageService
ent type of the attachment afilename the name of the attachment. aurl a string representation of the original url associated with the msg. amessageuri rdf resource that describes the message adisplayconsumer msgwindow nsimsgwindow for progress and status feedback aurllistener an nsiurllistener. savemessagetodisk() when you want to spool a message out to a file on disk. this is an async operation of course.note: you must pass in a url listener in order to figure out when the operation is done. void savemessagetodisk(in string amessageuri, in nsifilespec afile, in boolean ageneratedummyenvelope, in nsiurllistener aurllistener, out nsiuri aurl, in boolean canon...
nsIMsgProtocolInfo
nt type. read only. canloginatstartup boolean true if the account type can perform biff during startup. read only. defaultdobiff boolean true if the biff should be enabled by default for the account type. read only. defaultlocalfilepath nsilocalfile the default path under which all server data for this account type will be stored. folderscreateasync boolean new in thunderbird 24 (bug 832034) preflightprettynamewithemailaddress boolean unused. read only. requiresusername boolean true if the server requires a username to log on. read only. serveriid nsiidptr the iid of the server-specific interface, used during account creation. read only. showcomposemsglink boolean true if comp...
nsINavHistoryContainerResultNode
ote container api, or a bookmark folder (result_type_folder) for which some service (such as livemarks) has registered to provide certain operations. state unsigned short the current state of the container. this is one of the state constants. constants state constants constant value description state_closed 0 the container is closed. state_loading 1 the container has been opened asynchronously, but is still loading and is not all the way opened yet. state_opened 2 the container is open. methods findnodebydetails() returns a node matching specified details. nsinavhistoryresultnode findnodebydetails( in autf8string auristring, in prtime atime, in long long aitemid, in boolean recursive ); parameters auristring the uri attribute value to match on. atime the time ...
nsINavHistoryQueryOptions
1.9 inherits from: nsisupports last changed in gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) method overview nsinavhistoryqueryoptions clone(); attributes attribute type description applyoptionstocontainers boolean if true, the query options are only applied to the containers. asyncenabled boolean when true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so. by default, this is false. note: currently, only bookmark folder containers support being opened asynchronously. excludeitemifparenthasannotation obsolete since gecko 13.
nsINavHistoryService
. boolean canadduri( in nsiuri auri ); parameters auri the uri that needs to be added to the history system. return value returns true if this uri would be added to the history, otherwise returns false. addvisit() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasynchistory.updateplaces() instead. see this code for how a function to add visits and handle errors using the new api could look like. this method adds a visit for a specific page. this will probably not be commonly used other than for backup/restore type operations. if the uri does not have an entry in the history database already, one will be created with no visits, no title, hidden...
nsIOutputStream
s_base_stream_would_block indicates that flushing the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. isnonblocking() note: writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. note: a non-blocking output stream may implement nsiasyncoutputstream to provide consumers with a way to wait for the stream to accept more data once its write() method is unable to accept any data without blocking. boolean isnonblocking(); parameters none. return value true if stream is non-blocking. exceptions thrown ns_base_stream_would_block a non-blocking stream may throw this exception when written to if space for the data is not immedi...
nsIOutputStreamCallback
xpcom/io/nsiasyncoutputstream.idlscriptable this is a companion interface for nsiasyncoutputstream.asyncwait. inherits from: nsisupports last changed in gecko 1.7 method overview void onoutputstreamready(in nsiasyncoutputstream astream); methods onoutputstreamready() called to indicate that the stream is either writable or closed. void onoutputstreamready( in nsiasyncoutputstream astream ); parameters astream the stream whose nsiasyncoutputstream.asyncwait() method was called. ...
nsIProtocolHandler
with a principal that subsumes this uri. for example, privileged code and websites that are same origin as this uri. uri_non_persistable 1<<10 loading channels from this protocol has side-effects that make it unsuitable for saving to a local file. uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data. uri_is_local_resource 1<<12 uris for this protocol are considered to be local resources. this could be a local file (uri_is_local_file), a ui resource (uri_is_ui_resource), or something else that would not hit the network. uri_opening_executes_script 1<<13 uris for this protocol execute script when they are op...
nsIRequestObserver
as nsichannel ) to indicate the start and end of a request. inherits from: nsisupports last changed in gecko 1.0 method overview void onstartrequest(in nsirequest arequest, in nsisupports acontext); void onstoprequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode); methods onstartrequest() called to signify the beginning of an asynchronous request. note: an exception thrown from onstartrequest has the side-effect of causing the request to be canceled. void onstartrequest( in nsirequest arequest, in nsisupports acontext ); parameters arequest request being observed. acontext user defined context. onstoprequest() called to signify the end of an asynchronous request. this call is always preced...
nsISocketTransportService
xies in necko. return value an nsisockettransport containing the sockettransport. init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void init(); parameters none. native code only! notifywhencanattachsocket if the number of sockets reaches the limit, then consumers can be notified when the number of sockets becomes less than the limit. the notification is asynchronous, delivered via the given nsirunnable instance on the socket transport thread. note: this function may only be called from an event dispatch on the socket thread. void notifywhencanattachsocket( in nsirunnable aevent ); parameters aevent event that will receive the notification when a new socket can be attached. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5...
nsISyncMessageSender
returns an array containing return values from each listener invoked. send messagename and obj to the "other side" of this message manager. this invokes listeners who registered for messagename using a nsimessagelistenermanager. see nsimessagelistener::receivemessage() for the format of the data delivered...
nsITelemetry
val getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscal...
nsIThread
tched to the thread. this method is re-entrant but may only be called if this thread is the current thread. warning: calling nsithread.processnextevent allows network and ui events to run which can modify data structures that your code isn't expecting to be modified during a synchronous method call. this can cause random crashes and other bugs that may be hard to find and fix. consider use asynchronous callbacks instead. boolean processnextevent( in boolean maywait ); parameters maywait if true, this method blocks until an event is available to process if the event queue is empty. if false, this method returns immediately if the queue is empty. return value returns true if an event was processed, or false if there were no pending events. exceptions thrown ns_error_unexpe...
nsIUploadChannel
inherits from: nsisupports last changed in gecko 1.7 method overview void setuploadstream(in nsiinputstream astream, in acstring acontenttype, in long acontentlength); attributes attribute type description uploadstream nsiinputstream get the stream (to be) uploaded by this channel. read only. ...
nsIWebProgress
nsiwebprogress instances may be arranged in a parent-child configuration, corresponding to the parent-child configuration of their respective dom windows. however, in some cases a nsiwebprogress instance may not have an associated dom window. the parent-child relationship of nsiwebprogress instances is not made explicit by this interface, but the relationship may exist in some implementations. ...
nsIWebSocketListener
netwerk/protocol/websocket/nsiwebsocketlistener.idlscriptable implement this interface to receive websocket traffic events asynchronously after calling nsiwebsocketchannel.asyncopen(). 1.0 66 introduced gecko 8.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void onacknowledge(in nsisupports acontext, in pruint32 asize); void onbinarymessageavailable(in nsisupports acontext, in acstring amsg); void onmessageavailable(in nsisupports acontext, in autf8string amsg); void onserverclose(in nsisupports acontext, in unsigned short acode, in autf8string areason); void onstart(in nsisupports acontext); void onstop(in nsisupports acontext, in nsresult...
nsIXULTemplateQueryProcessor
l source, the datasource might be an nsidomnode. all of these uris are checked by the builder so it is safe to use them, however note that a uri that redirects may still needs to be checked to ensure that the document containing arootnode may access it. this is the responsibility of the query processor if it needs to load the content of the uri. if the query processor needs to load the datasource asynchronously, it may set the ashoulddelaybuilding returned parameter to true to delay building the template content, and call the builder's rebuild method when the data is available. nsisupports getdatasource( in nsiarray adatasources, in nsidomnode arootnode, in boolean aistrusted, in nsixultemplatebuilder abuilder, out boolean ashoulddelaybuilding ); parameters adatasources the list of ...
nsIZipWriter
hen adding the file to the archive. compression_default 6 use the default compression method when adding the file to the archive. compression_best 9 use the best compression method when adding the file to the archive. methods addentrychannel() adds data from a channel to the zip file. if the operation is performed on the queue then the channel will be opened asynchronously, otherwise the channel must support being opened synchronously. void addentrychannel( in autf8string azipentry, in prtime amodtime, in print32 acompression, in nsichannel achannel, in boolean aqueue ); parameters azipentry the path of the file entry to add to the zip file. this is the path it will be located at within the zip file. note: you must use forward slashes ('/...
nsIMsgCloudFileProvider
known, returns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. lasterror acstring readonly: the last error message received from the server. constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. uploaderr 0x8055311a returned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055...
Gloda examples
ction = id_q.getcollection(mylistener); show all messages where the from, to and cc values include a specified email address at present there doesn't appear to be any way of going directly from an email address to email addresses that it involves. instead you need to do two queries, first to get the "identity" object for an email address and then to get the messages. ...
Index
xpcshell-tests; see the core xpcshell-tests page for more information on how to develop these. 42 mailbox mailnews the mailbox protocol is used to read messages from a local folder berkeley mailbox. it consists of nsmailboxservice, nsmailboxurl, and nsmailboxprotocol. this may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onstart/stoprunningurl notifications when the url starts/stops, etc. 43 mailnews and mail code review requirements this document describes the process for reviewing patches to the mozilla/mailnews and mozilla/mail directories. thun...
Mailbox
the mailbox protocol is used to read messages from a local folder berkeley mailbox. it consists of nsmailboxservice, nsmailboxurl, and nsmailboxprotocol. this may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onstart/stoprunningurl notifications when the url starts/stops, etc. the mailbox protocol is also used to regenerate a summary file, in conjunction with nsmsgmailboxparser ...
Add to iPhoto
we'll get a ...
ctypes.open
ed, this will be addon xpi } this can then be joined with your file name to obtain it's path like this: function startup(adata, areason) { var jarpath_folder = 'jar:' + os.path.tofileuri(adata.installpath.path) + '!/'; // if unpacked is false in install.rdf this will look like: "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aksozfjt.unnamed%20profile%2010/extensions/asynczip@jetpack!/" var filepath_folder = adata.installpath.path; // if unpacked is set to false in install.rdf this will look like: "c:\users\vayeate\appdata\roaming\mozilla\firefox\profiles\aksozfjt.unnamed profile 10\extensions\asynczip@jetpack" var filepath_mylib = os.path.join(filepath_folder, 'mysubfolder', 'mycfunctionsforunix.so'); var jarpath_mylib = jarpath_folder + 'mysubfolder/...
Browser Side Plug-in API - Plugins
ied drawing region prior to repainting or refreshing a windowless plug-in. npn_memalloc allocates memory from the browser's memory space. npn_memflush requests that the browser free a specified amount of memory. npn_memfree deallocates a block of allocated memory. npn_newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser. npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated). npn_poppopupsenabledstate pops the popups-enabled state. npn_posturl posts data to a url. npn_posturlnotify posts data to a url, and receives notification of the result. npn_pushpopupsenabledstate pushes the popups-enabled state. n...
Drawing and Event Handling - Plugins
cified drawing area prior to repainting or refreshing. they pass an update event or a paint message to the plug-in. the browser redraws invalid areas of the document and windowless plug-ins at regularly timed intervals. to force a paint message, the plug-in can call npn_forceredraw after calling one of the invalidate methods. if a plug-in calls one of these methods, it receives a paint message asynchronously. void npn_invalidaterect(npp instance, nprect *invalidrect); void npn_invalidateregion(npp instance, npregion invalidregion); the instance parameter represents the current plug-in. the invalidrect and invalidregion parameters represent the area to invalidate, specified in a coordinate system whose origin is at the top left of the plug-in. both methods cause the npp_handleevent method...
Streams - Plugins
k of data is available in a network buffer). for instance, suppose the plug-in allocates, in npp_newstream, an 8k buffer to hold the data written from that stream. in the first call, npp_writeready could return 8192, resulting in a call to npp_write with a buffer of up to 8k bytes. after this data is copied from the browser's buffer to the plug-in's buffer, the plug-in begins to process the data asynchronously. at the next npp_writeready call, only half of the data has been processed. to avoid allocating additional buffers, the plug-in could return 4096, resulting in a call to npp_write with a buffer of up to 4k bytes. the buffer passed to npp_write may accommodate more bytes than the maximum number returned from npp_writeready . this maximum is only a promise to consume a certain amount of d...
Gecko Plugin API Reference - Plugins
ied drawing region prior to repainting or refreshing a windowless plug-in. npn_memalloc allocates memory from the browser's memory space. npn_memflush requests that the browser free a specified amount of memory. npn_memfree deallocates a block of allocated memory. npn_newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser. npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated). npn_poppopupsenabledstate pops the popups-enabled state. npn_posturl posts data to a url. npn_posturlnotify posts data to a url, and receives notification of the result. npn_pushpopupsenabledstate pushes the popups-enabled state. npn_...
Debugger.Script - Firefox Developer Tools
ode”, respectively. if the behavior does not differ, no such emphasized headings will appear. accessor properties of the debugger.script prototype object a debugger.script instance inherits the following accessor properties from its prototype: isgeneratorfunction true if this instance refers to a jsscript for a function defined with a function* expression or statement. false otherwise. isasyncfunction true if this instance refers to a jsscript for an async function, defined with an async function expression or statement. false otherwise. displayname if the instance refers to a jsscript, this is the script’s display name, if it has one. if the script has no display name — for example, if it is a top-level eval script — this is undefined. if the script’s function has a giv...
Network request list - Firefox Developer Tools
t as it was originally sent with no changes made. edit and resend opens an editor enabling you to edit the request's method, url, parameters, and headers, and resend the request. block url blocks the selected url for future requests. see blocking a specific url from the request list. open in new tab resends the request in a new tab — very useful for debugging asynchronous requests. open in style editor for a css resource, opens it in the style editor. start performance analysis use as fetch in console submits the request as a call to the fetch() method in the console. copy as curl the command may include the following options: -x [method] if the method is not get or post --data for url en...
Intensive JavaScript - Firefox Developer Tools
about 60 frames per second. so it will take almost a second to run all the computations, and that's visible in both the user experience and in the profile. using web workers in this version we'll try to fix the problem using a web worker. web workers enable you to run javascript in a separate thread. the main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging api. the main thread code would look something like this: const iterations = 50; const multiplier = 1000000000; var worker = new worker("js/calculate.js"); function dopointlesscomputationsinworker() { function handleworkercompletion(message) { if (message.data.command == "done") { pointlesscomputationsbutton.disabled = false; console.log(message.data.primes...
Animation.pending - Web APIs
Web › API › Animation › pending
syntax var pending = animation.pending; value true if the animation is pending, false otherwise. ...
Animation.playState - Web APIs
the current time of the animation is unresolved and there are no pending tasks. running the animation is running. paused the animation was suspended and the animation.currenttime property is not updating. finished the animation has reached one of its boundaries and the animation.currenttime property is not updating. previously, web animations defined a pending value to indicate that some asynchronous operation such as initiating playback was yet to complete. this is now indicated by the separate animation.pending property. example in the growing/shrinking alice game example, players can get an ending with alice crying into a pool of tears. in the game, for performance reasons, the tears should only be animating when they're visible. so they must be paused as soon as they are animated...
Animation.updatePlaybackRate() - Web APIs
tion may run on a separate thread or process and will continue updating even while long-running javascript delays the main thread. in such a case, setting the playbackrate on the animation directly may cause the animation's playback position to jump since its playback position on the main thread may have drifted from the playback position where it is currently running. updateplaybackrate() is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. after calling updateplaybackrate() the animation's playbackrate is not immediately updated. it will be updated once the animation's ready promise is resolved. syntax animation.updateplaybackrate(2); parameters ...
Animation - Web APIs
Web › API › Animation
l. animation.effect gets and sets the animationeffectreadonly associated with this animation. this will usually be a keyframeeffect object. animation.finished read only returns the current finished promise for this animation. animation.id gets and sets the string used to identify the animation. animation.pending read only indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. animation.playstate read only returns an enumerated value describing the playback state of an animation. animation.playbackrate gets or sets the playback rate of the animation. animation.ready read only returns the current ready promise for this animation. animation.replacestate returns the replace state ...
BaseAudioContext.createBuffer() - Web APIs
be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page. note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code execution. the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode. for simple uses like playing an mp3, decodeaudiodata() is what you should be using. syntax var buffer = baseaudiocontext.createbuffer(numofchannels, length, samplerate); parameters note: fo...
BaseAudioContext.decodeAudioData() - Web APIs
in this case the arraybuffer is loaded from xmlhttprequest and filereader. the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. ...
BaseAudioContext - Web APIs
iptprocessor() creates a scriptprocessornode, which can be used for direct audio processing via javascript. baseaudiocontext.createstereopanner() creates a stereopannernode, which can be used to apply stereo panning to an audio source. baseaudiocontext.createwaveshaper() creates a waveshapernode, which is used to implement non-linear distortion effects. baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer. in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocon...
Using the Beacon API - Web APIs
beacon requests use http post and do not require a response. beacon requests are guaranteed to be initiated before the page unloads. this document contains examples of the beacon interfaces. see beacon api for an overview. navigator.sendbeacon() the beacon api's navigator.sendbeacon() method sends a beacon request to the server in the global browsing context. the method takes two arguments: the url and the data to send. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns true and returns false otherwise. ...
CanvasRenderingContext2D.drawWindow() - Web APIs
drawwindow_draw_view 0x04 draw scrollbars and scroll the viewport if they are present. drawwindow_use_widget_layers 0x08 use the widget layer manager if available. this means hardware acceleration may be used, but it might actually be slower or lower quality than normal. it will, however, more accurately reflect the pixels rendered to the screen. drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have. example this method draws a snapshot of the contents of a dom window into the canvas. for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ... would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a w...
Client.postMessage() - Web APIs
to the client. this can be any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. return value undefined. examples sending a message from a service worker to a client: addeventlistener('fetch', event => { event.waituntil(async function() { // exit early if we don't have access to the client. // eg, if it's cross-origin. if (!event.clientid) return; // get the client. const client = await clients.get(event.clientid); // exit early if we don't get the client. // eg, if it closed. if (!client) return; // send a message to the client. client.postmessage({ msg: "hey i just got...
Clients - Web APIs
Web › API › Clients
opens a new browser window for a given url and returns a promise for the new windowclient. clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. examples the following example shows an existing chat window or creates a new one when the user clicks a notification. ...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
the read() method of the clipboard interface requests a copy of the clipboard's contents, delivering the data to the returned promise when the promise is resolved. unlike readtext(), the read() method can return arbitrary data, such as images. this method can also return text. to read from the clipboard, you must first have the "clipboard-read" permission. note: the asynchronous clipboard and permissions apis are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like. be sure to review the compatibility table before using these methods. syntax var promise = navigator.clipboard.read(); parameters none. return value a promise that resolves with a datatransfer object containing the clipboard's contents. the...
Clipboard.write() - Web APIs
Web › API › Clipboard › write
be sure to check the compatibility table as well as clipboard availability in clipboard for more information. ...
Clipboard.writeText() - Web APIs
the clipboard interface's writetext() property writes the specified text string to the system clipboard. text may be read back using either read() or readtext(). the "clipboard-write" permission of the permissions api, is granted automatically to pages when they are in the active tab. note: browser support for the asynchronous clipboard apis is still in the process of being implemented. be sure to check the compatibility table as well as clipboard availability in clipboard for more information. syntax var promise = navigator.clipboard.writetext(newcliptext) parameters newcliptext the domstring to be written to the clipboard. return value a promise which is resolved once the clipboard's contents have been updated. the promise is rejected if the caller does not have permission ...
ClipboardItem() - Web APIs
blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. ...
ClipboardItem.getType() - Web APIs
object. exceptions domexception the type does not match a known mime type. typeerror no parameter is specified or the type is not that of the clipboarditem. examples in the following example, we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object. ...
ClipboardItem.types - Web APIs
var types = clipboarditem.types; value an array of available mime types. examples in the below example, we're returning all items on the clipboard via the clipboard.read() method. then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object. if no clipboards contents is found for the specified type, an error is returned. ...
ConvolverNode - Web APIs
n when the buffer attribute is set, or not. methods no specific method; inherits methods from its parent, audionode. convolvernode example the following example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. see this codepen for an applied example. let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ... let reverb = await createreverb(); // someotheraudionode -> reve...
Document: DOMContentLoaded event - Web APIs
interface event event handler property none a different event, load, should be used only to detect a fully-loaded page. it is a common mistake to use load where domcontentloaded would be more appropriate. synchronous javascript pauses parsing of the dom. if you want the dom to get parsed as fast as possible after the user has requested the page, you can make your javascript asynchronous and optimize loading of stylesheets. if loaded as usual, stylesheets slow down dom parsing as they're loaded in parallel, "stealing" traffic from the main html document. examples basic usage document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); delaying domcontentloaded <script> document.addeventlistener('domcontentloaded', (...
Document.currentScript - Web APIs
cript module. (for modules use import.meta instead.) it's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed. syntax var curscriptelement = document.currentscript; example this example checks to see if the script is being executed asynchronously: if (document.currentscript.async) { console.log("executing asynchronously"); } else { console.log("executing synchronously"); } view live examples specifications specification status comment html living standardthe definition of 'document.currentscript' in that specification. living standard initial definition ...
Document.exitPointerLock() - Web APIs
to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events. syntax document.exitpointerlock(); specifications specification status comment pointer lockthe definition of 'document' in that specification. ...
Document.write() - Web APIs
Web › API › Document › write
rite() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_error_dom_not_supported_err] error in the error console). this happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchronously-loaded external script was ignored" in the error console. note: in edge only, calling document.write() more than once in an <iframe> causes the error "script70: permission denied". note: starting with version 55, chrome will not execute <script> elements injected via document.write() ...
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
d then animate from the start value. this is the approach used in flip animation. elem.style.transform = 'translatey(100px)'; elem.animate({ transform: 'none', offset: 0 }, 200); for some complex effects where animations layer on top of one another, it may be necessary to use a fill mode temporarily to capture the final value of an animation before canceling it. elem.addeventlistener('click', async evt => { const animation = elem.animate( { transform: `translate(${evt.clientx}px, ${evt.clienty}px)` }, { duration: 800, fill: 'forwards' } ); await animation.finished; // commitstyles will record the style up to and including `animation` and // update elem’s specified style with the result. animation.commitstyles(); animation.cancel(); }); specifications spec...
Element: DOMMouseScroll event - Web APIs
it's represented by the mousescrollevent interface. this event was only implemented by firefox. you should instead use the standard wheel event. bubbles yes cancelable yes interface mousescrollevent if you want to prevent the default action of mouse wheel events, it's not enough to handle only this event on gecko because if scroll amount by a native mouse wheel event is less than 1 line (or less than 1 page when the system setting is by page scroll), other mouse wheel events may be fired without this event. ...
Element: MSManipulationStateChanged event - Web APIs
...
Element: MozMousePixelScroll event - Web APIs
it's represented by the mousescrollevent interface. important: do not use this non-standard and obsolete event. instead, you should always use the standard wheel event. bubbles yes cancelable yes interface mousescrollevent getting the distance scrolled the event's detail property indicates the scroll distance in terms of lines, with negative values indicating the scrolling movement is either toward the bottom or toward the right, and positive values indicating scrolling to the top or left. ...
Element: blur event - Web APIs
the blur event fires when an element has lost focus. the main difference between this event and focusout is that focusout bubbles while blur does not. the opposite of blur is focus. ...
Element: focus event - Web APIs
the focus event fires when an element has received focus. the main difference between this event and focusin is that focusin bubbles while focus does not. the opposite of focus is blur. ...
Element: focusin event - Web APIs
the focusin event fires when an element is about to receive focus. the main difference between this event and focus is that focusin bubbles while focus does not. the opposite of focusin is focusout. ...
Element: focusout event - Web APIs
the focusout event fires when an element is about to lose focus. the main difference between this event and blur is that focusout bubbles while blur does not. the opposite of focusout is focusin. ...
Element: mousewheel event - Web APIs
the mousewheel event was never part of any standard, and while it was implemented by several browsers, it was never implemented by firefox. important: instead of this obsolete event, use the standard wheel event. ...
Element.requestFullscreen() - Web APIs
it's not guaranteed that the element will be put into full screen mode. if permission to enter full screen mode is granted, the returned promise will resolve and the element will receive a fullscreenchange event to let it know that it's now in full screen mode. if permission is denied, the promise is rejected and the element receives a fullscreenerror event instead. if the element has been detached from the original document, then the document receives these events instead. ...
Element.requestPointerLock() - Web APIs
to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events at the document level. ...
Element - Web APIs
Web › API › Element
ointer event. childnode.remove() removes the element from the children list of its parent. element.removeattribute() removes the named attribute from the current node. element.removeattributens() removes the attribute with the specified name and namespace, from the current node. eventtarget.removeeventlistener() removes an event listener from the element. element.requestfullscreen() asynchronously asks the browser to make the element full-screen. element.requestpointerlock() allows to asynchronously ask for the pointer to be locked on the given element. element.scroll() scrolls to a particular set of coordinates inside a given element. element.scrollby() scrolls an element by the given amount. element.scrollintoview() scrolls the page until the element gets into the vi...
Event - Web APIs
Web › API › Event
it can also be triggered programmatically, such as by calling the htmlelement.click() method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent(). there are many types of events, some of which use other interfaces based on the main event interface. ...
EventTarget.dispatchEvent() - Web APIs
g the event before the method was called, or if the event's type is null or an empty string. exceptions exceptions thrown by event handlers are reported as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously. all applicable event handlers will execute and return before the code continues on after the call to dispatchevent(). dispatchevent() is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model. the event can be created using event constructor. ...
ExtendableEvent.waitUntil() - Web APIs
it can be called multiple times, until all the promises passed to it settle. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274). syntax extendableevent.waituntil(promise); parameters a promise. return value undefined. example using waituntil() within a service worker's install event: addeventlistener('install', event => { const precache = async () => { const cache = await caches.open('static-v1'); return cache.addall([ '/', '/about/', '/static/styles.css' ]); }; event.waituntil(precache()); }); specifications specification status comment service workersthe definition of 'waituntil()' in that specification. working draft initial definition ...
FetchEvent.preloadResponse - Web APIs
rkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. 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 ...
FetchEvent.navigationPreload - Web APIs
lves 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. 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 ...
FetchEvent.respondWith() - Web APIs
, as hinted at in the "global rules" listed above. invalidstateerror the event has not been dispatched or respondwithwith() has already been invoked. examples this fetch event tries to return a response from the cache api, falling back to the network otherwise. addeventlistener('fetch', event => { // prevent the default, and handle the request ourselves. event.respondwith(async function() { // try to get the response from a cache. const cachedresponse = await caches.match(event.request); // return it if we found one. if (cachedresponse) return cachedresponse; // if we didn't find a match in the cache, use the network. return fetch(event.request); }()); }); note: caches.match() is a convenience method. equivalent functionality is to call cache...
FetchEvent - Web APIs
nse yourself. extendableevent.waituntil() extends the lifetime of the event. used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching. examples this fetch event uses the browser default for non-get requests. for get requests it tries to return a match in the cache, and falls back to the network. if it finds a match in the cache, it asynchronously updates the cache for next time. self.addeventlistener('fetch', event => { // let the browser do its default thing // for non-get requests. if (event.request.method != 'get') return; // prevent the default, and handle the request ourselves. event.respondwith(async function() { // try to get the response from a cache. const cache = await caches.open('dynamic-v1'); ...
Fetch basic concepts - Web APIs
ic concepts of the fetch api. note: this article will be added to over time. if you find a fetch concept that you feel needs explaining better, let someone know on the mdn discussion forum, or mdn web docs room on matrix. in a nutshell at the heart of fetch are the interface abstractions of http requests, responses, headers, and body payloads, along with a global fetch method for initiating asynchronous resource requests. because the main components of http are abstracted as javascript objects, it is easy for other apis to make use of such functionality. service workers is an example of an api that makes heavy use of fetch. fetch takes the asynchronous nature of such requests one step further. the api is completely promise-based. guard guard is a feature of headers objects, with possi...
FileError - Web APIs
Web › API › FileError
it extends the fileerror interface described in file writer and adds several new error codes. fileerror objects are passed to error callbacks. ...
FileReader - Web APIs
file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement. important note: filereader is used to read file content from the user's (remote) system in secure ways only. it cannot be used to simply read a file by pathname from a file system. ...
FileHandle API - Web APIs
ations on such object are performed in isolation, meaning that once a lockedfile is active, all operations of this lockedfile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other lockedfile. secured write operation for performance reasons, write (and read) operations are done in memory. periodically, the results of those operation are asynchronously flushed to the device storage area. if for some reason a problem occurs before that, you can lose the results of some operations. to avoid that problem, you can force the data to be flushed by using the lockedfile.flush() method. once this method has been successfully called, you can be sure your change on the file will be safe. // get a lockedfile object from the handle var myfile = my...
File and Directory Entries API support in Firefox - Web APIs
s you can then read. using drag and drop by calling the datatransferitem.getasentry() method, which lets you get a filesystemfileentry or filesystemdirectoryentry for files dropped on a drop zone. you can't use the localfilesystem.requestfilesystem() method to get access to a specified local file system. the localfilesystem.resolvelocalfilesystemurl() method isn't implemented. only the asynchronous versions of the interfaces are implemented. any interfaces with names that end in "sync" aren't available. firefox only supports reading from files in the file system. you can't write to them. in particular, the filesystemfileentry.createwriter() method, used to create a filewriter to handle writing to a file, is not implemented and will just treturn an error. firefox doesn't support the...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
s the font-family descriptor of @font-face . source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
GeolocationCoordinates.longitude - Web APIs
conveniently reference the button element and the two elements into which the latitude and logitude will be drawn, the event listener is established by calling addeventlistener() on the <button> element. when the user clicks the button, we'll fetch and display the location information. upon receiving a click event, we call getcurrentposition() to request the device's current position. this is an asynchronous request, so we provide a callback which receives as in put a geolocationposition object describing the determined position. from the geolocationposition object, we obtain the user's latitude and longitude using position.coords.latitude and position.coords.longitude so we can update the displayed coordinates. the two <span> elements are updated to display the corresponding values after bei...
Using the Geolocation API - Web APIs
ugh the navigator.geolocation object. if the object exists, geolocation services are available. you can test for the presence of geolocation thusly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation is not available */ } getting the current position to obtain the user's current location, you can call the getcurrentposition() method. this initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. when the position is determined, the defined callback function is executed. you can optionally provide a second callback function to be executed if an error occurs. a third, optional, parameter is an options object where you can set the maximum age of the position returned, the time t...
GlobalEventHandlers.onmousewheel - Web APIs
ated. it was used in non-gecko browsers only. instead use the standard wheel event. syntax element.onmousewheel = handlerfunction; var handlerfunction = element.onmousewheel; handlerfunction should be either null or a javascript function specifying the handler for the event. notes see the dom event handlers page for information on working with on... handlers. the mousewheel event is fired asynchronously when a mouse wheel or similar device is operated. it's represented by the mousewheelevent interface. see the mousewheel event documentation for more information about the event. ...
Audio() - Web APIs
n optional domstring containing the url of an audio file to be associated with the new audio element. return value a new htmlaudioelement object, configured to be used for playing back the audio from the file specified by url.the new object's preload property is set to auto and its src property is set to the specified url or null if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the new object. usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement. determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystat...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
...
HTMLElement: beforeinput event - Web APIs
d to any element when designmode is turned on. in the case of contenteditable and designmode, the event target is the editing host. if these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn't editable. bubbles yes cancelable yes interface inputevent event handler property none sync / async sync composed yes default action update the dom element examples this example logs current value of the element immediately before replacing that value with the new one applied to the <input> element. html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('input'); const log = document.gete...
HTMLImageElement.decoding - Web APIs
the decoding property of the htmlimageelement interface represents a hint given to the browser on how it should decode the image. syntax refstr = imgelem.decoding; imgelem.decoding = refstr; values a domstring representing the decoding hint. possible values are: sync: decode the image synchronously for atomic presentation with other content. async: decode the image asynchronously to reduce delay in presenting other content. auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. usage notes the decoding property allows you to control whether or not the browser is allowed to try to parallelize loading your image. if doing so would cause problems, you can specify sync to disable asynchronous loading. this can ...
HTMLImageElement - Web APIs
rrently displayed image was loaded. this may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place. htmlimageelement.decoding an optional domstring representing a hint given to the browser on how it should decode the image. if this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously, or auto to indicate no preference (which is the default). read the decoding page for details on the implications of this property's values. htmlimageelement.height an integer value that reflects the height html attribute, indicating the rendered height of the image in css pixels. htmlimageelement.ismap a boolean that reflects the ismap html attribute, indicating t...
HTMLMediaElement.seekToNextFrame() - Web APIs
this non-standard method is part of an experimentation process around support for non-real-time access to media for tasks including filtering, editing, and so forth. you should not use this method in production code, because its implementation may change—or be removed outright—without notice. you are, however, invited to experiment with it. this method lets you access frames of video media without the media being performed in real time. this also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want). ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
far too easily nowadays. solutions the use of web workers, which allow the main script to run other scripts in new threads, help to alleviate this problem. a well-designed web site or app uses workers to perform any complex or lengthy operations, leaving the main thread to do as little work as possible beyond updating, laying out, and rendering the web page. this is further alleviated by using asynchronous javascript techniques such as promises to allow the main code to continue to run while waiting for the results of a request. however, code running at a more fundamental level—such as code comprising a library or framework—may need a way to schedule code to be run at a safe time while still executing on the main thread, independent of the results of any single request or task. microtas...
HTML Drag and Drop API - Web APIs
. the datatransferitemlist object is a list of datatransferitem objects. the list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items. a key difference between the datatransfer and datatransferitem interfaces is that the former uses the synchronous getdata() method to access a drag item's data, but the latter instead uses the asynchronous getasstring() method. note: dragevent and datatransfer are broadly supported on desktop browsers. however, the datatransferitem and datatransferitemlist interfaces have limited browser support. see interoperability for more information about drag-and-drop interoperability. gecko-specific interfaces mozilla and firefox support some features not in the standard drag-and-drop model. these ...
History.back() - Web APIs
Web › API › History › back
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.back() examples the following short example causes a button on the page to navigate back one entry in the session history. ...
History.forward() - Web APIs
Web › API › History › forward
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.forward() examples the following examples create a button that moves forward one step in the session history. ...
History.go() - Web APIs
Web › API › History › go
add a listener for the popstate event in order to determine when the navigation has completed. syntax history.go([delta]) parameters delta optional the position in the history to which you want to move, relative to the current page. a negative value moves backwards, a positive value moves forwards. so, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages. ...
IDBCursor - Web APIs
Web › API › IDBCursor
l value property. the idbcursor interface of the indexeddb api represents a cursor for traversing or iterating over multiple records in a database. the cursor has a source that indicates which index or object store it is iterating over. it has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. the cursor enables an application to asynchronously process all the records in the cursor's range. you can have an unlimited number of cursors at the same time. you always get the same idbcursor object representing a given cursor. operations are performed on the underlying index or object store. note: this feature is available in web workers. properties note: idbcursorwithvalue is an idbcursor interface with an additional value prope...
IDBCursorWithValue - Web APIs
cursor for traversing or iterating over multiple records in a database. it is the same as the idbcursor, except that it includes the value property. the cursor has a source that indicates which index or object store it is iterating over. it has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. the cursor enables an application to asynchronously process all the records in the cursor's range. you can have an unlimited number of cursors at the same time. you always get the same idbcursorwithvalue object representing a given cursor. operations are performed on the underlying index or object store. note: this feature is available in web workers. <div id="interfacediagram" style="display: inline-block; position: relative; widt...
IDBDatabase - Web APIs
abase connection is unexpectedly closed. also available via the onclose property. error fired when a request returns an error and the event bubbles up to the connection object. also available via the onerror property. versionchange fired when a database structure change was requested. also available via the onversionchange property. example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdatabase object, // when the database is opene...
IDBEnvironment - Web APIs
f the windoworworkerglobalscope mixin). the idbenvironment helper of the indexeddb api contains the indexeddb property, which provides access to indexeddb functionality. it is the top level indexeddb interface implemented by the window and worker objects. note: this feature is available in web workers. properties idbenvironment.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; contains an idbfactory object. example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open("todolist"); dbopenrequest.onsuccess = function(e) { db = dbopenrequ...
IDBFactory.deleteDatabase() - Web APIs
if the database is successfully deleted, then a success event is fired on the request object returned from this method, with its result set to undefined. if an error occurs while the database is being deleted, then an error event is fired on the request object that is returned from this method. ...
IDBFactory.open() - Web APIs
Web › API › IDBFactory › open
if the operation is successful, a success event is fired on the request object that is returned from this method, with its result attribute set to the new idbdatabase object for the connection. if an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method. ...
IDBFactory - Web APIs
the object that implements the interface is window.indexeddb. you open — that is, create and access — and delete a database with this object, and not directly with idbfactory. note: this feature is available in web workers. methods idbfactory.open the current method to request opening a connection to a database. idbfactory.deletedatabase a method to request the deletion of a database. idbfactory.cmp a method that compares two keys and returns a result indicating which one is greater in value. idbfactory.databases a method that returns a list of all available databases, including their names and versions. ...
IDBIndex - Web APIs
Web › API › IDBIndex
an index is a kind of object store for looking up records in another object store, called the referenced object store. you use this interface to retrieve data. you can retrieve records in an object store through the primary key or by using an index. an index lets you look up records in an object store using properties of the values in the object stores records other than the primary key the index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. ...
IDBRequest.error - Web APIs
Web › API › IDBRequest › error
declined to grant you more space. unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a version lower than the one it already has. in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions. the list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. for example, if the the request failed and the result is not available, the invalidstateerror exception is thrown. example the following example requests a given record title, onsuccess gets the ...
IDBTransaction - Web APIs
all reading and writing of data is done within transactions. you use idbdatabase to start transactions, idbtransaction to set the mode of the transaction (e.g. is it readonly or readwrite), and you access an idbobjectstore to make a request. you can also use an idbtransaction object to abort transactions. note: this feature is available in web workers. ...
ImageBitmap - Web APIs
properties imagebitmap.height read only is an unsigned long representing the height, in css pixels, of the imagedata. imagebitmap.width read only is an unsigned long representing the width, in css pixels, of the imagedata. ...
IntersectionObserver - Web APIs
the ancestor element or viewport is referred to as the root. when an intersectionobserver is created, it's configured to watch for given ratios of visibility within the root. the configuration cannot be changed once the intersectionobserver is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer. ...
Timing element visibility with the Intersection Observer API - Web APIs
in this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the intersection observer api to track how much time each ad is visible to the user. when an ad exceeds one minute of visible time, it will be replaced with a new one. ...
LocalFileSystemSync - Web APIs
can request access to a sandboxed file system by requesting localfilesystemsync object from within a web worker. the global methods in the window object requestfilesystemsync() and resolvelocalfilesystemsyncurl() methods are exposed to the worker's global scope. calling window.requestfilesystemsync() for creates new storage for your web app. for more concepts, see the counterpart article for the asynchronous api. example //taking care of the browser-specific prefix window.requestfilesystemsync = window.requestfilesystemsync || window.webkitrequestfilesystemsync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the error callback // for denial of access and ot...
MediaDevices.getUserMedia() - Web APIs
permission, or matching media is not available, then the promise is rejected with notallowederror or notfounderror respectively. note: it's possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice at all and may simply ignore the request. ...
MediaTrackSupportedConstraints.cursor - Web APIs
sor constraint is supported by the device and user agent. example this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the cursor constraint only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. ...
MediaTrackSupportedConstraints.displaySurface - Web APIs
mple this method sets up the constraints object specifying the options for the call to getdisplaymedia(). it adds the displaysurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. ...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
edia(). it adds the logicalsurface constraint (requesting that only logical display surfaces—those which may not be entirely visible onscreen—be included among the options available to the user) only if it is known to be supported by the browser. capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem. ...
Media Capture and Streams API (Media Stream) - Web APIs
the media capture and streams api, often called the media streams api or simply mediastream api, is an api related to webrtc which provides support for streaming audio and video data. it provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process. concepts and usage the api is based on the manipulation of a mediastream object representing a flux of audio- or video-related data. see an example in get the video. a mediastream consists of zero or more mediastreamtrack objects, representing various audio or video tracks. each mediastreamtrack may have one or more channels. the channel represents the ...
Navigator.clipboard - Web APIs
the clipboard api adds to the navigator interface the read-only clipboard property, which returns the clipboard object used to read and write the clipboard's contents. the clipboard api can be used to implement cut, copy, and paste features within a web application. use of the asynchronous clipboard read and write methods requires that the user grant the web site or app permission to access the clipboard. this permission must be obtained from the permissions api using the "clipboard-read" and/or "clipboard-write" permissions. syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard. examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard. navigator.clipboa...
Navigator.share() - Web APIs
Web › API › Navigator › share
ch, when clicked, invokes the web share api to share mdn's url. the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.textcontent = 'mdn shared successfully' } catch(err) { resultpara.textcontent = 'error: ' + err } }); sharing files to share files, first test for and call navigator.canshare(). then include an array of files in the call to navigator.share(): notice: that the sample handles feature detection by testing for navigator.c...
Navigator - Web APIs
Web › API › Navigator
navigator.registercontenthandler() obsolete since gecko 59 allows web sites to register themselves as a possible handler for a given mime type. navigator.registerprotocolhandler() allows web sites to register themselves as a possible handler for a given protocol. navigator.requestmediakeysystemaccess() returns a promise for a mediakeysystemaccess object. navigator.sendbeacon() used to asynchronously transfer a small amount of data using http from the user agent to a web server. navigator.share() invokes the native sharing mechanism of the current platform. navigatorid.taintenabled() deprecated since gecko 1.7.8 obsolete since gecko 9.0 returns false. javascript taint/untaint functions removed in javascript 1.2. navigator.vibrate() causes vibration on devices with support f...
Notification - Web APIs
constructor notification() creates a new instance of the notification object. ...
NotificationAction - Web APIs
properties instance properties these properties are available only on instances of the notification object. ...
OffscreenCanvas - Web APIs
some drawing for the first canvas using the gl context ... // commit rendering to the first canvas var bitmapone = offscreen.transfertoimagebitmap(); one.transferfromimagebitmap(bitmapone); // ... some more drawing for the second canvas using the gl context ... // commit rendering to the second canvas var bitmaptwo = offscreen.transfertoimagebitmap(); two.transferfromimagebitmap(bitmaptwo); asynchronous display of frames produced by an offscreencanvas another way to use the offscreencanvas api, is to call transfercontroltooffscreen() on a <canvas> element, either on a worker or the main thread, which will return an offscreencanvas object from an htmlcanvaselement object from the main thread. calling getcontext() will then obtain a renderingcontext from that offscreencanvas. main.js (mai...
PaymentAddress - Web APIs
// call show() to trigger the browser's payment flow. const response = await request.show(); // process payment. const json = response.tojson(); const httpresponse = await fetch("/pay/", { method: "post", body: json }); const result = httpresponse.
PaymentRequest.onmerchantvalidation - Web APIs
an event handler function which is to be called whenever the merchantvalidation event is fired at the paymentrequest, indicating that the payment handler requires the merchant to validate themselves as allowed to use this payment handler. examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. specifications ...
PaymentResponse.onpayerdetailchange - Web APIs
rname: true, requestpayerphone: true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid. if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpay...
PerformanceTiming.domInteractive - Web APIs
t, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. check if you are in one of these cases before using this property as a proxy for the user experience of a web site's speed of loading. syntax time = performancetiming.dominteractive; specifications specification status comment navigation timingthe definition of 'performancetiming.dominteractive' in that specification. recommendatio...
Pointer Lock API - Web APIs
locked element, if any. here is an example of using pointerlockelement: if(document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); } else { console.log('the pointer lock status is now unlocked'); } the document.exitpointerlock() method is used to exit pointer lock, and like requestpointerlock, works asynchronously using the pointerlockchange and pointerlockerror events, which you'll see more about below. document.exitpointerlock = document.exitpointerlock || document.mozexitpointerlock; // attempt to unlock document.exitpointerlock(); pointerlockchange event when the pointer lock state changes—for example, when calling requestpointerlock(), exitpointerlock(), t...
PushSubscription - Web APIs
ng the subscription id associated with the push subscription. methods pushsubscription.getkey() returns an arraybuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data. pushsubscription.tojson() standard serializer — returns a json representation of the subscription properties. pushsubscription.unsubscribe() starts the asynchronous process of unsubscribing from the push service, returning a promise that resolves to a boolean when the current subscription is successfully unregistered. example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).c...
Push API - Web APIs
Web › API › Push API
push concepts and usage when implementing pushmanager subscriptions, it is vitally important that you protect against csrf/xsrf issues in your app. ...
RTCDTMFSender.insertDTMF() - Web APIs
as long as the connection is active, you can send tones at any time. calling insertdtmf() will append the specified tones to the end of the current tone buffer, so that those tones play after the previously-enqueued tones. ...
RTCDataChannel.bufferedAmount - Web APIs
er the data channel. the queue may build up as a result of calls to the send() method. this only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. closing the data channel doesn't reset this count, even though the user agent purges the queued messages. however, even after closing the channel, attempts to send messages continue to add to the bufferedamount value, even though the messages are neither sent nor buffered. whenever this value decreases to fall to or b...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
his value, a bufferedamountlow event is fired. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. listeners may be added with onbufferedamountlow or addeventlistener(). the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. syntax var threshold = adatachannel.bufferedamountlowthreshold; adatachannel.bufferedamountlowthreshold = threshold; value the number of queued outgoing data bytes below which the buffer is considered to be "low." example in this snippet o...
RTCDataChannel.close() - Web APIs
the sequence of events which occurs in response to this method being called: rtcdatachannel.readystate is set to "closing". ...
RTCRtpReceiver.getStats() - Web APIs
syntax var promise = rtcrtpreceiver.getstats(); return value a javascript promise which is fulfilled once the statistics are available. the promise's fulfillment handler receives as a parameter a rtcstatsreport object containing the collected statistics. the returned statistics include those from all streams which are coming in through the rtcrtpreceiver, as well as any of their dependencies. ...
RTCRtpSender.getStats() - Web APIs
syntax var promise = rtcrtpsender.getstats(); return value a javascript promise which is fulfilled once the statistics are available. the promise's fulfillment handler receives as a parameter a rtcstatsreport object containing the collected statistics. the returned rtcstatsreport accumulates the statistics for all of the streams being sent using the rtcrtpsender, as well as the statistics for any dependencies those streams have. ...
ReadableStreamDefaultReader.read() - Web APIs
unk; 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. it deals with stream chunks not ending on line boundaries and converting from uint8array to strings. ...
SVGImageElement.decode - Web APIs
syntax var promise = svgimageelement.decode(); parameters none. return value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth. exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. ...
SVGImageElement.decoding - Web APIs
the decoding property of the svgimageelement interface represents a hint given to the browser on how it should decode the image. syntax var refstr = svgimageelement.decoding svgimageelement.decoding = refstr; values a domstring representing the decoding hint. possible values are: sync: decode the image synchronously for atomic presentation with other content. async: decode the image asynchronously to reduce delay in presenting other content. auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.svg'; specifications specification status comment html living standardthe definition of 'decoding' in that specif...
SVGImageElement - Web APIs
ibute of the given <image> element. svgimageelement.x read only an svganimatedlength corresponding to the x attribute of the given <image> element. svgimageelement.y read only an svganimatedlength corresponding to the y attribute of the given <image> element. methods this interface also inherits methods from its parent interface, svggraphicselement. svgimageelement.decode() initiates asynchronous decoding of the image data. returns a promise which resolves once the image data is ready to be used. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgimageelement' in that specification. candidate recommendation changed the inheritance from svgelement to svggraphicselement, removed the implemented interfaces...
ServiceWorkerContainer: message event - Web APIs
vent is used in a page controlled by a service worker to receive messages from the service worker. bubbles no cancelable no interface messageevent event handler property onmessage examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ... }); }); the client can receive the message by listening to the message event: // in the page being controlled navigator.serviceworker.addeventlistener('...
ServiceWorkerGlobalScope - Web APIs
a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 12.142857142857142%; vertica...
Service Worker API - Web APIs
ests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available). a service worker is run in a worker context: it therefore has no dom access, and runs on a different thread to the main javascript that powers your app, so it is non-blocking. it is designed to be fully async; as a consequence, apis such as synchronous xhr and localstorage can't be used inside a service worker. service workers only run over https, for security reasons. having modified network requests, wide open to man in the middle attacks would be really bad. in firefox, service worker apis are also hidden and cannot be used when the user is in private browsing mode. note: service workers win ove...
SourceBuffer.abort() - Web APIs
. return value undefined. exceptions exception explanation invalidstateerror the mediasource.readystate property of the parent media source is not equal to open, or this sourcebuffer has been removed from the mediasource. example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state. the mse api is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. for example, consider this code: sourcebuffer.addeventlistener('upd...
SpeechSynthesis.onvoiceschanged - Web APIs
syntax speechsynthesisinstance.onvoiceschanged = function() { ... }; examples this could be used to populate a list of voices that the user can choose between when the event fires (see our speak easy synthesis demo.) note that firefox doesn't support it at present, and will just return a list o...
StorageManager.estimate() - Web APIs
the promise's fulfillment handler is called with a storageestimate containing the usage and quota data. syntax const estimatepromise = storagemanager.estimate(); parameters none. return value a promise that resolves to an object which conforms to the storageestimate dictionary. ...
SubtleCrypto.encrypt() - Web APIs
crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-ctr", counter, length: 64 }, key, encoded ); } let iv = new uint8array(16); let key = new uint8array(16); let data = new uint8array(12345); //crypto functions are wrapped in promises so we have to use await and make sure the function that //contains this code is an async function //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 t...
TransformStream - Web APIs
handlers. properties transformstream.readable read only the readable end of a transformstream. transformstream.writable read only the writable end of a transformstream. methods none examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values. const transformcontent = { start() {}, // required. ...
USBDevice.claimInterface() - Web APIs
omise that resolves when the requested interface is claimed for exclusive access. syntax var promise = usbdevice.claiminterface(interfacenumber) parameters interfacenumber the index of one of the interfaces supported by the device. interfaces are device-specific. return value a promise. example the following example shows claiminterface() in the context of connecting to a usb device. async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'claiminterface()' in that specification. draft initial definition. ...
USBDevice.configuration - Web APIs
n read only property of the usbdevice interface returns a usbconfiguration object for the currently selected interface for a paired usb device. syntax var usbconfiguration = usbdevice.configuration value a usbconfiguration object. example the following example uses this property to test for the existence of a usbconfiguration property to select a configuration before claiming an interface. async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'configuration' in that specification. draft initial definition. ...
USBDevice.opened - Web APIs
Web › API › USBDevice › opened
be controlled by a web page. syntax var serialnumber = usbdevice.opened value a boolean. example this example is for a hypothetical usb device with a multi-colored led. it shows how to test that a device is open before calling usbdevice.controltransferout to set a specified led color. what data can be passed to a usb device and how it is passed is particular and unique to each device. async setdevicecolor(usbdevice, r, g, b) { if (device.opened) { // this hypothetical usb device requires that the data passed to // it be in a uint8array. let payload = new uint8array([r, g, b]); await usbdevice.controltransferout({ requesttype: 'vendor', recipient: 'device', request: 1, value: 0, index: 0, }, payload); } } specifica...
WakeLockSentinel.type - Web APIs
f the wakelocksentinel interface returns a string representation of the currently acquired wakelocksentinel type. syntax var type = wakelocksentinel.type; value a string representation of the currently acquired wake lock type. type read only return values are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. examples this example shows an asynchronous function that acquires a wakelocksentinel, then logs the type to the console. const requestwakelock = async () => { wakelock = await navigator.wakelock.request('screen'); console.log(wakelock.type); // logs 'screen' }; requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'wakelocktype' in that specification. ...
WebGL2RenderingContext.beginQuery() - Web APIs
the target parameter indicates which kind of query to begin. syntax void gl.beginquery(target, query); parameters target a glenum specifying the target of the query. possible values: gl.any_samples_passed: specifies an occlusion query: these queries detect whether an object is visible (whether the scoped drawing commands pass the depth test and if so, how many samples pass). gl.any_samples_passed_conservative: same as above above, but less accurate and faster version. gl.transform_feedback_primitives_written: number of primitives that are written to transform feedback buffers. ...
WebGL2RenderingContext.createQuery() - Web APIs
syntax webglquery gl.createquery(); parameters none. return value a webglquery object. examples gl must be a webgl2renderingcontext. webglquery objects are not available in webgl 1. var query = gl.createquery(); specifications specification status comment webgl 2.0the definition of 'createquery' in that specification. ...
WebGL2RenderingContext - Web APIs
buffers from the currently bound framebuffer. query objects methods for working with webglquery objects. webgl2renderingcontext.createquery() creates a new webglquery object. webgl2renderingcontext.deletequery() deletes a given webglquery object. webgl2renderingcontext.isquery() returns true if a given object is a valid webglquery object. webgl2renderingcontext.beginquery() begins an asynchronous query. webgl2renderingcontext.endquery() marks the end of an asynchronous query. webgl2renderingcontext.getquery() returns a webglquery object for a given target. webgl2renderingcontext.getqueryparameter() returns information about a query. sampler objects webgl2renderingcontext.createsampler() creates a new webglsampler object. webgl2renderingcontext.deletesampler() deletes ...
WebGLQuery - Web APIs
by default, occlusion queries and primitive queries are available. another kind of queries are disjoint timer queries, which allow you to measure performance and profiling of your gpu. disjoint timer queries are available with the ext_disjoint_timer_query extension only. ...
Compressed texture formats - Web APIs
ssed_texture_etc1* not usable with compressedtexsubimage2d/copytexsubimage2d. no no webgl_compressed_texture_pvrtc width and height must be powers of 2. no no webgl_compressed_texture_s3tc width and height must be multiples of 4. yes no webgl_compressed_texture_s3tc_srgb width and height must be multiples of 4. ...
Signaling and video calling - Web APIs
in essentially all cases. avoid the temptation to try to make it more complicated than that until you really know what you're doing. that way lies madness. all your signaling server now needs to do is send the messages it's asked to. your workflow may also demand login/authentication functionality, but such details will vary. note: the onicecandidate event and createanswer() promise are both async calls which are handled separately. be sure that your signaling does not change order! for example addicecandidate() with the server's ice candidates must be called after setting the answer with setremotedescription(). signaling transaction flow the signaling process involves this exchange of messages between two peers using an intermediary, the signaling server. the exact process will vary, o...
Writing WebSocket client applications - Web APIs
r wss://www.example.com. sending data to the server once you've opened your connection, you can begin transmitting data to the server. to do this, simply call the websocket object's send() method for each message you want to send: examplesocket.send("here's some text that the server is urgently awaiting!"); you can send data as a string, blob, or arraybuffer. as establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a websocket object will be successful. we can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen event handler to do the work: examplesocket.onopen = function (event) { examplesocket.send("here's some text that the server...
The WebSocket API (WebSockets) - Web APIs
node.js server and client. signalr: signalr will use websockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same. caddy: a web server capable of proxying arbitrary commands (stdin/stdout) as a websocket. ws: a popular websocket client & server library for node.js. jsonrpc-bidirectional: asynchronous rpc which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client). cowboy: cowboy is a small, fast and modern http server for erlang/otp with websocket support. related topics ajax javascript specifications specification status comments html living st...
Using bounded reference spaces - Web APIs
ate a session that supports them. since not all hardware supports bounded reference spaces, you should made sure to support bounded reference spaces as an option rather than as a required feature unless you have special knowledge of the environment in which your code will run. ...
Movement, orientation, and motion: A WebXR example - Web APIs
xrbutton.disabled = true; }); } } the label of the button gets adjusted in the code that handles actuallys ttarting and stopping the webxr session; we'll see that below. the webxr session is toggled on and off by the handler for click events on the button, whose label is appropriately set to either "enter webxr" or "exit webxr". this is done by the onxrbuttonclick() event handler. async function onxrbuttonclick(event) { if (!xrsession) { navigator.xr.requestsession(session_type) .then(sessionstarted); } else { await xrsession.end(); if (xrsession) { sessionended(); } } } this begins by looking at the value of xrsession to see if we already have a xrsession object representing an ongoing webxr session. if we don't, the click represents a request ...
Rendering and the WebXR frame animation callback - Web APIs
ce in which you want to draw, with its origin and orientation set at the viewer's starting position and viewing direction. once that's in hand, you request that the browser call your rendering function the next time it needs a framebuffer to render your scene. this is done by calling the xrsession method requestanimationframe(). ...
Background audio processing using AudioWorklet - Web APIs
: load and install the audio processor module create an audioworkletnode, specifying the audio processor module to use by its name connect inputs to the audioworkletnode and its outputs to appropriate destinations (either other nodes or to the audiocontext object's destination property. ...
Web Speech API - Web APIs
there are two components to this api: speech recognition is accessed via the speechrecognition interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately. ...
Window: blur event - Web APIs
Web › API › Window › blur event
it uses addeventlistener() to monitor focus and blur events. ...
Window: focus event - Web APIs
it uses addeventlistener() to monitor focus and blur events. ...
Window.open() - Web APIs
Web › API › Window › open
, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that remote urls won't load immediately. when window.open() returns, the window always contains about:blank. the actual fetching of the url is deferred and starts after the current script block finishes executing. the window creation and the loading of the referenced resource are done asynchronously. examples var windowobjectreference; var windowfeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/...
window.postMessage() - Web APIs
w, at any time, regardless of the location of the document in the window, to send it a message. consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. this cannot be overstated: failure to check the origin and possibly source properties enables cross-site scripting attacks. as with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an exception. postmessage() schedules the messageevent to be dispatched only after all pending execution contexts have finished. for example, if postmessage() is invoked in an event handler, that event handl...
Window - Web APIs
Web › API › Window
e window.frames for more details. properties implemented from elsewhere windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the global object's origin, serialized as a string. (this does not yet appear to be implemented in any browser.) depr...
WindowOrWorkerGlobalScope.indexedDB - Web APIs
syntax var idbfactory = self.indexeddb; value an idbfactory object. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
s lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. see using microtasks in javascript with queuemicrotask() for more details. microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be e...
WindowOrWorkerGlobalScope - Web APIs
he current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the origin of the global scope, serialized as a string. methods these methods are defined on the windoworworkerglob...
WorkerGlobalScope - Web APIs
nsole associated with the worker. properties implemented from elsewhere windoworworkerglobalscope.caches read only returns the cachestorage object associated with the current context. this object enables functionality such as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object. windoworworkerglobalscope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the global object's origin, serialized as a string. (this does not yet appear to be implemented in any browser.) even...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
as of at least gecko 1.9, this no longer supports cross-site loading of documents (use xmlhttprequest or fetch() instead). examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory. ...
Sending and Receiving Binary Data - Web APIs
tegers and sending it; you can use any binary data you'd like, of course. note: support for sending arraybuffer objects using xmlhttprequest was added to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6). add information about other browsers' support here. submitting forms and uploading files please, read this paragraph. firefox-specific examples this example transmits binary content asynchronously, using the post method, and firefox's non-standard sendasbinary(). var req = new xmlhttprequest(); req.open("post", url, true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header to 741, indicating that the data is 741 bytes long. obviously you need to change this value based on the ac...
XMLHttpRequest.multipart - Web APIs
ce gecko 22 this gecko-only feature was removed in firefox/gecko 22. please use server-sent events, web sockets, or responsetext from progress events instead. this boolean indicates if the response is expected to be a stream of possibly multiple xml documents. if set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. all requests must be asynchronous. this enables support for server push; for each xml document that's written to this request, a new xml dom document is created and the onload handler is called between documents. note: when this is set, the onload handler and other event handlers are not reset after the first xmldocument is loaded, and the onload handler is called after each part of the response is received. ...
XMLHttpRequest.open() - Web APIs
the xmlhttprequest method open() initializes a newly-created request, or re-initializes an existing one. note: calling this method for an already active request (one for which open() has already been called) is the equivalent of calling abort(). syntax xmlhttprequest.open(method, url[, async[, user[, password]]]) parameters method the http request method to use, such as "get", "post", "put", "delete", etc. ignored for non-http(s) urls. url a domstring representing the url to send the request to. async optional an optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. if this value is false, the send() method does not return until the response is received. if true, notification of a completed transaction is provided using ...
XMLHttpRequest.responseText - Web APIs
the read-only xmlhttprequest property responsetext returns the text received from a server following a request being sent. syntax var resulttext = xmlhttprequest.responsetext; value a domstring which contains either the textual data received using the xmlhttprequest or null if the request failed or "" if the request has not yet been sent by calling send(). while handling an asynchronous request, the value of responsetext always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. you know the entire content has been received when the value of readystate becomes xmlhttprequest.done (4), and status becomes 200 ("ok"). exceptions invalidstateerror the xmlhttprequest.responsetype is not set to either...
XMLHttpRequest.responseType - Web APIs
strictions below. usage notes synchronous xhr restrictions you cannot change the value of responsetype in a synchronous xmlhttprequest except when the request belongs to a worker. this restriction is designed in part to help ensure that synchronous operations aren't used for large transactions that block the browser's main thread, thereby bogging down the user experience. xmlhttprequests are asynchronous by default; they are only placed in synchronous mode by passing false as the value of the optional async parameter when calling open(). restrictions in workers attempts to set the value of responsetype to document are ignored in a worker. specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.responseXML - Web APIs
turns a document containing the html or xml retrieved by the request; or null if the request was unsuccessful, has not yet been sent, or if the data can't be parsed as xml or html. note: the name responsexml is an artifact of this property's history; it works for both html and xml. usually, the response is parsed as "text/xml". if the responsetype is set to "document" and the request was made asynchronously, instead the response is parsed as "text/html". responsexml is null for any other types of data, as well as for data: urls. if the server doesn't specify the content-type as "text/xml" or "application/xml", you can use xmlhttprequest.overridemimetype() to parse it as xml anyway. this property isn't available to workers. syntax var data = xmlhttprequest.responsexml; value a documen...
XMLHttpRequest.send() - Web APIs
if the request is synchronous, this method doesn't return until the response has arrived. send() accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as put. if the request method is get or head, the body parameter is ignored and the request body is set to null. if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. ...
XMLHttpRequest.timeout - Web APIs
automatically being terminated. the default value is 0, which means there is no timeout. timeout shouldn't be used for synchronous xmlhttprequests requests used in a document environment or it will throw an invalidaccesserror exception. when a timeout happens, a timeout event is fired. note: you may not use a timeout for synchronous requests with an owning window. using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method. example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished. do processing here. }; xhr.ontimeout = function (e) { // xmlhttprequest timed...
XMLHttpRequest - Web APIs
ved. xmlhttprequest.getresponseheader() returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response. xmlhttprequest.open() initializes a request. xmlhttprequest.overridemimetype() overrides the mime type returned by the server. xmlhttprequest.send() sends the request. if the request is asynchronous (which is the default), this method returns as soon as the request is sent. xmlhttprequest.setrequestheader() sets the value of an http request header. you must call setrequestheader()after open(), but before send(). non-standard methods xmlhttprequest.init() initializes the object for use from c++ code. warning: this method must not be called from javascript. xmlhttprequest.op...
XRSession.cancelAnimationFrame() - Web APIs
e, removing the callback terminates updating of the webxr scene. ...
An overview of accessible web applications and widgets - Accessibility
ent and setting its aria role to button, then switching to "edit" mode by making the element writable and removing the role attribute in "edit" mode (since <input> elements have their own role semantics). do not do this. instead, implement the "view" mode using a different element altogether, such as a <div> or <span> with a role of button, and the « edit » mode using a text <input> element. asynchronous content changes under construction. see also live regions keyboard navigation often times developers overlook support for the keyboard when they create custom widgets. to be accessible to a variety of users, all features of a web application or widget should also be controllable with the keyboard, without requiring a mouse. in practice, this usually involves following the conventions su...
WAI ARIA Live Regions/API Support - Developer guides
where the container-[name] attribute has not been set, the at must have code to fall back on the default value as defined in the w3c spec. determining if event was from user input all events will now provide information about whether the event was caused by user input, or was something that the web page caused. this information is retrieved differently on each platform, because some platforms use asynchronous events. in iaccessible2, this is retrieved from the object attribute "event-from-input", which will be set to "true" or "false". if it is not present, then something went wrong and mozilla was not able to provide this information. this information is available only for event_show, event_hide, ia2_event_text_inserted and ia2_event_text_removed. for atk/at-spi, this information is retrieved ...
Overview of events and handlers - Developer guides
to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened. the pattern is therefore easy to learn and implement. the difficulty with events comes from learning the wide variety of events which are generated in modern web browsers. there is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations. notable events web browsers define a large number of events so it is not practical to list them all. the event reference attempts to maintain a list of the standard events used in modern web browsers. in general, we can distinguish events of different kinds based on the object emitting the event including: th...
Event developer guide - Developer guides
Web › Guide › Events
the overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers. the custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code. the remaining pages describe how to use events of different kinds defined by web browsers. ...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
i that closely conforms to opengl es 2.0 that can be used in html5 <canvas> elements. svg an xml-based format of vectorial images that can directly be embedded in the html. performance and integration web workers allows delegation of javascript evaluation to background threads, allowing these activities to prevent slowing down interactive events. xmlhttprequest level 2 allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. this is the technology behind ajax. jit-compiling javascript engines the new generation of javascript engines is much more powerful, leading to greater performance. history api allows the manipulation of the browser history. this is especially useful for pages loading inter...
Developer guides
o and video in the browser means we can use these data streams with technologies such as <canvas>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. this article provides a reference to explain what you need to do. events developer guide events refer to two things: a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page; and the naming, characterization, and use of a large number of incidents of different types. ajax ajax is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and mor...
HTML attribute reference - HTML: Hypertext Markup Language
ubmitted via the form. align <applet>, <caption>, <col>, <colgroup>, <hr>, <iframe>, <img>, <table>, <tbody>, <td>, <tfoot> , <th>, <thead>, <tr> specifies the horizontal alignment of the element. allow <iframe> specifies a feature-policy for the iframe. alt <applet>, <area>, <img>, <input> alternative text in case an image can't be displayed. async <script> executes the script asynchronously. autocapitalize global attribute sets whether input is automatically capitalized when entered by user autocomplete <form>, <input>, <select>, <textarea> indicates whether controls in this form can by default have their values automatically completed by the browser. autofocus <button>, <input>, <keygen>, <s...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
owser marks the image as tainted and restricts access to its image data. if the attribute has an invalid value, browsers handle it as if the anonymous value was used. see cors settings attributes for additional information. decoding provides an image decoding hint to the browser. allowed values: sync decode the image synchronously, for atomic presentation with other content. async decode the image asynchronously, to reduce delay in presenting other content. auto default: no preference for the decoding mode. the browser decides what is best for the user. height the intrinsic height of the image, in pixels. must be an integer without a unit. importance indicates the relative download importance of the resource. priority hints allow the values: auto: no pre...
Cache-Control - HTTP
caches. max-stale[=<seconds>] indicates the client will accept a stale response. an optional value in seconds indicates the upper limit of staleness the client will accept. min-fresh=<seconds> indicates the client wants a response that will still be fresh for at least the specified number of seconds. stale-while-revalidate=<seconds> indicates the client will accept a stale response, while asynchronously checking in the background for a fresh one. the seconds value indicates how long the client will accept a stale response. see "keeping things fresh with stale-while-revalidate" for more information. stale-if-error=<seconds> indicates the client will accept a stale response if the check for a fresh one fails. the seconds value indicates how long the client will accept the stale respon...
HTTP Index - HTTP
Web › HTTP › Index
ge, its location being either the url of the request, or the content of the location header. 223 202 accepted http, reference, status code, success response the hypertext transfer protocol (http) 202 accepted response status code indicates that the request has been received but not yet acted upon. it is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request. it is intended for cases where another process or server handles the request, or for batch processing. 224 203 non-authoritative information http, http status code, reference, status code, successful response the http 203 non-authoritative information response status indicates that the request was successful bu...
202 Accepted - HTTP
Web › HTTP › Status › 202
tocol (http) 202 accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request. it is intended for cases where another process or server handles the request, or for batch processing. status 202 accepted specifications specification title rfc 7231, section 6.3.3: 202 accepted hypertext transfer protocol (http/1.1): semantics and content ...
HTTP response status codes - HTTP
Web › HTTP › Status
sage body. trace: the message body contains the request message as received by the server 201 created the request has succeeded and a new resource has been created as a result. this is typically the response sent after post requests, or some put requests. 202 accepted the request has been received but not yet acted upon. it is noncommittal, since there is no way in http to later send an asynchronous response indicating the outcome of the request. it is intended for cases where another process or server handles the request, or for batch processing. 203 non-authoritative information this response code means the returned meta-information is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. this is mostly used for mirrors o...
JavaScript technologies overview - JavaScript
, as those represent list items. in general, it also forbids using elements and attributes that aren't defined in a standard. looking for the document object, window object, and the other dom elements? read the dom documentation. other notable apis the settimeout and setinterval functions were first specified on the window interface in html standard. xmlhttprequest makes it possible to send asynchronous http requests. the css object model abstract css rules as objects. webworkers allows parallel computation. websockets allows low-level bidirectional communication. canvas 2d context is a drawing api for <canvas>. ...
Public class fields - JavaScript
nstancemethod { publicmethod() { return 'hello world' } } const instance = new classwithpublicinstancemethod() console.log(instance.publicmethod()) // expected output: "hello worl​d" public instance methods are added to the class prototype at the time of class evaluation using object.defineproperty(). they are writable, non-enumerable, and configurable. you may make use of generator, async, and async generator functions. class classwithfancymethods { *generatormethod() { } async asyncmethod() { } async *asyncgeneratormethod() { } } inside instance methods, this refers to the instance itself. in subclasses, super lets you access the superclass prototype, allowing you to call methods from the superclass. class baseclass { msg = 'hello world' basepublicmethod() { retu...
Array.prototype.reduceRight() - JavaScript
value = callback(value, t[k], k, t); } } return value; }; } examples sum up all values within an array var sum = [0, 1, 2, 3].reduceright(function(a, b) { return a + b; }); // sum is 6 flatten an array of arrays var flattened = [[0, 1], [2, 3], [4, 5]].reduceright(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] run a list of asynchronous functions with callbacks in series each passing their results to the next const waterfall = (...functions) => (callback, ...args) => functions.reduceright( (composition, fn) => (...results) => fn(composition, ...results), callback )(...args); const randint = max => math.floor(math.random() * max) const add5 = (callback, x) => { settimeout(callback, randint(1000), x + 5); }...
Promise.prototype.catch() - JavaScript
hen(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch method most of the time var p1 = new promise(function(resolve, reject) { throw new error('uh-oh!'); }); p1.catch(function(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 = new promise(function(resolve, reject) { settimeout(function() { throw new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is never called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silen...
Promise.resolve() - JavaScript
see how then works here. resolving thenables and throwing errors // resolving a thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) // true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not called }); // thenable throws be...
Symbol - JavaScript
array of symbols and lets you find symbol properties on a given object. note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object. constructor symbol() creates a new symbol object. it is incomplete as a constructor because it does not support the syntax "new symbol()". static properties symbol.asynciterator a method that returns the default asynciterator for an object. used by for await...of. symbol.hasinstance a method determining if a constructor object recognizes an object as its instance. used by instanceof. symbol.isconcatspreadable a boolean value indicating if an object should be flattened to its array elements. used by array.prototype.concat(). symbol.iterator a method returni...
WebAssembly.Instance - JavaScript
le 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: { imported_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 funct...
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times. the webassembly.module() constructor function can be called to synchronously compile given webassembly binary code. however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. new webassembly.module(buffersource); parameters buffersource a typed...
Standard built-in objects - JavaScript
d set) contain elements which are easily iterated in the order of insertion. map set weakmap weakset structured data these objects represent and interact with structured data buffers and data coded using javascript object notation (json). arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example). promise generator generatorfunction asyncfunction reflection reflect proxy internationalization additions to the ecmascript core for language-sensitive functionalities. intl intl.collator intl.datetimeformat intl.listformat intl.numberformat intl.pluralrules intl.relativetimeformat intl.locale webassembly ...
Expressions and operators - JavaScript
javascript. this the this keyword refers to a special property of an execution context. function the function keyword defines a function expression. class the class keyword defines a class expression. function* the function* keyword defines a generator function expression. yield pause and resume a generator function. yield* delegate to another generator function or iterable object. async function the async function defines an async function expression. await pause and resume an async function and wait for the promise's resolution/rejection. [] array initializer/literal syntax. {} object initializer/literal syntax. /ab+c/i regular expression literal syntax. ( ) grouping operator. left-hand-side expressions left values are the destination of an assignment. property...
function* - JavaScript
the function name. param optional the name of a formal parameter for the function. statements the statements comprising the body of the function. description generators are functions that can be exited and later re-entered. their context (variable bindings) will be saved across re-entrances. generators in javascript -- especially when combined with promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as callback hell and inversion of control. however, an even simpler solution to these problems can be achieved with async functions. calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. when the iterator's next() method is c...
JavaScript
key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. introducing javascript objects the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. asynchronous javascript discusses asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. client-side web apis explores what apis are, and how to use some of the most common apis you'll come across often in your development work. javascript guide javascript guide a much more detailed guid...
CSS and JavaScript animation performance - Web Performance
thread. the most common property is the css transform. if an element is promoted as a layer, animating transform properties can be done in the gpu, meaning better performance/efficiency, especially on mobile. find out more details in offmainthreadcompositing. to enable the omta (off main thread animation) in firefox, you can go to about:config and search for the layers.offmainthreadcomposition.async-animations. toggle its value to true. after enabling omta, try running the above test again. you should see that the fps of the css animations will now be significantly higher. note: in nightly/developer edition, you should see that omta is enabled by default, so you might have to do the tests the other way around (test with it enabled first, then disable to test without omta.) summary br...
Critical rendering path - Web Performance
remember to measure first. then you can determine whether it should be an optimization priority. optimizing for crp improve page load speed by prioritizing which resources get loaded, controlling the order in which they are loaded, and reducing the file sizes of those resources. performance tips include 1) minimizing the number of critical resources by deferring their download, marking them as async, or eliminating them altogether, 2) optimizing the number of requests required along with the file size of each request, and 3) optimizing the order in which critical resources are loaded by prioritizing the downloading critical assets, shorten the critical path length. ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
urce code of our app server.js, which contains the server part (written in node.js) service-worker.js, which contains the service worker-specific code. let's explore all of these index.js the index.js file starts by registering the service worker: navigator.serviceworker.register('service-worker.js') .then(function(registration) { return registration.pushmanager.getsubscription() .then(async function(subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); it is a little bit more complicated than the service worker we saw in the js13kpwa demo. in this particular case, after registering, we use the registration object to subscribe, and then use the resulting subscription object to complete the whole process. in the registration ...
Features restricted to secure contexts - Web security
available only in secure contexts this section lists all the apis available only in secure contexts, along with browser versions the limitation was introduced in, as appropriate. note: only the browsers that actually support secure contexts are listed in this document. see here for information on secure contexts support. ...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
ng that if you alter the stylesheet dom after importing it, this will be reflected in the processing. rather than modifying the dom it is recommended to use stylesheet parameters which are usually easier and can give better performance. var testtransform = document.implementation.createdocument("", "test", null); // just an example to get a transform into a script as a dom // xmldocument.load is asynchronous, so all processing happens in the // onload handler testtransform.addeventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node. if that node is a document node, you can pass in a full xsl transform or a literal result element transfor...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
n also run wasm code in firefox 47+ by enabling the javascript.options.wasm flag in about:config, or chrome (51+) and opera (38+) by going to chrome://flags and enabling the experimental webassembly flag.) note: if you try to open generated html file (hello.html) directly from your local hard drive (e.g. file://your_path/hello.html), you will end up with an error message along the lines of both async and sync fetching of the wasm failed. you need to run your html file through an http server (http://) — see how do you set up a local testing server? for more information. if everything has worked as planned, you should see "hello world" output in the emscripten console appearing on the web page, and your browser’s javascript console. congratulations, you’ve just compiled c to webassembly...
Caching compiled WebAssembly modules - WebAssembly
function storeindatabase(db, module) { var store = db.transaction([storename], 'readwrite').objectstore(storename); var request = store.put(module, url); request.onerror = err => { console.log(`failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`successfully stored ${url} in wasm cache`...