Search completed in 1.38 seconds.
Function return values - Learn web development
previous overview: building blocks next there's one last essential concept about functions for us to discuss — re
turn values. some functions don't re
turn a significant value, but others do. it's important to understand what their values are, how to use them in your code, and how to make functions re
turn useful values. we'll cover all of these below. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to understand function re
turn values, and how to make use of them. ...
...their values are, how to use them in your code, and how to make functions re
turn useful values. we'll cover all of these below. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to understand function re
turn values, and how to make use of them. what are re
turn values? ...
..., how to use them in your code, and how to make functions re
turn useful values. we'll cover all of these below. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to understand function re
turn values, and how to make use of them. what are re
turn values? ...
...And 21 more matches
Warning: unreachable code after return statement - JavaScript
the javascript warning "unreachable code after re
turn statement" occurs when using an expression after a re
turn statement, or when using a semicolon-less re
turn statement but including an expression directly after. message warning: unreachable code after re
turn statement (firefox) error type warning what went wrong? ...
... the javascript warning "unreachable code after re
turn statement" occurs when using an expression after a re
turn statement, or when using a semicolon-less re
turn statement but including an expression directly after. message warning: unreachable code after re
turn statement (firefox) error type warning what went wrong? ...
...de after re
turn statement" occurs when using an expression after a re
turn statement, or when using a semicolon-less re
turn statement but including an expression directly after. message warning: unreachable code after re
turn statement (firefox) error type warning what went wrong? ...
...And 9 more matches
Components.returnCode
if the javascript code needs to signal failure then that is done by throwing an exception. ...
...if the javascript code needs to signal failure then that is done by throwing an exception. ...
...if the javascript code needs to signal failure then that is done by throwing an exception. ...
...And 6 more matches
HTMLDialogElement.returnValue - Web APIs
examples the following example displays a button to open a <dialog> containing a form via the showmodal() method. from there, either button will close the dialog. ...
... examples the following example displays a button to open a <dialog> containing a form via the showmodal() method. from there, either button will close the dialog. ...
... examples the following example displays a button to open a <dialog> containing a form via the showmodal() method. from there, either button will close the dialog. ...
...And 5 more matches
Error codes returned by Mozilla APIs
an argument supplied to a method was not valid, for instance a null value was supplied as an argument which does not allow null values, or a value was out of range. ns_error_no_aggregation (0x80040110) ns_error_not_available (0x80040111) an operation could not be completed because some other necessary component or resource was not available. ns_error_factory_not_registered (0x80040154) re
turned when a service could not be found. ns_error_factory_register_again (0x80040155) this error is re
turned when registering a component and the registration should try registering again later. ns_error_factory_not_loaded (0x800401f8) ns_error_factory_exists (0xc1f30100) ns_error_factory_no_signature_support (0xc1f30101) ns_error_proxy_invalid_in_parameter (0x80010010) ns_error_pr...
...sn't valid for the platform. ns_error_file_disk_full (0x8052000a) this error will occur if attempting to write to a disk that is full. ns_error_file_corrupted (0x8052000b) indicates that an attempt was made to open or access a file that has been corrupted, or that the format of a file is unknown. this error might occur if a previous attempt to write to the file had failed. this error may be re
turned by various components that use files to indicate that necessary files are not in an expected format. ns_error_file_not_directory (0x8052000c) this error will occur if an attempt was made to perform an operation on a file that is only valid for a directory. this error can be caused by the directoryentries nsifile.attributes attribute. ns_error_file_is_directory (0x8052000d) this error will o...
...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 re
turn this error if the channel has already been opened (and has not yet been closed). ns_error_offline (0x804b0010) ns_error_no_content (0x804b0011) re
turned 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 (0x804b0012) the uri scheme...
...And 4 more matches
return - JavaScript
the re
turn statement ends function execution and specifies a value to be re
turned to the function caller. 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 re
turn [[expression]]; expression the expression whose value is to be re
turned. if omitted, undefined is re
turned instead. description when a re
turn statement is used in a function body, the execution of the function is stopped. if specified, a given value is re
turned to the function caller. for example, the following function re
turns the square of its argument, x, where x is a number. ...
... expression the expression whose value is to be re
turned. if omitted, undefined is re
turned instead. description when a re
turn statement is used in a function body, the execution of the function is stopped. if specified, a given value is re
turned to the function caller. for example, the following function re
turns the square of its argument, x, where x is a number. function square(x) { re
turn x * x; } var demo = square(3); // demo will equal 9 if the value is omitted, undefined is re
turned instead. the following re
turn statements all break the function execution: re
turn; re
turn true; re
turn false; re
turn x; re
turn x + y / 3; automatic semicolon insertion the re
turn statement is affected by automatic semicolon insertion (asi). ...
... re
turn x * x; } var demo = square(3); // demo will equal 9 if the value is omitted, undefined is re
turned instead. the following re
turn statements all break the function execution: re
turn; re
turn true; re
turn false; re
turn x; re
turn x + y / 3; automatic semicolon insertion the re
turn statement is affected by automatic semicolon insertion (asi). no line terminator is allowed between the re
turn keyword and the expression. re
turn a + b; is transformed by asi into: re
turn; a + b; the console will warn "unreachable code after re
turn statement". starting with firefox 40, a warning is shown in the console if unreachable code is found after a re
turn statement. ...
...And 3 more matches
SyntaxError: return not in function - JavaScript
the javascript exception "re
turn (or yield) not in function" occurs when a re
turn or yield statement is called outside of a function. message syntaxerror: 're
turn' statement outside of function (edge) syntaxerror: re
turn not in function (firefox) syntaxerror: yield not in function (firefox) error type syntaxerror. what went wrong? a re
turn or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? ...
...on" occurs when a re
turn or yield statement is called outside of a function. message syntaxerror: 're
turn' statement outside of function (edge) syntaxerror: re
turn not in function (firefox) syntaxerror: yield not in function (firefox) error type syntaxerror. what went wrong? a re
turn or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? ...
...ion (edge) syntaxerror: re
turn not in function (firefox) syntaxerror: yield not in function (firefox) error type syntaxerror. what went wrong? a re
turn or yield statement is called outside of a function. maybe there are missing curly brackets somewhere? the re
turn and yield statements must be in a function, because they end (or pause and resume) function execution and specify a value to be re
turned to the function caller. examples missing curly brackets var cheer = function(score) { if (score === 147) re
turn 'maximum!'; }; if (score > 100) { re
turn 'century!'; } } // syntaxerror: re
turn not in function the curly brackets look correct at a first glance, but this code snippet is missing a { after the first if statement. correct would be: var cheer = function(score) { ...
...And 2 more matches
Event.returnValue - Web APIs
the event property re
turnvalue indicates whether the default action for this event has been prevented or not. it is set to true by default, allowing the default action to occur. setting this property to false prevents the default action. note: while re
turnvalue has been adopted into the dom standard, it is present primarily to support existing code. you should use preventdefault(), and defaultprevented instead of this historical property. syntax event.re
turnvalue = bool; var bool = event.re
turnvalue; value a boolean value which is true if the event has not been canceled; otherwise, if the event has been canceled or the default has been prevented, the value is false. the value re
turned by re
turnvalue is the opposite of the value re
turned by defaultprevented. ...
...aultprevented instead of this historical property. syntax event.re
turnvalue = bool; var bool = event.re
turnvalue; value a boolean value which is true if the event has not been canceled; otherwise, if the event has been canceled or the default has been prevented, the value is false. the value re
turned by re
turnvalue is the opposite of the value re
turned by defaultprevented. usage notes re
turnvalue was introduced into the dom by internet explorer 6, and due to that browser's ubiquity became so commonly used that other browsers eventually implemented it as well. it has been adopted into the dom specification, primarily to ensure that existing web content continues to function going forward. ...
... living standard added for legacy compatibility. ...
...so commonly used that other browsers eventually implemented it as well. it has been adopted into the dom specification, primarily to ensure that existing web content continues to function going forward. new projects should generally avoid using re
turnvalue, although they may if they choose to do so. specifications specification status comment domthe definition of 're
turnvalue' in that specification. living standard added for legacy compatibility. ...
Generator.prototype.return() - JavaScript
the re
turn() method re
turns the given value and finishes the generator. syntax gen.re
turn(value) parameters value the value to re
turn. re
turn value the value that is given as an argument. examples using re
turn() the following example shows a simple generator and the re
turn method. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.re
turn('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if re
turn(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. if no argument is provided, the value property of re
turned object is the same as if .next(). if an argument is provided, it will be set to the value of the ...
...'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if re
turn(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. if no argument is provided, the value property of re
turned object is the same as if .next(). if an argument is provided, it will be set to the value of the value property of the re
turned object. ...
...lue property of re
turned object is the same as if .next(). if an argument is provided, it will be set to the value of the value property of the re
turned object. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.re
turn(); // { value: undefined, done: true } g.re
turn(1); // { value: 1, done: true } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.re
turn' in that specification. ...
TURN - MDN Web Docs Glossary: Definitions of Web-related terms
turn (traversal using relays around nat) is a protocol enabling a computer to receive and send data from behind a network address translator (nat) or firewall.
turn is used by webrtc to allow any two devices on the internet to enter a peer-to-peer connection. ...
...
turn (traversal using relays around nat) is a protocol enabling a computer to receive and send data from behind a network address translator (nat) or firewall.
turn is used by webrtc to allow any two devices on the internet to enter a peer-to-peer connection. ...
JS_SetCallReturnValue2
obsolete since javascript 1.8.5this 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. causes a native to re
turn a reference value (as allowed by ecma 262-3 §11.2.3). syntax void js_setcallre
turnvalue2(jscontext *cx, jsval v); name type description cx jscontext * the context in which the native function is running. v jsval the id of the property of the reference value to be re
turned from the native. descrip...
...ame type description cx jscontext * the context in which the native function is running. v jsval the id of the property of the reference value to be re
turned from the native. description calling js_setcallre
turnvalue2 indicates to the runtime that the native will re
turn a value of type reference. the native must store the object part of the reference value in *rval, and the argument v gives the id of the property part of the reference value. this reference value can then be used as an lvalue in script. an example is in js/src/js.c; searching for js_setcallre
turnvalue2 should find it. ...
Return Codes - Archive of obsolete content
in mozilla/seamonkey, these constants are defined as part of the xpinstall object (formerly the softwareupdate object in netscape communicator 4.5). name code explanation success 0 success. reboot_needed 999 the files were installed, but one or more components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. ...
How to turn off form autocompletion - Web security
he wcag 2.1 success criterion 1.3.5: identify input purpose does not require that autocomplete/autofill actually work - merely that form fields that relate to specific personal user information are programmatically identified. this means that the criterion can be passed (by adding the relevant autocomplete attributes to individual form fields) even when autocompletion for the form itself has been
turned off. disabling autocompletion to disable autocompletion in forms, you can set the autocomplete attribute to "off": autocomplete="off" you can do this either for an entire form, or for specific input elements in a form: <form method="post" action="/form" autocomplete="off"> […] </form> <form method="post" action="/form"> […] <div> <label for="cc">credit card:</label> <input...
Index - Web APIs
ort() the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. 9 abortcontroller.signal api, abortcontroller, experimental, fetch, property, reference, signal the signal read-only property of the abortcontroller interface re
turns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired. 10 abortsignal api, abortsignal, dom, experimental, interface, reference the abortsignal interface represents a signal object that allows you to communicate with a dom request (such as a fetch) and abort it if required via an abortcontroller object. 11 abortsignal...
... abortsignal api, abortsignal, dom, experimental, interface, reference the abortsignal interface represents a signal object that allows you to communicate with a dom request (such as a fetch) and abort it if required via an abortcontroller object. 11 abortsignal.aborted api, abortsignal, experimental, property, reference, aborted the aborted read-only property re
turns a boolean that indicates whether the dom request(s) the signal is communicating with is/are aborted (true) or not (false). 12 abortsignal.onabort api, abortsignal, event handler, experimental, fetch, property, reference, onabort the onabort read-only property of the fetchsignal interface is an event handler invoked when an abort event fires, i.e. when the fetch request(s) th...
... the abstractrange abstract interface is the base class upon which all dom range types are defined. a range is an object that indicates the start and end points of a section of content within the document. 17 abstractrange.collapsed api, abstractrange, dom, dom api, empty, property, range, reference, collapsed the collapsed read-only property of the abstractrange interface re
turns true if the range's start position and end position are the same. 18 abstractrange.endcontainer api, abstractrange, dom, dom api, end, node, position, property, range, read-only, reference, container, endcontainer the endcontainer property of the abstractrange interface re
turns the node in which the end of the range is located. 19 abstractrange.endoffset api, ...
...And 1273 more matches
jspage - Archive of obsolete content
;var h=k.generics;var f=k.initialize;var g=k.afterimplement||function(){};var d=f||i;h=h!==false;d.constructor=native;d.$family={name:"native"}; if(i&&f){d.prototype=i.prototype;}d.prototype.constructor=d;if(a){var e=a.tolowercase();d.prototype.$family={name:e};native.typize(d,e);}var j=function(n,l,o,m){if(!b||m||!n.prototype[l]){n.prototype[l]=o; }if(h){native.genericize(n,l,b);}g.call(n,l,o);re
turn n;};d.alias=function(n,l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){re
turn j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}re
turn this;};d.implement=function(m,l,o){if(typeof m=="string"){re
turn j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }re
turn this;};if(c){d.implement(c);}re
turn d;};native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"...
...ototype[n];if((n=o)){re
turn j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}re
turn this;};d.implement=function(m,l,o){if(typeof m=="string"){re
turn j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }re
turn this;};if(c){d.implement(c);}re
turn d;};native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function(){var d=array.prototype.slice.call(arguments); re
turn b.prototype[c].apply(d.shift(),d);};}};native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};native.typize=function(a,b){if(!a.type){a.type=function(c){re
turn($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boo...
...alueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}re
turn this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:function(){var b={};for(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}re
turn b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}re
turn b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,...
...And 121 more matches
Index
boolean_to_jsval converts a bool argument, b, to a boolean jsval. 19 double_to_jsval jsapi reference, obsolete, spidermonkey double_to_jsval is the inverse of js::tonumber. 20 int_fits_in_jsval jsapi reference, obsolete, spidermonkey determines if a specified c integer value, i, lies within the range allowed for integer jsvals. if so, int_fits_in_jsval re
turns true, and i can be cast to jsval by calling int_to_jsval(i). otherwise, int_fits_in_jsval re
turns false. in this case, the application can still convert i to a jsval using js_newnumbervalue. 21 int_to_jsval jsapi reference, obsolete, spidermonkey int_to_jsval converts a c integer, i, to a jsval. 22 js::add*root jsapi reference, needscontent, obsolete, referenc...
...nction compiles a function from a text string chars, bytes, or srcbuf. 33 js::compileoffthread jsapi reference, reference, référence(2), spidermonkey js::compileoffthread compiles a script, chars for execution. 34 js::compileoptions jsapi reference, reference, référence(2), spidermonkey some methods of js::owningcompileoptions and js::compileoptions re
turn the instance itself to allow method chain. 35 js::construct jsapi reference, reference, référence(2), spidermonkey js::construct calls a specified function as a constructor, fun. 36 js::createerror jsapi reference, reference, référence(2), spidermonkey js::createerror creates an error object with specified properties. 37 js::currentglobalor...
...ce, référence(2), spidermonkey js::construct calls a specified function as a constructor, fun. 36 js::createerror jsapi reference, reference, référence(2), spidermonkey js::createerror creates an error object with specified properties. 37 js::currentglobalornull jsapi reference, reference, référence(2), spidermonkey js::currentglobalornull() re
turns the global object for whatever function is currently running on the context. in other words, it re
turns the global object on the current scope chain. 38 js::deflatestringtoutf8buffer jsapi reference, refere, spidermonkey js::deflatestringtoutf8buffer encodes src as utf8. the caller must either ensure dst has enough space to encode the entire string, or pass the length of the...
...And 110 more matches
sslfnc.html
her tasks required to run network security services. database files are opened read-only. syntax #include "nss.h" secstatus nss_init(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_init opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are perfor...
... numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadwrite instead. before calling nss_init, your program must call pr_init. the policy flags for all cipher suites are
turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the ssl export policy functions: nss_setdomesticpolicy, nss_setexportpolicy, and nss_setfrancepolicy configure the cipher suites for domestic, international, and french versions of software products...
...s_init, nss_initreadwrite provides both read and write access to database files. syntax #include "nss.h" secstatus nss_initreadwrite(char *configdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_initreadwrite opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) with both read and write permission in the specified directory. nss_initreadwrite isnot idempotent, so call it only once. use nss_i...
...And 87 more matches
Index
pconnect components.interfaces is a read-only object whose properties are interfaces indexed by their names. 23 components.interfacesbyid xpcom:language bindings, xpconnect components.interfacesbyid is a read-only array of classes indexed by iid. 24 components.issuccesscode xpcom, xpcom:language bindings, xpconnect determines whether a given xpcom re
turn code (that is, an nsresult value) indicates the success or failure of an operation, re
turning true or false respectively. 25 components.lastresult xpcom:language bindings, xpconnect no summary! 26 components.manager xpcom:language bindings, xpconnect components.manager is a convenience reflection of the global native component manager service. the scripta...
...entmanager interface can be called directly on this object. 27 components.results xpcom:language bindings, xpconnect components.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of errors), with the value of each corresponding to that constant's value. 28 components.re
turncode xpcom:language bindings, xpconnect no summary! 29 components.stack xpcom:language bindings, xpconnect components.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack. this can be used for various diagnostic purposes. 30 components.utils xpcom:language bindings, xpconnec...
...nts.utils.sandbox needsmarkupwork, reference, référence(2), xpcom:language bindings, xpconnect components.utils.sandbox is used to create a sandbox object for use with evalinsandbox(). 32 components.utils.cloneinto this function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it re
turns a reference to the clone: 33 components.utils.createobjectin add-ons, developing mozilla, extensions, javascript, reference, référence(2), xpcom:language bindings, xpconnect components.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment. 34 components.utils.evalinsandbox add-ons, developing mozilla, extensi...
...And 82 more matches
WebIDL bindings
che_0(myclass) ns_impl_cycle_collecting_addref(myclass) ns_impl_cycle_collecting_release(myclass) ns_interface_map_begin_cycle_collection(myclass) ns_wrappercache_interface_map_entry ns_interface_map_entry(nsisupports) ns_interface_map_end if your class doesn't inherit from a class that implements getparentobject, then add a function of that name that, for a given instance of your class, re
turns the same object every time (unless you write explicit code that handles your parent object changing by reparenting js wrappers, as nodes do). the idea is that walking the getparentobject chain will eventually get you to a window, so that every webidl object is associated with a particular window. for example, nsinode::getparentobject re
turns the node's owner document. the re
turn type of get...
... chain will eventually get you to a window, so that every webidl object is associated with a particular window. for example, nsinode::getparentobject re
turns the node's owner document. the re
turn type of getparentobject doesn't matter other than it must either singly-inherit from nsisupports or have a corresponding tosupports method that can produce an nsisupports from it. ...
...parentobject doesn't matter other than it must either singly-inherit from nsisupports or have a corresponding tosupports method that can produce an nsisupports from it. (this allows the re
turn value to be implicitly converted to a parentobject instance by the compiler via one of that class's non-explicit constructors.) if many instances of myinterface are expected to be created quicky, the re
turn value of getparentobject should itself inherit from nswrappercache for optimal performance. re
turning null from getparentobject is allowed in situations in which it's ok to associate the resulting object with a random global object for security purposes; this is not usually ok for things that are exposed to web content. again, if you do not need wrapper caching you don't need to do this. the act...
...And 77 more matches
JXON - Archive of obsolete content
if you have already have a dom tree from using xmlhttprequest, skip to the next paragraph. note: if you are using an instance of xmlhttprequest in order to retrieve your xml file, please use the yourrequest.responsexml property to get a p...
...if you have already have a dom tree from using xmlhttprequest, skip to the next paragraph. note: if you are using an instance of xmlhttprequest in order to retrieve your xml file, please use the yourrequest.responsexml property to get a parsed xml document. don...
...agment or simply an element node. /*\ |*| |*| jxon snippet #1 mdndeveloper network |*| |*| https://developer.mozilla.org/docs/jxon |*| https://developer.mozilla.org/user:fusionchess |*| |*| this framework is released under the gnu public license, version 3 or later. ...
...And 57 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
0%; margin: 5px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; } javascript content var uicolorpicker = (function uicolorpicker() { 'use strict'; function getelembyid(id) { re
turn document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); re
turn; } this.r = ...
...ue 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); re
turn; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color = new color(); color.setrgba(r, g, b, 1); re
turn color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); re
turn color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); re
turn color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; re
turn color; } function hslcolor(h, s, l) { var color = new color()...
...(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); re
turn color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); re
turn color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; re
turn color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); re
turn color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; re
turn color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); re
turn; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.satu...
...And 48 more matches
Color picker tool - CSS: Cascading Style Sheets
olute; opacity: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #ddd; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; } javascript content 'use strict'; var uicolorpicker = (function uicolorpicker() { function getelembyid(id) { re
turn document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); re
turn; } this.r = ...
...ue 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); re
turn; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color = new color(); color.setrgba(r, g, b, 1); re
turn color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); re
turn color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); re
turn color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; re
turn color; } function hslcolor(h, s, l) { var color = new color()...
...(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); re
turn color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); re
turn color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; re
turn color; } function hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); re
turn color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; re
turn color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); re
turn; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.satu...
...And 47 more matches
Starting WebLock
if the object has only registered for one notification, then you can ignore the atopic string and simply handle the event as it occurs. in other words, the observe method should never be called in response to some event for which the object is not registered. ns_imethodimp weblock::observe(nsisupports *asubject, const char *atopic, const prunichar *adata) { re
turn ns_ok; } notification via the observer service is somewhat indirect. the only way to register directly for a notification via the observer service is to instantiate an nsiobserver object. this works for most cases, but consider the case when you have this notification create a component. since the component hasn't been created yet, there are no instantiated nsiobserver objects that can be passe...
...that implements the nsicomponentmanager interface also implements nsiservicemanager, all you have to do is queryinterface the nsicomponentmanager to nsiservicemanager to get the service manager. you can then use the service manager to add the component to the category: nsresult rv; nscomptr<nsiservicemanager> servman = do_queryinterface((nsisupports*)acompmgr, &rv); if (ns_failed(rv)) re
turn rv; do_queryinterface the previous code uses the special nscomptr function do_queryinterface that lets you queryinterface without having to worry about reference counting, error handling, and other overhead. the do_queryinterface knows what interface to qi to based on the nscomptr that is being assigned into. we could have just as easily have used the raw queryinterface() method, but using ns...
... to using createinstance from the nsicomponentmanager, but there is no aggregation parameter since the object has already been constructed. nscomptr<nsicategorymanager> catman; rv = servman->getservicebycontractid(ns_categorymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); if (ns_failed(rv)) re
turn rv; there are two service getters on the nsiservicemanager interface: one that takes a cid and another interface that takes a contract id. here we'll use the latter. the first parameter to the getservicebycontractid is of course the contract id, which is defined in the nsxpcom.h header file. the next parameter is a nifty macro that re
turns the iid for the interface name that you pass in. the la...
...And 46 more matches
Expressions and operators - JavaScript
ht shift assignment x >>>= y x = x >>> y bitwise and assignment x &= y x = x & y bitwise xor assignment x ^= y x = x ^ y bitwise or assignment x |= y x = x | y logical and assignment x &&= y x && (x = y) logical or assignment x ||= y x || (x = y) logical nullish assignment x ??= y x ?? ...
... x &= y x = x & y bitwise xor assignment x ^= y x = x ^ y bitwise or assignment x |= y x = x | y logical and assignment x &&= y x && (x = y) logical or assignment x ||= y x || (x = y) logical nullish assignment x ??= y x ?? (x = y) re
turn value and chaining like most expressions, assignments like x = y have a re
turn value. it can be retrieved by e.g. assigning the expression or logging it: const z = (x = y); // or equivalently: const z = x = y; console.log(z); // log the re
turn value of the assignment x = y. console.log(x = y); // or log the re
turn value directly. the re
turn value matches the expression to the right of the = sign in the “meaning” column of the table above. that means that (x = y) ret...
...etrieved by e.g. assigning the expression or logging it: const z = (x = y); // or equivalently: const z = x = y; console.log(z); // log the re
turn value of the assignment x = y. console.log(x = y); // or log the re
turn value directly. the re
turn value matches the expression to the right of the = sign in the “meaning” column of the table above. that means that (x = y) re
turns y, (x += y) re
turns the resulting sum x + y, (x **= y) re
turns the resulting power x ** y, and so on. in the case of logical assignments, (x &&= y), (x ||= y), and (x ??= y), the re
turn value is that of the logical operation without the assignment, so x && y, x || y, and x ?? y, respectively. note that the re
turn values are always based on the operands’ values before the operation. when chaining these expressi...
...And 46 more matches
JavaScript Daemons Management - Archive of obsolete content
this framework is released under the gnu public license, version 3 or later. ...
...you could safely remove all or some of them, * depending on your needs. if you want to remove them and are using the daemon.safe subsystem you * shou...
...you could safely remove all or some of them, * depending on your needs. if you want to remove them and are using the daemon.safe subsystem you * should also remove the daemon.safe global object methods that require them. **/ daemon.construct = function (aargs...
...And 44 more matches
Shell global objects
fference between each versions. you can get the list of functions by help() function in js shell. variables scriptargs an array that contains arguments passed to js shell. scriptpath a string that is a path of script. console an object that has following property: log evaluate and print expressions to stdout. this function is an alias of the print() function. timesaccessed re
turns a number that indicates how many times this variable is accessed perfmeasurement see perfmeasurement.jsm. shell only functions functions always available version([number]) get or force a script compilation version number. options([option ...]) get or toggle javascript options. load(['foo.js' ...]) load files named by string arguments. filename is relative to the current working dire...
...and debug info linenumber starting line number for error messages and debug info columnnumber starting column number for error messages and debug info global global in which to execute the code newcontext if true, create and use a new cx (default: false) catchtermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and re
turn 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename re
turns...
...ecode if true, and if the source is a cacheentryobject, the bytecode would be encoded and saved into the cache entry after the script execution. asserteqbytecode if true, and if both loadbytecode and savebytecode are true, then the loaded bytecode and the encoded bytecode are compared. and an assertion is raised if they differ. run('foo.js') run the file named by the first argument, re
turning the number of of milliseconds spent compiling and executing it. read('bar.js') reads the file named by the first argument, re
turning the content of the file as string. readline() read a single line from stdin. readlinebuf([ buf ]) emulate readline() on the specified string. the first call with a string argument sets the source buffer. subsequent calls without an argument then read ...
...And 44 more matches
Proxy Auto-Configuration (PAC) file - HTTP
but there is interest in changing this behavior to match https); in firefox, the preference is network.proxy.autoconfig_url.include_path. host the hostname extracted from the url. this is only for convenience; it is the same string as between :// and the first : or / after that. the port number is not included in this parameter. it can be extracted from the url when necessary. ...
...rence is network.proxy.autoconfig_url.include_path. host the hostname extracted from the url. this is only for convenience; it is the same string as between :// and the first : or / after that. the port number is not included in this parameter. it can be extracted from the url when necessary. description re
turns a string describing the configuration. the format of this string is defined in re
turn value format below. ...
...onfig_url.include_path. host the hostname extracted from the url. this is only for convenience; it is the same string as between :// and the first : or / after that. the port number is not included in this parameter. it can be extracted from the url when necessary. description re
turns a string describing the configuration. the format of this string is defined in re
turn value format below. ...
...And 42 more matches
Graceful asynchronous programming with Promises - Learn web development
rstanding 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. essentially, a promise is an object that represents an intermediate state of an operation — in effect, a promise that a result of some kind will be re
turned at some point in the future. there is no guarantee of exactly when the operation will complete and the result will be re
turned, 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 ...
...s no guarantee of exactly when the operation will complete and the result will be re
turned, 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 re
turn its result (unless of course, it takes far too long!), and more interested in being able to respond to it being re
turned, 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 re
turn a promise. let's consider a hypothetical video chat application. the application has a wi...
...ice-only call, among other possible options), it can block until not only all of those decisions are made, but also the camera and microphone have been engaged. also, the user may not respond immediately to these permission requests. this can potentially take a long time. ...
...And 38 more matches
nsIDOMWindowUtils
an element may be restyled multiple times (for example, when an inline element contains blocks). this number also counts restyling of pseudo-elements and anonymous boxes. throws ns_error_not_available if the count can't be provided. focusedinputtype string the type of the currently-focused html <input> element, if one is focused. imageanimationmode unsigned short re
turns the image animation mode of the window. the attribute's value must be one of the animationmode values from imgicontainer. imeisopen boolean re
turns the ime open state. true if it's open, otherwise false. this attribute only works when imestatus is ime_status_enabled. read only. imestatus unsigned long re
turns the current ime status. values correspond to the ime_sta...
...read only. layermanagertype astring what type of layer manager the widget associated with this window is using. "basic" is unaccelerated; other types are accelerated. throws an error if there is no widget associated with this window. read only. ...
...r window. read only. paintingsuppressed boolean true if painting is currently suppressed for this window; otherwise false. read only. this is used on mobile, for example, to prevent attempts to render content until enough of the page has been loaded to avoid content bouncing around excessively as more content is loaded. screenpixelspercsspixel float re
turns the number of screen pixels per css pixel. read only. audiomuted boolean with this it's possible to mute all the mediaelements in this window. we have audiomuted and audiovolume to preserve the volume across mute/umute. audiovolume float range: greater or equal to 0. the real volume level is affected by the volume of all ancestor windows. constants ...
...And 37 more matches
Index - Archive of obsolete content
-on in firefox's add-on bar. 67 windows add-on sdk enumerate and examine open browser windows, open new windows, and listen for window events. 68 low-level apis no summary! 69 /loader create commonjs module loaders. 70 chrome the chrome module gives an add-on sdk add-on access to the components object, which in
turn gives it access to a large set of privileged low-level firefox apis. 71 console/plain-text constructor for a console instance. 72 console/traceback functionality similar to python's traceback module. 73 content/content re-exports three objects from three other modules: loader, worker, and symbiont. 74 content/loader ...
...l editingsession->makewindoweditable(domwindow, editortype, pr_true). the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. ...
...error console can be opened from the tools menu or by ctrl-shift-j. 433 exception logging in javascript extensions, extensions:tools, guide, javascript, javascript:tools, tools, web development, web development:tools in versions of firefox prior to firefox 3, all javascript exceptions were always logged into the error console if they remained unhandled at the time execution re
turned back into c++ code. as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was re
turned to the c++ caller. 434 existing content this is a list of existing mozilla.org documentation. it needs to be checked, prioritized, and migrated. 435 extension frequently aske...
...And 35 more matches
Parser API
/reflect.jsm", obj) built-in objects whether in spidermonkey shell or firefox (after importing), the global singleton object reflect currently contains just the parse method. properties of the reflect object the reflect object currently consists of a single method. reflect.parse(src[, options]) coerces src to a string and parses the result as a javascript program. by default, the parsing re
turns a program object (see below) representing the parsed abstract syntax tree (ast). additional options may be provided via the options object, which can include any of the following properties: loc boolean default: true when loc is true, the parser includes source location information in the re
turned ast nodes. source string default: null a descript...
... line number default: 1 the initial line number to use for source location information. builder builder default: null a builder object, which can be used to produce ast nodes in custom data formats. ...
...: expression; body: statement; } a with statement. interface switchstatement <: statement { type: "switchstatement"; discriminant: expression; cases: [ switchcase ]; lexical: boolean; } a switch statement. the lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). interface re
turnstatement <: statement { type: "re
turnstatement"; argument: expression | null; } a re
turn statement. interface throwstatement <: statement { type: "throwstatement"; argument: expression; } a throw statement. interface trystatement <: statement { type: "trystatement"; block: blockstatement; handler: catchclause | null; guardedhandlers: [ catchclause ]; fina...
...And 35 more matches
Functions - JavaScript
to use a function, you must define it somewhere in the scope from which you wish to call it. ...
...nction declaration, or function statement) consists of the function keyword, followed by: the name of the function. a list of parameters to the function, enclosed in parentheses and separated by commas. the javascript statements that define the function, enclosed in curly brackets, {...}. ...
...ters to the function, enclosed in parentheses and separated by commas. the javascript statements that define the function, enclosed in curly brackets, {...}. for example, the following code defines a simple function named square: function square(number) { re
turn number * number; } the function square takes one parameter, called number. the function consists of one statement that says to re
turn the parameter of the function (that is, number) multiplied by itself. the statement re
turn specifies the value re
turned by the function: re
turn number * number; primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. i...
...And 35 more matches
IAccessibleTable
er-licenses/ia2/accessibletable.idlnot scriptable this interface gives access to a two-dimensional table. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) typically all accessible objects that represent cells or cell-clusters of a table will be at the same time children of the table. in this case iaccessible2.indexinparent() will re
turn the child index which then can be used when calling rowindex() and columnindex(). however, in some cases that kind of implementation will not be possible. when the table cells are not direct children of a table, the object representing the cell can define a "table-cell-index" object attribute identifying the 0 based table cell index. this object attribute is obtained by parsing the attribute stri...
...child index which then can be used when calling rowindex() and columnindex(). however, in some cases that kind of implementation will not be possible. when the table cells are not direct children of a table, the object representing the cell can define a "table-cell-index" object attribute identifying the 0 based table cell index. this object attribute is obtained by parsing the attribute string re
turned by iaccessible2.attributes(). the "table-cell-index" attribute can be used just like a child index of the typical case. ats should first test for the presence of the "table-cell-index" attribute and if it is not present then iaccessible2.indexinparent() can be used as in the typical case where cells are direct children of the table. the range of valid coordinates for this interface are implemen...
...ex" attribute and if it is not present then iaccessible2.indexinparent() can be used as in the typical case where cells are direct children of the table. the range of valid coordinates for this interface are implementation dependent. however, that range includes at least the intervals from the from the first row or column with the index 0 up to the last (but not including) used row or column as re
turned by nrows() and ncolumns(). method overview [propget] hresult accessibleat([in] long row, [in] long column, [out] iunknown accessible ); [propget] hresult caption([out] iunknown accessible ); [propget] hresult childindex([in] long rowindex, [in] long columnindex, [out] long cellindex ); [propget] hresult columndescription([in] long column, [out] bstr description ); [propget] hresult c...
...And 34 more matches
Document - Web APIs
(e.g. html, xml, svg, …), a larger api is available: html documents, served with the "text/html" content type, also implement the htmldocument interface, whereas xml and svg documents implement the xmldocument interface. constructor document() creates a new document object. properties this interface also inherits from the node and eventtarget interfaces. ...
... served with the "text/html" content type, also implement the htmldocument interface, whereas xml and svg documents implement the xmldocument interface. constructor document() creates a new document object. properties this interface also inherits from the node and eventtarget interfaces. document.anchorsread only re
turns a list of all of the anchors in the document. document.body re
turns the <body> or <frameset> node of the current document. ...
... and svg documents implement the xmldocument interface. constructor document() creates a new document object. properties this interface also inherits from the node and eventtarget interfaces. document.anchorsread only re
turns a list of all of the anchors in the document. document.body re
turns the <body> or <frameset> node of the current document. document.charactersetread only re
turns the character set being used by the document. document.compatmode read only indicates whether the document is rendered in quirks or strict mode. ...
...And 34 more matches
StringView - Archive of obsolete content
ript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview constructor is one level above typed arrays. ...
.../ stringview.loadutf8charcode = function (achars, nidx) { /* the iso 10646 view of utf-8 considers valid codepoints encoded by 1-6 bytes, * while the unicode view of utf-8 in 2003 has limited them to 1-4 bytes in order to * match utf-16's codepoints. in front of a 5/6-byte sequence stringview tries to * encode it in any case. ...
...pt! ...
...And 32 more matches
nsIXPConnect
void flagsystemfilenameprefix(in string afilenameprefix, in prbool awantnativewrappers); void garbagecollect(); [noscript,notxpcom] void getcaller(out jscontextptr ajscontext, out jsobjectptr aobject); jsval getcowforobject(in jscontextptr ajscontext, in jsobjectptr aparent, in jsobjectptr awrappedobj); native code only! obsol...
...iption native code only!createsandbox create a sandbox for evaluating code in isolation using evalinsandboxobject(). nsixpconnectjsobjectholder createsandbox( in jscontextptr cx, in nsiprincipal principal ); parameters cx a context to use when creating the sandbox object. principal the principal (or null to use the null principal) to use when evaluating code in this sandbox. ...
...ing description createstackframelocation() nsistackframe createstackframelocation( in pruint32 alanguage, in string afilename, in string afunctionname, in print32 alinenumber, in nsistackframe acaller ); parameters alanguage missing description afilename missing description afunctionname missing description alinenumber missing description acaller missing description re
turn value missing description exceptions thrown missing exception missing description debugdump() void debugdump( in short depth ); parameters depth missing description exceptions thrown missing exception missing description debugdumpevalinjsstackframe() void debugdumpevalinjsstackframe( in pruint32 aframenumber, in string asourcetext ); parameters aframenumber mis...
...And 32 more matches
Places utilities for JavaScript
sy to use functions that can save you from reinventing the wheel and cluttering up your own classes/functions when you need it. global objects there are a few global objects and constants defined in utils.js. these are: qi_node qi_node(anode, aiid) runs a query interface on a bookmark node to expose the interface available to that type. if the interface isn't available to that node, null is re
turned. anode - the bookmark aiid - the re
turn interface wanted. there are several predefined versions of this for common calls. these just take in the node, as the interface is already defined: asvisit(anode) asfullvisit(anode) ascontainer(anode) asquery(anode) annotations a few annotation names are defined here. load_in_sidebar_anno - this annotation is associated with bookmarks or...
...ore. uritypes containertypes leftpanequeries queries that appear in the library's left pane. leftpanefolderid a single folder shown in the library's left pane. allbookmarksfolderid the id of the "all bookmarks" folder shown in the library's left pane. placesflavors generic_view_drop_types methods createfixeduri nsiuri createfixeduri(string aspec) takes in a spec and re
turns a valid uri based on it using the nsiurifixup service. parameters aspec a url string that needs fixup re
turn type re
turns a correct nsiuri. getformattedstring() string getformattedstring(string key, array string params) parameters key the string name to get from the string bundle params strings to substitute into the bundle at designated points see...
...ixup service. parameters aspec a url string that needs fixup re
turn type re
turns a correct nsiuri. getformattedstring() string getformattedstring(string key, array string params) parameters key the string name to get from the string bundle params strings to substitute into the bundle at designated points see xul:stringbundle for more information. re
turn type re
turns a string from the default places stringbundle. getstring() string getstring(string key) parameters key the name of the string to get. re
turn type re
turns a string from the default places stringbundle. ...
...And 31 more matches
Space Manager Detailed Design - Archive of obsolete content
new(size_t asize); void operator delete(void* aptr, size_t asize); static void shutdown(); /* * get the frame that's associated with the space manager. this frame * created the space manager, and the world coordinate space is * relative to this frame. * * you can use queryinterface() on this frame to get any additional * interfaces. */ nsiframe* getframe() const { re
turn mframe; } /** * translate the current origin by the specified (dx, dy). this * creates a new local coordinate space relative to the current * coordinate space. */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * re
turns the current translation from local coordinate space to * world coordinate space. this represents the accumulated calls to * tr...
...l coordinate space relative to the current * coordinate space. */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * re
turns the current translation from local coordinate space to * world coordinate space. this represents the accumulated calls to * translate(). */ void gettranslation(nscoord& ax, nscoord& ay) const { ax = mx; ay = my; } /** * re
turns the y-most of the bottommost band or 0 if there are no bands. ...
...anslate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * re
turns the current translation from local coordinate space to * world coordinate space. this represents the accumulated calls to * translate(). */ void gettranslation(nscoord& ax, nscoord& ay) const { ax = mx; ay = my; } /** * re
turns the y-most of the bottommost band or 0 if there are no bands. * * @re
turn pr_true if there are bands and pr_false if there are no bands */ prbool ymost(nscoord& aymost) const; /** * re
turns a band starting at the specified y-offset. the band data * indicates which parts of the band are available, and which parts * are unavailable * * the band data that is re
turned is in the coordinate space of the * local coordinate system. * * the loca...
...And 30 more matches
Enc Dec MAC Output Public Key as CSR
eader as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* map option letter enumerated commad type */ static commandtype option2command(const char* c) { switch (*c) { case 'g': re
turn gen_csr; case 'e': re
turn encrypt; case 'd': re
turn decrypt; default: re
turn unknown; } } /* * wrap the symkey using public key */ secstatus wrapkey(pk11symkey* key, seckeypublickey *pubkey, secitem **wrappedkey) { secstatus rv; secitem *data = (secitem *)port_zalloc(sizeof(secitem)); if (!data) { pr_fprintf(pr_stderr, "error while allocating memory\n"); ...
...(pubkey); data->data = (unsigned char*)port_zalloc((data->len)*sizeof(unsigned int)); if (!data->data) { pr_fprintf(pr_stderr, "error while allocating memory\n"); rv = secfailure; goto cleanup; } rv = pk11_pubwrapsymkey(ckm_rsa_pkcs, pubkey, key, data); if (rv != secsuccess) { rv = secfailure; } else { *wrappedkey = data; re
turn secsuccess; } cleanup: if (data) { secitem_freeitem(data, pr_true); } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; /* generate the symmetric key */ key = pk11_tokenkeygen...
...ey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_false, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, unsigned char *msg, unsigned int msglen) { secstatus rv = pk11_digestop(ctx, msg, msglen); ...
...And 30 more matches
Encrypt Decrypt_MAC_Using Token
nc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id. */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute re
turned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); re
turn rv; } re
turn rv; } /* * generate a symmetric key. */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { ...
...ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); re
turn null; } } /* generate the symmetric key. */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != sec...
... */ secstatus macfinal(pk11context *ctx, unsigned char *mac, unsigned int *ma...
...And 30 more matches
Debugger.Object - Firefox Developer Tools
ort of exotic object (an opaque wrapper, for example). class a string naming the ecmascript [[class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor re
turns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function’s body). displayname the referent’s display name, if the referent is...
...name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameternames if the referent is a debuggee function, the names of the its parameters, as an array of strings. if the referent is not a debuggee function, or not a function at all, this is undefined. if the referent is a host function for which parameter names are not available, re
turn an array with one element per parameter, each of which is undefined. if the referent is a function proxy, re
turn an empty array. if the referent uses destructuring parameters, then the array’s elements reflect the structure of the parameters. for example, if the referent is a function declared in this way: function f(a, [b, c], {d, e:f}) { ... } then this debugger.object instance’s pa...
...is a string which is the name of the template; undefined otherwise. errorlinenumber if the referent is an error object, this is the line number at which the referent was created; undefined otherwise. errorcolumnnumber if the referent is an error object, this is the column number at which the referent was created; undefined otherwise. isboundfunction if the referent is a debuggee function, re
turns true if the referent is a bound function; false otherwise. if the referent is not a debuggee function, or not a function at all, re
turns undefined instead. isarrowfunction if the referent is a debuggee function, re
turns true if the referent is an arrow function; false otherwise. if the referent is not a debuggee function, or not a function at all, re
turns undefined instead. isgeneratorfunctio...
...And 30 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
er to an integer, just change the base: parseint('11', 2); // 3 similarly, you can parse floating point numbers using the built-in parsefloat() function. unlike its parseint() cousin, parsefloat() always uses base 10. ...
...however the "+" operator simply converts the string to nan if there is an invalid character contained within it. just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better. strings strings in javascript are sequences of unicode characters. this should be welcome news to anyone who has had to ...
...tion is to use an array literal: var a = ['dog', 'cat', 'hen']; a.length; // 3 note that array.length isn't necessarily the number of items in the array. consider the following: var a = ['dog', 'cat', 'hen']; a[100] = 'fox'; a.length; // 101 remember — the length of the array is one more than the highest index. ...
...And 30 more matches
JSAPI Cookbook
(cx), that makes a best guess, and sometimes that is the best that can be done. but in a jsnative the correct way to do this is: /* jsapi */ bool mynative(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); jsobject *global = js_getglobalforobject(cx, &args.callee()); ... ...
...ed argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); jsobject *global = js_getglobalforobject(cx, &args.callee()); ... } defining a function // javascript function justforfun() { re
turn null; } /* jsapi */ bool justforfun(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); args.rval().setnull(); re
turn true; } ... /* * add this to your jscontext setup code. * this makes your c function visible as a global function in javascript. */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) re
turn false; to define many jsapi functions at once, use js_definefunctions. creating an array // javascript var x = []; // or "x = array()", or "x = new array" /* jsapi */ js::root...
...de. * this makes your c function visible as a global function in javascript. */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) re
turn false; to define many jsapi functions at once, use js_definefunctions. ...
...And 29 more matches
IAccessibleText
/ia2/accessibletext.idlnot scriptable a structure containing a substring and the start and end offsets in the enclosing string. 1.0 66 introduced gecko 1.9 inherits from: iunknown last changed in gecko 1.9 (firefox 3) this enum defines values which specify a text() boundary type. ia2_text_boundary_sentence is optional. when a method doesn't implement this method it must re
turn s_false. typically this feature would not be implemented by an application. however, if the application developer was not satisfied with how screen readers have handled the reading of sentences this boundary type could be implemented and screen readers could use the application's version of a sentence rather than the screen reader's. the rest of the boundary types must be supported. this enum is ...
...esult textbeforeoffset([in] long offset, [in] enum ia2textboundarytype boundarytype, [out] long startoffset, [out] long endoffset, [out] bstr text ); methods addselection() adds a text() selection(). hresult addselection( [in] long startoffset, [in] long endoffset ); parameters startoffset starting offset ( 0 based). endoffset offset of first character after new selection() (0 based). re
turn value e_invalidarg if bad [in] passed. s_ok. attributes() re
turns text() attributes. [propget] hresult attributes( [in] long offset, [out] long startoffset, [out] long endoffset, [out] bstr textattributes ); parameters offset text() offset (0 based) startoffset the starting offset of the character range over which all text() attributes match those of offset. (0 based) endoffset the offs...
...tarting offset of the character range over which all text() attributes match those of offset. (0 based) endoffset the offset of the first character past the character range over which all text() attributes match those of offset. (0 based) textattributes a string of attributes describing the text(). the attributes are described in the; text attributes specification on the iaccessible2 web site. re
turn value e_invalidarg if bad [in] passed, [out] values are 0s and null respectively. s_false if there is nothing to re
turn, [out] values are 0s and null respectively. s_ok. caretoffset() re
turns the position of the caret. re
turns the 0-based offset of the caret within the text(). if the text() is implemented as a tree of text() objects with embed characters in higher levels representing substrings o...
...And 29 more matches
Modularization techniques - Archive of obsolete content
e counting. interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for hiding the the mechanics of how the object was implemented. interface interrogation is performed using the queryinterface() method. the caller passes in an id and a pointer to a address to place the resulting interface. if the query is successful, queryinterface() will re
turn ns_ok. if the object does not support the given interface, it will re
turn ns_nointerface. reference counting is performed using the addref() and release() methods. an objects reference count generally starts at zero. addref() increments that reference count, and release() decrements it. if a call to release() causes the reference count to hit zero, the object will generally free itself. a succes...
..._nointerface. reference counting is performed using the addref() and release() methods. an objects reference count generally starts at zero. addref() increments that reference count, and release() decrements it. if a call to release() causes the reference count to hit zero, the object will generally free itself. a successful queryinterface() will call addref() on the requested interface before re
turning. both addref() and release() re
turn the resulting reference count. the convenience macros ns_addref() and ns_release() are preferred over calling addref and release directly. in debug builds, these macros provide useful reference counting logs. use them wherever possible. /* * the nsisupports interface */ class nsisupports { public: ns_imethod queryinterface(const nsiid &aiid, ...
...sisupports is defined as ns_isupports_iid. queryinterface() has several important characteristics that must be maintained. if you perform a queryinterface() on interface a and obtain interface b, you must be able to perform a queryinterface() b and obtain interface a. if interfaces a and b are both implemented by the same instance, performing a queryinterface() for nsisupports on either should re
turn the exact same interface. this means that even though interface b inherits from nsisupports, performing a queryinterface() on it may not re
turn the same interface. this important behavior is the only reliable mechanism for determining whether interfaces a and b are implemented by the same object.for simple objects, maintaining these behaviors is easy. aggregation, as we will see later, can compli...
...And 28 more matches
Debugger - Firefox Developer Tools
that spidermonkey calls when a call to a debug event handler, breakpoint handler, or similar function throws some exception, which we refer to asdebugger-exception here. exceptions thrown in the debugger are not propagated to debuggee code; instead, spidermonkey calls this function, passingdebugger-exception as its sole argument and the debugger instance as the this value. this function should re
turn a resumption value, which determines how the debuggee should continue. if the uncaught exception hook itself throws an exception,uncaught-hook-exception, spidermonkey throws a new error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. if uncaughtexceptionhook...
...ou can store handler functions for spidermonkey to call when given events occur in debuggee code. when one of the events described below occurs in debuggee code, the engine pauses the debuggee and calls the corresponding debugging handler on each debugger instance that is observing the debuggee. the handler functions receive the debugger instance as their this value. most handler functions can re
turn a resumption value indicating how the debuggee’s execution should proceed. on a new debugger instance, each of these properties is initially undefined. any value assigned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a...
...gging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a debuggee compartment. onnewscript(script,global) new code, represented by the debugger.script instancescript, has been loaded in the scope of the debuggees. ...
...And 28 more matches
HTMLInputElement - Web APIs
ke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlinputelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties properties related to the parent form form read only htmlformelement object: re
turns a reference to the parent <form> element. formaction string: re
turns / sets the element's formaction attribute, containing the uri of a program that processes information submitted by the element. this overrides the action attribute of the parent form. formenctype string: re
turns / sets the element's formenctype attribute, containing the type of content that is used to su...
...ibute, containing the uri of a program that processes information submitted by the element. this overrides the action attribute of the parent form. formenctype string: re
turns / sets the element's formenctype attribute, containing the type of content that is used to submit the form to the server. this overrides the enctype attribute of the parent form. formmethod string: re
turns / sets the element's formmethod attribute, containing the http method that the browser uses to submit the form. this overrides the method attribute of the parent form. formnovalidate boolean: re
turns / sets the element's formnovalidate attribute, indicating that the form is not to be validated when it is submitted. this overrides the novalidate attribute of the parent form. ...
...ormmethod attribute, containing the http method that the browser uses to submit the form. this overrides the method attribute of the parent form. formnovalidate boolean: re
turns / sets the element's formnovalidate attribute, indicating that the form is not to be validated when it is submitted. this overrides the novalidate attribute of the parent form. formtarget string: re
turns / sets the element's formtarget attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. this overrides the target attribute of the parent form. ...
...And 28 more matches
Window - Web APIs
xt></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructors see also the dom interfaces. domparser domparser can parse xml or html source stored in a string into a dom document. domparser is specified in dom parsing and serialization. image used for creating an htmlimageelement. option used for creating an htmloptionelement. staticrange read only re
turns a staticrange() constructor which creates a staticrange object. worker used for creating a web worker. xmlserializer converts a dom tree into xml or html source. properties this interface inherits properties from the eventtarget interface and implements properties from the windoworworkerglobalscope and windoweventhandlers mixins. note that properties which are objects (e.g.,. for overrid...
...operties from the eventtarget interface and implements properties from the windoworworkerglobalscope and windoweventhandlers mixins. note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below. window.closed read only this property indicates whether the current window is closed or not. ...
...note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below. window.closed read only this property indicates whether the current window is closed or not. window.console read only re
turns a reference to the console object which provides access to the browser's debugging console. window.controllers read only re
turns the xul controller objects for the current chrome window. ...
...And 28 more matches
Promise.prototype.then() - JavaScript
the then() method re
turns a promise. it takes up to two arguments: callback functions for the success and failure cases of the 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. if one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any errors. if the promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the re
turned promise simply adopts the final state of the original promise on which then was called. syntax p.then(onfulfilled[, onrejected]); p.then(value => { // fulfillment }, reaso...
...nal state of the original promise on which then was called. syntax p.then(onfulfilled[, onrejected]); p.then(value => { // fulfillment }, reason => { // rejection }); parameters onfulfilled optional a function called if the promise is fulfilled. this function has one argument, the fulfillment value. ...
...ne argument, the fulfillment value. if it is not a function, it is internally replaced with an "identity" function (it re
turns the 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). re
turn 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. ...
...And 28 more matches
this - JavaScript
object using the global globalthis property, regardless of the current context in which your code is running. function context inside a function, the value of this depends on how the function is called. since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. ...
... this will default to the global object, which is window in a browser. function f1() { re
turn this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode re
turn this; } f2() === undefined; // true in the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). this feature wasn't implemented in some browsers when they first started to support strict mode. as a result, they incorrectly re
turned the window object. to set the value of this to a particular value when calling...
...elf. derived classes unlike base class constructors, derived constructors have no initial this binding. calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error. ...
...And 28 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
ng them out into their own functions. not only does this make the code easier to read, it simplifies adding support for new clients: var elm = getelmbyid("myid"); function getelmbyid(aid){ var element = null; if (ismozilla || isie5) element = document.getelementbyid(aid); else if (isnetscape4) element = document.layers[aid]; else if (isie4) element = document.all[aid]; re
turn element; } the above code still has the issue of browser sniffing, or detecting which browser the user is using. browser sniffing is usually done through the useragent, such as: mozilla/5.0 (x11; u; linux i686; en-us; rv:1.5) gecko/20031016 while using the useragent to sniff the browser provides detailed information on the browser in use, code that handles useragents often can make mistakes ...
...c version of a specific browser. for all other purposes you should check for the feature you need rather than the browsers you think will support that feature. javascript also allows inline conditional statements, which can help with code readability: var foo = (condition) ? conditionistrue : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ re
turn (document.getelementbyid) ? document.getelementbyid(aid) : document.all[aid]); } differences between mozilla and internet explorer first, i'll discuss the differences in the way html behaves between mozilla and internet explorer. tooltips legacy browsers introduced tooltips into html by showing them on links and using the value of the alt attribute as a too...
...pe 4 document.layers method and internet explorer's document.all. while document.getelementbyid lets you retrieve one element, you can also use document.layers and document.all to obtain a list of all document elements with a certain tag name, such as all <div> elements. the w3c dom level 1 method gets references to all elements with the same tag name through getelementsbytagname(). the method re
turns an array in javascript, and can be called on the document element or other nodes to search only their subtree. to get an array of all elements in the dom tree, you can use getelementsbytagname("*"). the dom level 1 methods, as shown in table 1, are commonly used to move an element to a certain position and toggle its visibility (menus, animations). netscape 4 used the <layer> tag, which mozilla...
...And 27 more matches
nsINavBookmarksService
ach call to beginupdatebatch. if you do not do this, certain parts of the ui will not get updated and any changes to bookmarks will not get written to disk. from c++ code inside the places component, use nsbookmarksupdatebatcher defined in nsnavbookmarks.h to scope batches. for js or from other components, just please be very careful to close the batch, especially when encountering an error and re
turning early. void beginupdatebatch(); parameters none. changebookmarkuri() this method changes the bookmarked uri for a bookmark. it changes which "place" the bookmark points at, which means all annotations, and so on are carried along. void changebookmarkuri( in nsiuri olduri, obsolete since gecko 1.9 in long long aitemid, in nsiuri anewuri ); parameters olduri obsolete since geck...
...ng long createdynamiccontainer( in long long aparentfolder, in autf8string aname, in astring acontractid, in long aindex ); parameters aparentfolder the id of the parent folder. aname the name of the new folder. acontractid the contract id of the service which is to manipulate this container. aindex the index to insert at, or default_index to append to the end of the list. re
turn value re
turns the id of the newly-inserted folder. createfolder() this method creates a new child folder and inserts it under the given parent. long long createfolder( in long long aparentfolder, in autf8string name, in long index ); parameters aparentfolder the id of the parent folder. name the name of the new folder. index the index to insert at, or default_index to append t...
...he newly-inserted folder. createfolder() this method creates a new child folder and inserts it under the given parent. long long createfolder( in long long aparentfolder, in autf8string name, in long index ); parameters aparentfolder the id of the parent folder. name the name of the new folder. index the index to insert at, or default_index to append to the end of the list. re
turn value re
turns the id of the newly-inserted folder. endupdatebatch() obsolete since gecko 1.9 (firefox 3) causes observers to be notified of an endupdatebatch when a batch is done changing. should match beginupdatebatch() or bad things will happen. void endupdatebatch(); parameters none. exportbookmarkshtml() obsolete since gecko 1.9 (firefox 3) ...
...And 27 more matches
DevTools API - Firefox Developer Tools
. parameters: target {target} - the target the toolbox will debug. toolid {string} - the tool that should be activated. if unspecified the previously active tool is shown. hosttype {string} - the position the toolbox will be placed. one of bottom, side, window, custom. see hosttype for details. hostoptions {object} - an options object passed to the selected host. see hosttype for details. re
turn value: a promise that is fulfilled with the toolbox instance once it has been initialized and the selected tool is loaded. gettoolbox(target) fetch the toolbox object for the given target. parameters: target {target} - the target the toolbox is debugging. re
turn value: toolbox object or undefined if there's no toolbox for the given target.. closetoolbox(target) closes the too...
...tool is loaded. gettoolbox(target) fetch the toolbox object for the given target. parameters: target {target} - the target the toolbox is debugging. re
turn value: toolbox object or undefined if there's no toolbox for the given target.. closetoolbox(target) closes the toolbox for given target. parameters: target {target} - the target of the toolbox that should be closed. re
turn value: a promise that is fulfilled once the toolbox has been destroyed. getdefaulttools() re
turns an array of tooldefinition objects for the built-in tools. getadditionaltools() re
turns an array of tooldefinition objects for tools added by addons. gettooldefinition(toolid) fetch the tooldefinition object for a tool if it exists and is enabled. parameters: toolid {string} - ...
... is fulfilled once the toolbox has been destroyed. getdefaulttools() re
turns an array of tooldefinition objects for the built-in tools. getadditionaltools() re
turns an array of tooldefinition objects for tools added by addons. gettooldefinition(toolid) fetch the tooldefinition object for a tool if it exists and is enabled. parameters: toolid {string} - the id of the tool. re
turn value: a tooldefinition if a tool with the given id exists and is enabled, null otherwise. gettooldefinitionmap() re
turns a toolid → tooldefinition map for tools that are enabled. gettooldefinitionarray() re
turns an array of tooldefinition objects for enabled tools sorted by the order they appear in the toolbox. getthemedefinition(themeid) fetch the themedefinition object for...
...And 27 more matches
Box-shadow generator - CSS: Cascading Style Sheets
.appendchild(unit); input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { setvalue(topic, e.target.value | 0); }); subscribe(topic, function(value) { node.children[0].value = value; }); } var increment = function increment(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) re
turn; if (slider.value + slider.step <= slider.max) { slider.value += slider.step; setvalue(slider.topic, slider.value) notify.call(slider); } }; var decrement = function decrement(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) re
turn; if (slider.value - slider.step >= slider.min) { slider.value -= slider.step; setvalue(topic, slider...
...f (precision > this.step / 2) value = value + this.step; if (this.snap) pos = (value - this.min) * width / delta; this.pointer.style.left = pos - offset/2 + "px"; this.value = value; node.setattribute('data-value', value); notify.call(this); } var setvalue = function setvalue(topic, value) { var slider = sliders[topic]; if (value > slider.max || value < slider.min) re
turn; var delta = slider.max - slider.min; var width = slider.node.clientwidth; var offset = slider.pointer.clientwidth; var pos = (value - slider.min) * width / delta; slider.value = value; slider.pointer.style.left = pos - offset / 2 + "px"; slider.node.setattribute('data-value', value); notify.call(slider); } var setmousetracking = function setmousetracking(elem, callback) { ...
... }); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) re
turn; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem, size; elem = document.queryselectorall('.ui-slider-btn-set'); size = elem.length; for (var i = 0; i < size; i++) setbuttoncomponent(elem[i]); elem = document.queryselectorall('.ui-slider-input'); size = elem.length; for (var i = 0; i < size; i+...
...And 27 more matches
JSAPI User Guide
igned int) report->lineno, message); } int run(jscontext *cx) { // enter a request before running anything in the context. jsautorequest ar(cx); // create the global object and a new compartment. ...
...al(cx); global = js_newglobalobject(cx, &globalclass, nullptr, js::dontfireonnewglobalhook); if (!global) re
turn 1; // enter the new global object's compartment. jsautocompartment ac(cx, global); // populate the global object with the standard globals, like object and // array. if (!js_initstandardclasses(cx, global)) re
turn 1; // your application code here. this may include jsapi calls to create your // own custom js objects and run scripts. re
turn 0; } int main(int argc, const char *argv[]) { // initialize the js engine. if (!js_init()) re
turn 1; // create a js runtime. jsruntime *rt = js_newruntime(8l * 1024l * 1024l); if (!rt) re
turn 1; // create a context. ...
...ls to create your // own custom js objects and run scripts. re
turn 0; } int main(int argc, const char *argv[]) { // initialize the js engine. if (!js_init()) re
turn 1; // create a js runtime. jsruntime *rt = js_newruntime(8l * 1024l * 1024l); if (!rt) re
turn 1; // create a context. jscontext *cx = js_newcontext(rt, 8192); if (!cx) re
turn 1; js_seterrorreporter(rt, reporterror); int status = run(cx); // shut everything down. js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); re
turn status; } each jsnative has the same signature, regardless of what arguments it expects to receive from javascript. the javascript arguments to the function are given in argc and vp. argc tells how many actual...
...And 26 more matches
core/promise - Archive of obsolete content
implementation of promises to make asynchronous programming easier. rationale most of the js apis are asynchronous complementing its non-blocking nature. while this has a good reason and many advantages, it comes with a price. ...
...to continuation passing style, involving lots of machinery: function sphagetti(a, b, callback) { assemble(a, function continuewith(error, c) { if (error) callback(error); else combine(b, c, callback); }); } this style also makes doing things in sequence hard: widget.on('click', function onclick() { promptuserfortwitterhandle(function continuewith(error, handle) { if (error) re
turn ui.displayerror(error); twitter.gettweetsfor(handle, funtion continuewith(error, tweets) { if (error) re
turn ui.displayerror(error); ui.showtweets(tweets); }); }); }); doing things in parallel is even harder: var tweets, answers, checkins; twitter.gettweetsfor(user, function continuewith(result) { tweets = result; somethingfinished(); }); stackoverflow.getanswersfor(q...
...ult; somethingfinished(); }); foursquare.getcheckinsby(user, function continuewith(result) { checkins=result; somethingfinished(); }); var finished = 0; function somethingfinished() { if (++finished === 3) ui.show(tweets, answers, checkins); } this also makes error handling quite an adventure. promises consider another approach, instead of continuation via callbacks, a function re
turns an object that represents a eventual result, either successful or failed. this object is a promise, both figuratively and by name, to eventually resolve. we can call a function on the promise to observe either its fulfillment or rejection. if the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. in the add-on ...
...And 25 more matches
Bytecode Descriptions
typeof, typeofexpr stack: val ⇒ (typeof val) the typeof operator. infallible. the result is always a string that depends on the type of val. jsop::typeof and jsop::typeofexpr are the same except that--amazingly--jsop::typeof affects the behavior of an immediately preceding jsop::getname or jsop::getgname instruction! this is how we implement typeof step 2, making typeof nonexistingvariable re
turn "undefined" instead of throwing a referenceerror. in a global scope: typeof x compiles to getgname "x"; typeof. typeof (0, x) compiles to getgname "x"; typeofexpr. emitting the same bytecode for these two expressions would be a bug. per spec, the latter throws a referenceerror if x doesn't exist. format: jof_ic pos stack: val ⇒ (+val) the unary + operator. +val doesn't do any actual math. ...
...n executing with iter on the stack, starting with the next instruction (always jsop::loophead). code must not jump into or out of this region: control can enter only by executing jsop::iter and can exit only by executing a jsop::enditer or by exception unwinding. (a jsop::enditer is always emitted at the end of the loop, and extra copies are emitted on "exit slides", where a break, continue, or re
turn statement exits the loop.) typically a single try note entry marks the contiguous chunk of bytecode from the instruction after jsop::iter to jsop::enditer (inclusive); but if that range contains any instructions on exit slides, after a jsop::enditer, then those must be correctly noted as outside the loop. format: jof_ic moreiter stack: iter ⇒ iter, name get the next property name for a for-i...
... iteration checkisobj operands: (checkisobjectkind kind) stack: result ⇒ result check that the top value on the stack is an object, and throw a typeerror if not. kind is used only to generate an appropriate error message. implements: getiterator step 5, iteratornext step 3. both operations call a js method which scripts can define however they want, so they check afterwards that the method re
turned 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 ⇒ async...
...And 25 more matches
tabbrowser - Archive of obsolete content
iewer type: nsimarkupdocumentviewer this read-only property contains the nsimarkupdocumentviewer which is responsible for drawing the document. securityui type: nsisecurebrowserui the read-only property holds an object which may be used to determine the security level of the loaded document. selectedbrowser type: browser element this read-only property re
turns the currently displayed browser element. selectedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. sessionhistory type: nsishistory this read-only property contains the nsishistory object which holds the session histor...
... selectedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. sessionhistory type: nsishistory this read-only property contains the nsishistory object which holds the session history. tabcontainer type: tabs element re
turns the tabs element that contains the tabs. this is useful for add-ons that need to use events related to tabs in the browser window. tabs type: array a nodelist containing the tab objects for each tab in the tabbrowser. this is a shortcut for looking at the tabs in the tabcontainer. visibletabs type: array an array containing tab objects for each visible tab in the tabbrowser. this lets you ...
...faultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addprogresslistener( listener ) re
turn type: no re
turn value add a progress listener to the browser which will monitor loaded documents. the progress listener should implement the nsiwebprogresslistener interface. addtab( url, referreruri, charset, postdata, owner, allowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... }) re
turn type: ...
...And 24 more matches
Encrypt Decrypt MAC Keys As Session Objects
enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute re
turned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); re
turn rv; } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { ...
...ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); re
turn null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secs...
...anism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, unsigned char *msg, unsigned int msglen) { secstatus rv = pk11_digestop(ctx, msg, msglen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : digestop()\n"); } re
turn rv; } /* * finalize macing */ secstatus macfinal(pk11context *ctx, unsigned char *mac, unsigned int *mac...
...And 24 more matches
Encrypt and decrypt MAC using token
enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute re
turned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); re
turn rv; } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { ...
...ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); re
turn null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secs...
...anism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, unsigned char *msg, unsigned int msglen) { secstatus rv = pk11_digestop(ctx, msg, msglen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : digestop()\n"); } re
turn rv; } /* * finalize macing */ secstatus macfinal(pk11context *ctx, unsigned char *mac, unsigned int *mac...
...And 24 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
r headers */ #include <prthread.h> #include <plgetopt.h> #include <prerror.h> #include <prinit.h> #include <prlog.h> #include <prtypes.h> #include <plstr.h> /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute re
turned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); re
turn rv; } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { ...
...ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); re
turn null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secs...
...anism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, unsigned char *msg, unsigned int msglen) { secstatus rv = pk11_digestop(ctx, msg, msglen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : digestop()\n"); } re
turn rv; } /* * finalize macing */ secstatus macfinal(pk11context *ctx, unsigned char *mac, unsigned int *mac...
...And 24 more matches
lang/functional - Archive of obsolete content
functional helper methods. usage the lang/functional module provides functional helper methods. some of these functions implement apis from jeremy ashkenas's underscore.js and all credits go to him and his contributors. globals functions method(lambda) takes a function and re
turns a method associated with an object. when the method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. ...
...od associated with an object. when the method is invoked on an instance of the object, the original function is called. it is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the method. let { method } = require("sdk/lang/functional"); let mynumber = { times: method(times), add: method(add), number: 0 }; function times (target, x) { re
turn target.number *= x; } function add (target, x) { re
turn target.number += x; } console.log(mynumber.number); // 0 mynumber.add(10); // 10 mynumber.times(2); // 20 mynumber.add(3); // 23 parameters lambda : function the function to be wrapped and re
turned. re
turns function : the wrapped lambda. defer(fn) takes a function and re
turns a wrapped version of the function. calling the wrapped v...
...lang/functional"); let fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // this will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myevent` // function, making it non-blocking and executing on the // next event loop parameters fn : function the function to be deferred. ...
...And 23 more matches
Install script template - Archive of obsolete content
o"; var plugin_description = "my exemplary plugin mine all mine"; // registry constant paths // these will be used when the win32 registry keys are written var hkey_local_machine = "hkey_local_machine"; var hkey_current_user = "hkey_current_user"; var reg_moz_path = "software\\mozillaplugins"; // my own error code in case secondary installation fails var nosecondaryinstall = 1; // error re
turn codes need some memory var err; // error re
turn codes when we try and install to the current browser var errblock1; // error re
turn codes when we try and do a secondary installation var errblock2 = 0; // global variable containing our secondary install location var secondaryfolder; //special error values used by the cycore developers (www.cycore.com) who helped make this install script va...
...ing current browser install due to lack of space..."); cancellinstall(); } // secondary install block, which sets up plugins and xpt in another location in addition to the current browser errblock2 = createsecondaryinstall(); // performinstall block, in which error conditions from previous blocks are checked. ...
...n failed, * you still have a chance to install the plugin for the already * installed gecko browsers. ...
...And 23 more matches
IPDL Tutorial
(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 re
turn 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 from-parent-to-child, from-child-to-parent, or both ways.
...ply assign a valid value to it, as follows: avariant = false; structs ipdl has built-in support for arbitrary collections of serializable data types. struct namevaluepair { nscstring name; nscstring value; }; in implementation code, these structs can be created and used like so: namevaluepair entry(astring, anotherstring); foo(entry.name(), entry.value()); // named accessor functions re
turn references to the members arrays ipdl has simple syntax for arrays: invokemethod(nscstring[] args); in c++ this is translated into a nstarray reference: virtual bool recvinvokemethod(nstarray<nscstring>& args); ipdl's generated data structures can be used in several protocols if they are defined in a separate .ipdlh file. these files must be added to the ipdl.mk makefile like regular ...
... a separate .ipdlh file. these files must be added to the ipdl.mk makefile like regular .ipdl files, and they use the same syntax (except they cannot declare protocols). to use the structures defined in foo.ipdlh, include it as follows. // in a .ipdl file include foo; synchronous and rpc messaging up until now, all the messages have been asynchronous. the message is sent, and the c++ method re
turns immediately. but what if we wanted to wait until the message was handled, or get re
turn values from a message? in ipdl, there are three different semantics: asynchronous semantics; the sender is not blocked. wait until the receiver acknowledges that it received the message. we call this synchronous semantics, as the sender blocks until the receiver receives the message and sends back a repl...
...And 23 more matches
EncDecMAC using token object - sample 3
n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute re
turned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); re
turn rv; } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) {...
...v; } re
turn rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); re
turn null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } r...
...null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } re
turn key; } /* * macinit */ secstatus macinit(pk11context *ctx) { secstatus rv = pk11_digestbegin(ctx); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : pk11_digestbegin()\n"); } re
turn rv; } /* * macupdate */ secstatus macupdate(pk11context *ctx, unsigned char *msg, unsigned int msglen) { secstatus rv = pk11_digestop(ctx, msg, msglen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "compute mac failed : digestop()\n"); } re
turn rv; } /* * finalize macing */ secstatus macfinal(pk11context *ctx, unsigned char *mac, unsigned int *maclen, unsigned int maxlen) { secstatus rv = pk11_d...
...And 23 more matches
Creating the Component Code
tually happening. in this case, the long-hand implementation gives us an opportunity to talk about various features of xpcom. what we'll be working on the component we'll be working on in this book controls a special mode in your browser that prevents users from leaving the current domain or a set of safe domains. once enabled, this "weblock" mode is password protected and persists until it is
turned off by the password holder. it can be used to implement parental controlled browsing for children, or for targeted "kiosk browsing," where the content is restricted to a particular server. web lock user interface shows the icon that is used to activate the web lock mode (leftmost in the status bar) once you have installed the weblock component and the extra user interface. web lock user interf...
... of acceptable domains. in a way, the factory and module layers are glue to plug the xpcom object into the larger xpcom system. one layer above the object itself is the nsifactory object. this object provides basic abstraction of the xpcom object itself. as you can see in onion peel view of xpcom component creation, the main accessor for the xpcom object is createinstance, which is expected to re
turn the object that matches a given cid and iid pair. moving another layer outward is the nsimodule. this interface provides yet another abstraction of the nsifactory object, and may allow for multiple nsifactory objects. the key to this interface is that the re
turn type of getclassobject does not have to be an nsifactory. instead, the nsimodule can ask for implementation details about the xpcom obj...
...ual relationships between the client and component interfaces. the variable kifactoryiid, for example, provides methods like equals() that can be used to facilitate comparisons in the code, as in the following example from the mozilla source: using class methods to handle identifiers if (aiid.equals(ns_get_iid(nsisupports))) { *ainstanceptr = (void*)(nsisupports*)this; ns_addref_this(); re
turn ns_ok; } finally, sample_cid is an example of a cid that uniquely identifies the component. all of the 128-bit numbers used in xpcom - the class and the interface ids - are examples of uuids, or universal unique identifiers, which were discussed in object interface discovery. generating cids to generate a cid for your component, you can use the uuidgen tool that comes with most unix distribu...
...And 23 more matches
Border-image generator - CSS: Cascading Style Sheets
createelement('input'); input.setattribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { var value = parsefloat(e.target.value); if (isnan(value) === true) setvalue(obj.topic, obj.value); else setvalue(obj.topic, value); }); re
turn input; }; var slidercomponent = function slidercomponent(obj, sign) { var slider = document.createelement('div'); var startx = null; var start_value = 0; slider.addeventlistener("click", function(e) { document.removeeventlistener("mousemove", slidermotion); setvalue(obj.topic, obj.value + obj.step * sign); }); slider.addeventlistener("mousedown", function(e) { startx = e...
...nd = function slideend(e) { document.removeeventlistener("mousemove", slidermotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var slidermotion = function slidermotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientx - startx) / obj.sensivity | 0; var value = delta * obj.step + start_value; setvalue(obj.topic, value); }; re
turn slider; }; var inputslider = function(node) { var min = parsefloat(node.getattribute('data-min')); var max = parsefloat(node.getattribute('data-max')); var step = parsefloat(node.getattribute('data-step')); var value = parsefloat(node.getattribute('data-value')); var topic = node.getattribute('data-topic'); var unit = node.getattribute('data-unit'); var name = node.getattribut...
...appendchild(input); node.appendchild(slider_right); this.input = input; sliders[topic] = this; setvalue(topic, value); }; inputslider.prototype.setinputvalue = function setinputvalue() { this.input.value = this.value.tofixed(this.precision) + this.unit; }; var setvalue = function setvalue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) re
turn; value = parsefloat(value.tofixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); slider.setinputvalue(); if (send_notify === false) re
turn; notify.call(slider); }; var setmax = function setmax(topic, value) { var slider = sliders[topic]; ...
...And 23 more matches
Introduction to using XPath in JavaScript - XPath
avascript internally, in extensions, and from websites. mozilla implements a fair amount of the dom 3 xpath, which means that xpath expressions can be run against both html and xml documents. the main interface to using xpath is the evaluate function of the document object. document.evaluate this method evaluates xpath expressions against an xml based document (including html documents), and re
turns a xpathresult object, which can be a single node or a set of nodes. the existing documentation for this method is located at document.evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below. var xpathresult = document.evaluate( xpathexpression, contextnode, namespaceresolver, resulttype, result ); parameters the evaluate function ta...
...a total of five parameters: xpathexpression: a string containing the xpath expression to be evaluated. contextnode: a node in the document against which the xpathexpression should be evaluated, including any and all of its child nodes. the document node is the most commonly used. namespaceresolver: a function that will be passed any namespace prefixes contained within xpathexpression which re
turns a string representing the namespace uri associated with that prefix. this enables conversion between the prefixes used in the xpath expressions and the possibly different prefixes used in the document. the function can be either: created by using the creatensresolver method of a xpathevaluator object. you should use this virtually all of the time. null, which can be used for html docume...
...used for html documents or when no namespace prefixes are used. note that, if the xpathexpression contains a namespace prefix, this will result in a domexception being thrown with the code namespace_err. a custom user-defined function. see the using a user defined namespace resolver section in the appendix for details. ...
...And 23 more matches
Editor Embedding Guide - Archive of obsolete content
l editingsession->makewindoweditable(domwindow, editortype, pr_true). the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. ...
...rtlinknoui cmd_insertimagenoui cmd_inserthr cmd_charset sets the charset for the document. getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring) note there must be a clear undo stack or this will not work. cmd_copy copies current selection. getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand. this will not really give you any concrete information on the state of the command. cmd_cut cuts current selection. getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand. this will not really give you any concrete information on the...
...ndstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand. this will not really give you any concrete information on the state of the command. cmd_delete deletes current selection. getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand. this will not really give you any concrete information on the state of the command. cmd_paste pastes into current selection or if there is no selection at the cursor position. getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will re
turn whether or not it is possible to call docommand. t...
...And 22 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
progname, dbdir, headerfilename, encryptedfilename); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-d -d <dbdirpath> -b <headerfilename> -e <encryptfilename> -o <opfilename>\n"); exit(-1); } } /* * sign the contents of input file using private key and * re
turn result as secitem */ secstatus signdata(const char *infilename, seckeyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { ...
...ss) { pr_fprintf(pr_stderr, "problem while sgn_update\n"); goto cleanup; } } rv = sgn_end(sgn, res); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_end\n"); goto cleanup; } cleanup: if (infile) { pr_close(infile); } if (sgn) { sgn_destroycontext(sgn, pr_true); } re
turn rv; } /* * verify the signature using public key */ secstatus verifydata(const char *infilename, seckeypublickey *pk, secitem *sigitem, secupwdata *pwdata) { unsigned int nb; unsigned char ibuf[4096]; secstatus rv = secfailure; vfycontext *vfy = null; prfiledesc *infile = null; /* open the input file for reading */ infile = ...
...success) { pr_fprintf(pr_stderr, "problem while vfy_update\n"); goto cleanup; } } rv = vfy_end(vfy); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while vfy_end\n"); goto cleanup; } cleanup: if (infile) { pr_close(infile); } if (vfy) { vfy_destroycontext(vfy, pr_true); } re
turn rv; } /* * write cryptographic parameters to header file */ secstatus writetoheaderfile(const char *buf, unsigned int len, headertype type, prfiledesc *outfile) { secstatus rv; const char *header; const char *trailer; switch (type) { case symkey: header = enckey_header; trailer = enckey_trailer; break; ...
...And 22 more matches
sample2
* missing publically from nss versions earlier than 3.13 */ #ifndef sec_error_base #define sec_error_base (-0x2000) typedef enum { sec_error_io = sec_error_base + 0, sec_error_token_not_logged_in = (sec_error_base + 155), sec_error_end_of_list } secerrorcodes; #endif /* port_errortostring introduced in nss 3.13. on earlier versions of nss that * don't support error tables, pr_errortostring will re
turn "unknown code". */ #ifndef port_errortostring #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } he...
...pr_fprintf(pr_stderr, "%s -d -d %s -b %s -e %s -o : output file name is not found\n", progname, dbdir, headerfilename, encryptedfilename); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-d -d <dbdirpath> -b <headerfilename> -e <encryptfilename> -o <opfilename>\n"); exit(-1); } } /* * sign the contents of input file using private key and * re
turn result as secitem */ secstatus signdata(const char *infilename, seckeyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv =...
...leanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_update\n"); goto cleanup; } } rv = sgn_end(sgn, res); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_end\n"); goto cleanup; } cleanup: if (infile) { pr_close(infile); } if (sgn) { sgn_destroycontext(sgn, pr_true); } re
turn rv; } /* * verify the signature using public key */ secstatus verifydata(const char *infilename, seckeypublickey *pk, secitem *sigitem, secupwdata *pwdata) { unsigned int nb; unsigned char ibuf[4096]; secstatus rv = secfailure; vfycontext *vfy = null; prfiledesc *infile = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "...
...And 22 more matches
IAccessibleTable2
opget] hresult selectedcolumns([out, size_is(, ncolumns)] long selectedcolumns, [out] long ncolumns ); [propget] hresult selectedrows([out, size_is(, nrows)] long selectedrows, [out] long nrows ); hresult selectrow([in] long row ); [propget] hresult summary([out] iunknown accessible ); hresult unselectcolumn([in] long column ); hresult unselectrow([in] long row ); methods caption() re
turns the caption for the table. the re
turned object could be an iaccessible or an iaccessible2. [propget] hresult caption( [out] iunknown accessible ); parameters accessible if the table has a caption then a reference to it is re
turned, else a null pointer is re
turned. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. cellat() re
turns the accessible object at the spe...
...d row and column in the table. this object could be an iaccessible or an iaccessible2. [propget] hresult cellat( [in] long row, [in] long column, [out] iunknown cell ); parameters row the 0 based row index for which to retrieve the cell. column the 0 based column index for which to retrieve the cell. cell if both row and column index are valid then the corresponding accessible object is re
turned that represents the requested cell regardless of whether the cell is currently visible (on the screen). re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_ok. columndescription() re
turns the description text of the specified column in the table. [propget] hresult columndescription( [in] long column, [out] bstr description ); parameters column the 0 based index of the co...
...r the cell is currently visible (on the screen). re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_ok. columndescription() re
turns the description text of the specified column in the table. [propget] hresult columndescription( [in] long column, [out] bstr description ); parameters column the 0 based index of the column for which to retrieve the description. description re
turns the description text of the specified column in the table if such a description exists. otherwise a null pointer is re
turned. re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to re
turn, [out] value is null. s_ok. iscolumnselected() re
turns a boolean value indicating whether the specified column is completely selected. [propget] hresult iscolumnselec...
...And 22 more matches
nsIAnnotationService
ry annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. nsivariant getpageannotation( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the annotation is set. aname the annotation name. re
turn value re
turns a page annotation. getitemannotation() this method retrieves the value of a given item annotation. throws an error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a diff...
...ions, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. nsivariant getitemannotation( in long long aitemid, in autf8string aname ); parameters aitemid the item on which the annotation is set. aname the annotation name. re
turn value re
turns an item annotation. getpageannotationstring() this method retrieves the value of a given uri annotation in string format. throws an error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given anno...
...annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if the given annotation is set in a different type. astring getpageannotationstring( in nsiuri auri, in autf8string aname ); parameters auri the uri on which the annotation is set. aname the annotation name. re
turn value re
turns a string value page annotation. getitemannotationstring() this method retrieves the value of a given item annotation in string format. throws an error if the annotation does not exist. throws for binary annotations, for which getpageannotationbinary() or getitemannotationbinary() should be used. c++ consumers may use the type-specific methods. the type-specific methods throw if t...
...And 22 more matches
Old Proxy API - Archive of obsolete content
proxy objects, controlled by a handler object. there are two kinds of proxies: object proxies var proxy = proxy.create(handler, proto); and function proxies : var proxy = proxy.createfunction(handler, calltrap, constructtrap); where: proto is an optional object representing the proxy’s prototype (defaults to null if none is provided). calltrap is a variable-argument function(args) { re
turn any; } that reifies “proxy(args)”. note: the this-binding of the calltrap function is the this-binding of the call-site. constructtrap is an optional variable-argument function(args) { re
turn any-object; } that reifies “new proxy(args)”. the this-binding of the constructtrap is either undefined (in strict mode) or the global object (in non-strict mode). if no constructtrap is provided, p...
...the derived trap is undefined, a default implementation using the fundamental traps is used. in other words: fundamental traps are required, derived traps are optional. fundamental traps emulated javascript code handler method description object.getownpropertydescriptor(proxy, name) getownpropertydescriptor: function(name) -> propertydescriptor | undefined should re
turn a valid property descriptor object, or undefined to indicate that no property with name exists in the emulated object. object.getpropertydescriptor(proxy, name) getpropertydescriptor: function(name) -> propertydescriptor | undefined this function doesn't exist in ecmascript 5. like getownpropertydescriptor, but should also search the prototype chain. object.getownpropertyn...
... property with name exists in the emulated object. object.getpropertydescriptor(proxy, name) getpropertydescriptor: function(name) -> propertydescriptor | undefined this function doesn't exist in ecmascript 5. like getownpropertydescriptor, but should also search the prototype chain. object.getownpropertynames(proxy) getownpropertynames: function() -> strings array re
turn an array of all own (non-inherited) property names of the emulated object. object.getpropertynames(proxy) getpropertynames: function() -> strings array this function doesn't exist in ecmascript 5. like getownpropertynames, but should also re
turn non-overridden inherited properties. object.defineproperty(proxy,name,pd) defineproperty: function(name, propertydescriptor) -...
...And 21 more matches
source-editor.jsm
call removeeventlistener(). void addeventlistener( string aeventtype, function acallback ); parameters aeventtype the name of the event type to listen for; see event name constants for possible values. acallback the function to call when the specified event occurs. canredo() determines whether or not there are changes that can be redone. boolean canredo(); parameters none. re
turn value true if there are changes that can be redone, otherwise false. canundo() determines whether or not there are changes that can be undone. boolean canundo(); parameters none. re
turn value true if there are changes that can be undone, otherwise false. destroy() destroys the editor, releasing resource it's allocated and removing event handlers it's installed. you should call this met...
...() finds a string in the editor's text. number find( [optional] string astring [optional] object aoptions ); parameters astring optional the string for which to search. if not specified, the currently selected text in the editor is used as the search string. aoptions optional an optional object containing properties customizing the search operation. see find options for details. re
turn value re
turns an integer indicating the offset into the text at which the first character of the found string is located, or -1 if the string wasn't found. find options the aoptions object can customize the search operation. it may have the following properties: property type description backwards boolean if true, the search begins at start (or the end of the tex...
...finds the next occurrence of the search operation started by the last call to find(). note: this ignores the value you specified for backwards in the original search; it always searches forward. number findnext( boolean awrap }; parameters awrap if true, the search operation will wrap around to the beginning of the text. otherwise, the search stops if the end of the text is reached. re
turn value the offset into the text at which the next occurrence of the string begins, or -1 if the string isn't found. findprevious() finds the previous occurrence of the search operation started by the last call to find(). note: this ignores the value you specified for backwards in the original search; it always searches backward. number findnext( boolean awrap }; parameters awrap if tr...
...And 21 more matches
Debugger.Object - Firefox Developer Tools
t instance), or null if it has no prototype. class a string naming the ecmascript [[class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor re
turns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayname the referent's display name, if the referent is a f...
...ame: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameternames if the referent is a debuggee function, the names of the its parameters, as an array of strings. if the referent is not a debuggee function, or not a function at all, this is undefined. if the referent is a host function for which parameter names are not available, re
turn an array with one element per parameter, each of which is undefined. if the referent is a function proxy, re
turn an empty array. if the referent uses destructuring parameters, then the array's elements reflect the structure of the parameters. for example, if the referent is a function declared in this way: function f(a, [b, c], {d, e:f}) { ... } then this debugger.object instance's parame...
...s: if the referent is a wrapper, the result refers to the wrapper's global, not the wrapped object's global. the result refers to the global directly, not via a wrapper. hostannotations a javascript object providing further metadata about the referent, or null if none is available. the metadata object is in the same compartment as this debugger.object instance. the same metadata object is re
turned each time for a given debugger.object instance. a typical javascript embedding provides "host objects" to expose application-specific functionality to scripts. the hostannotations accessor consults the embedding for additional information about the referent that might be of interest to the debugger. the re
turned object's properties' meanings are up to the embedding. for example, a web browser...
...And 21 more matches
WebGL constants - Web APIs
all constants are of type glenum. standard webgl constants are installed on the webglrenderingcontext and webgl2renderingcontext objects, so that you use them as gl.constant_name: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl'); gl.getparameter(gl.line_width); some constants are also provided by webgl extensions. a list is provided below. var debuginfo = gl.getextension('webgl_debug_renderer_info'); var vendor = gl.getparameter(debuginfo.unmasked_vendor_webgl); the webgl tutorial has more information, examples, and resources on how to get started with webgl. ...
...roup of triangles. each vertex connects to the previous and the first vertex in the fan. blending modes constants passed to webglrenderingcontext.blendfunc() or webglrenderingcontext.blendfuncseparate() to specify the blending mode (for both, rbg and alpha, or separately). constant name value description zero 0 passed to blendfunc or blendfuncseparate to
turn off a component. one 1 passed to blendfunc or blendfuncseparate to
turn on a component. src_color 0x0300 passed to blendfunc or blendfuncseparate to multiply a component by the source elements color. one_minus_src_color 0x0301 passed to blendfunc or blendfuncseparate to multiply a component by one minus the source elements color. src_alpha ...
... blendequation or blendequationseparate to specify a subtraction blend function (source - destination). func_reverse_subtract 0x800b passed to blendequation or blendequationseparate to specify a reverse subtraction blend function (destination - source). getting gl parameter information constants passed to webglrenderingcontext.getparameter() to specify what information to re
turn. constant name value description blend_equation 0x8009 passed to getparameter to get the current rgb blend function. blend_equation_rgb 0x8009 passed to getparameter to get the current rgb blend function. same as blend_equation blend_equation_alpha 0x883d passed to getparameter to get the current alpha blend function. same as blend_...
...And 21 more matches
Element - Web APIs
e53" text-anchor="middle" alignment-baseline="middle">element</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent interface, node, and by extension that interface's parent, eventtarget. it implements the properties of parentnode, childnode, nondocumenttypechildnode, and animatable. ...
...ts: all;} properties inherits properties from its parent interface, node, and by extension that interface's parent, eventtarget. it implements the properties of parentnode, childnode, nondocumenttypechildnode, and animatable. element.attributes read only re
turns a namednodemap object containing the assigned attributes of the corresponding html element. element.classlist read only re
turns a domtokenlist containing the list of class attributes. element.classname is a domstring representing the class of the element. ...
...ntnode, childnode, nondocumenttypechildnode, and animatable. element.attributes read only re
turns a namednodemap object containing the assigned attributes of the corresponding html element. element.classlist read only re
turns a domtokenlist containing the list of class attributes. element.classname is a domstring representing the class of the element. element.clientheight read only re
turns a number representing the inner height of the element. element.clientleft read only re
turns a number representing the width of the left border of the element. element.clienttop read only re
turns a number representing the width of the top border of the element. element.clientwidth read only re
turns a number representing the inner width of the element. element.computedname read only re...
...And 20 more matches
Node - Web APIs
in addition, every kind of dom node is represented by an interface based on node. these include attr, characterdata (which text, comment, and cdatasection are all based on), processinginstruction, documenttype, notation, entity, and entityreference. in some cases, a particular feature of the base node interface may not apply to one of its child interfaces; in that case, the inheriting node may re
turn null or throw an exception, depending on circumstances. for example, attempting to add children to a node type that cannot have children will throw an exception. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0;...
...troke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">node</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties in addition to the properties below, node inherits properties from its parent, eventtarget. node.baseuriread only re
turns a domstring representing the base url of the document containing the node. node.baseuriobject read only (not available to web content.) the nsiuri object representing the base uri for the element. node.childnodesread only re
turns a live nodelist containing all the children of this node. nodelist being live means that if the children of the node change, the nodelist object is automaticall...
...f the document containing the node. node.baseuriobject read only (not available to web content.) the nsiuri object representing the base uri for the element. node.childnodesread only re
turns a live nodelist containing all the children of this node. nodelist being live means that if the children of the node change, the nodelist object is automatically updated. node.firstchildread only re
turns a node representing the first direct child node of the node, or null if the node has no child. ...
...And 20 more matches
RTCPeerConnection - Web APIs
="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">rtcpeerconnection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructorrtcpeerconnection() the rtcpeerconnection() constructor re
turns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.propertiesalso inherits properties from: eventtargetcantrickleicecandidatesthe read-only rtcpeerconnection property cantrickleicecandidates re
turns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.connectionstate the read-only connectionstate pro...
... remote peer.propertiesalso inherits properties from: eventtargetcantrickleicecandidatesthe read-only rtcpeerconnection property cantrickleicecandidates re
turns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.connectionstate the read-only connectionstate property of the rtcpeerconnection interface indicates the current state of the peer connection by re
turning one of the string values specified by the enum rtcpeerconnectionstate.currentlocaldescription read only the read-only property rtcpeerconnection.currentlocaldescription re
turns an rtcsessiondescription object describing the local end of the connection as it was most recently successfully negotiated since the last time the rtcpeerconnection finished negotiating and connecting to a remote peer.
...essfully negotiated since the last time the rtcpeerconnection finished negotiating and connecting to a remote peer. also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated.currentremotedescription read only the read-only property rtcpeerconnection.currentremotedescription re
turns an rtcsessiondescription object describing the remote end of the connection as it was most recently successfully negotiated since the last time the rtcpeerconnection finished negotiating and connecting to a remote peer. also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiate...
...And 20 more matches
Indexed collections - JavaScript
items, either of the following can be used: // this... let arr = new array(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number. otherwise, an array with a single element (the provided value) will be created. calling arr.length will re
turn arraylength, but the array doesn't contain any elements. a for...in loop will not find any property on the array. in addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object: let obj = {} // ... obj.prop = [element0, element1, ..., elementn] // or let obj = {prop: [element0, element1, ...., elementn]} if you wish to initia...
...operty(3.4)) // true you can also populate an array when you create it: let myarray = new array('hello', myvar, 3.14159) // or let myarray = ['mango', 'apple', 'orange'] understanding length at the implementation level, javascript's arrays actually store their elements as standard object properties, using the array index as the property name. the length property is special. it always re
turns the index of the last element plus one. (in the example below, 'dusty' is indexed at 30, so cats.length re
turns 30 + 1). remember, javascript array indexes are 0-based: they start at 0, not 1. this means that the length property will be one more than the highest index stored in the array: let cats = [] cats[30] = ['dusty'] console.log(cats.length) // 31 you can also assign to the length prop...
...n(element) { console.log(element) }) // first // second // undefined // fourth since javascript elements are saved as standard object properties, it is not advisable to iterate through javascript arrays using for...in loops, because normal elements and all enumerable properties will be listed. ...
...And 20 more matches
Array.prototype.reduce() - JavaScript
gle output value. 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 reducer function takes four arguments: accumulator (acc) current value (cur) current index (idx) source array (src) your reducer function's re
turned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value. syntax arr.reduce(callback( accumulator, currentvalue, [, index[, array]] )[, initialvalue]) parameters callback a function to execute on each element in the array (except for the first, if no initialvalue is supplied). ...
...ion throughout the array, and ultimately becomes the final, single resulting value. syntax arr.reduce(callback( accumulator, currentvalue, [, index[, array]] )[, initialvalue]) parameters callback a function to execute on each element in the array (except for the first, if no initialvalue is supplied). it takes four arguments: accumulator the accumulator accumulates callback's re
turn values. it is the accumulated value previously re
turned in the last invocation of the callback—or initialvalue, if it was supplied (see below). currentvalue the current element being processed in the array. index optional the index of the current element being processed in the array. starts from index 0 if an initialvalue is provided. otherwise, it starts from index 1. array optional ...
...tarts from index 1. array optional the array reduce() was called upon. initialvalue optional a value to use as the first argument to the first call of the callback. if no initialvalue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentvalue. calling reduce() on an empty array without an initialvalue will throw a typeerror. re
turn value the single value that results from the reduction. description the reduce() method executes the callback once for each assigned value present in the array, taking four arguments: accumulator currentvalue currentindex array the first time the callback is called, accumulator and currentvalue can be one of two values. if initialvalue is provided in the call to reduce(), then accumula...
...And 20 more matches
Tree View Details - Archive of obsolete content
it involves keeping track of which items have children and also which rows are open and closed. nesting level every row in the tree has a nesting level. the topmost rows are at level 0, the children of those rows are at level 1, their children at level 2 and so on. the tree will query the view for each row by calling its getlevel method to find out the level of that row. the view will need to re
turn 0 for the outermost rows and higher values for inner rows. the tree will use this information to determine the hierarchical structure of the rows. in addition to the getlevel method, there is a hasnextsibling function which, given a row, should re
turn true if there is another row afterwards at the same level. this function is used, specifically, to draw the nesting lines along the side of the tr...
...inner rows. the tree will use this information to determine the hierarchical structure of the rows. in addition to the getlevel method, there is a hasnextsibling function which, given a row, should re
turn true if there is another row afterwards at the same level. this function is used, specifically, to draw the nesting lines along the side of the tree. the getparentindex method is expected to re
turn the parent row of a given row, that is, the row before it with a lower nesting value. all of these methods must be implemented by the view for children to be handled properly. ...
... the iscontaineropen method is used to determine which items are opened and closed. the view is required to keep track of this. ...
...And 19 more matches
LiveConnect Overview - Archive of obsolete content
ng("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string. as a javaobject, mystring has access to the public instance methods of java.lang.string and its superclass, java.lang.object. these java methods are available in javascript as methods of the javaobject, and you can call them as follows: mystring.length(); // re
turns 11 static members can be called directly on the javaclass object. alert(java.lang.integer.max_value); //alerts 2147483647 the packages object if a java class is not part of the java, sun, or netscape packages, you access it with the packages object. for example, suppose the redwood corporation uses a java package called redwood to contain various java classes that it implements. to create an i...
...lang.string("hello world"); working with java arrays when any java method creates an array and you reference that array in javascript, you are working with a javaarray. for example, the following code creates the javaarray x with ten elements of type int: var x = java.lang.reflect.array.newinstance(java.lang.integer, 10); like the javascript array object, javaarray has a length property which re
turns the number of elements in the array. unlike array.length, javaarray.length is a read-only property, because the number of elements in a java array are fixed at the time of creation. package and class references simple references to java packages and classes from javascript create the javapackage and javaclass objects. in the earlier example about the redwood corporation, for example, the referen...
...d to assign the name of a java class to a variable called theclass. the forname method throws an exception if the value you pass it does not evaluate to the name of a java class. ...
...And 19 more matches
How to embed the JavaScript engine
of the global object. */ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, }; int main(int argc, const char *argv[]) { jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) re
turn 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) re
turn 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(c...
... { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...*/ static jsclass global_clas...
...And 19 more matches
HTMLTextAreaElement - Web APIs
ect x="301" y="65" width="190" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="396" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmltextareaelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties accesskey string: re
turns / sets the element's accesskey attribute. autocapitalize string: re
turns / sets the element's capitalization behavior for user input. valid values are: none, off, characters, words, sentences. autocomplete autofocus boolean: re
turns / sets the element's autofocus attribute, indicating that the control should have input focus when the page loads c...
...ccesskey attribute. autocapitalize string: re
turns / sets the element's capitalization behavior for user input. valid values are: none, off, characters, words, sentences. autocomplete autofocus boolean: re
turns / sets the element's autofocus attribute, indicating that the control should have input focus when the page loads cols unsigned long: re
turns / sets the element's cols attribute, indicating the visible width of the text area. defaultvalue string: re
turns / sets the control's default value, which behaves like the node.textcontent property. ...
...ns / sets the element's autofocus attribute, indicating that the control should have input focus when the page loads cols unsigned long: re
turns / sets the element's cols attribute, indicating the visible width of the text area. defaultvalue string: re
turns / sets the control's default value, which behaves like the node.textcontent property. disabled boolean: re
turns / sets the element's disabled attribute, indicating that the control is not available for interaction. form read only object: re
turns a reference to the parent form element. ...
...And 19 more matches
Using Service Workers - Web APIs
apps. setting up to play with service workers many service workers features are now enabled by default in newer versions of supporting browsers. if however you find that demo code is not working in your installed versions, you might need to enable a pref: firefox nightly: go to about:config and set dom.serviceworkers.enabled to true; restart browser. chrome canary: go to chrome://flags and
turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default in chrome.) opera: go to opera://flags and enable support for serviceworker; restart browser. microsoft edge: go to about:flags and tick enable service workers; restart browser. you’ll also need to serve your code via https — service workers are restricted to running across https for...
...o 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 re
turns 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 myfunctio...
...e 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 re
turn value before any more of the code can execute. in the second example, myfunction() re
turns a promise for value, then the rest of the code can carry on running. when the promise resolves, the code inside then will be run, asynchronously. 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? thi...
...And 19 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
the setinterval() method, offered on the window and worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. it re
turns an interval id which uniquely identifies the interval, so you can remove it later by calling clearinterval(). this method is defined by the windoworworkerglobalscope mixin. syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no re
turn value is expected. code an optional syntax allows you to include a string instead of a function, which is compiled and executed every ...
...ge of delay values. arg1, ..., argn optional additional arguments which are passed through to the function specified by func once the timer expires. note: passing additional arguments to setinterval() in the first syntax does not work in internet explorer 9 and earlier. if you want to enable this functionality on that browser, you must use a polyfill (see the callback arguments section). re
turn value the re
turned intervalid is a numeric, non-zero value which identifies the timer created by the call to setinterval(); this value can be passed to windoworworkerglobalscope.clearinterval() to cancel the timeout. it may be helpful to be aware that setinterval() and settimeout() share the same pool of ids, and that clearinterval() and cleartimeout() can technically be used interchangeably. f...
...amap[npos]++ : bexit = true; if (beraseandstop && (orel.ref.nodetype - 1 | 1) === 3 && orel.ref.nodevalue) { bexit = true; ocurrent = orel.ref; spa...
...And 19 more matches
async function - JavaScript
e interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax async function name([param[, param[, ...param]]]) { statements } parameters name the function’s name. param the name of an argument to be passed to the function. statements the statements comprising the body of the function. the await mechanism may be used. re
turn value a promise which will be resolved with the value re
turned by the async function, or rejected with an exception thrown from, or uncaught within, the async function. description async functions can contain zero or more await expressions. await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynch...
... an exception thrown from, or uncaught within, the async function. description async functions can contain zero or more await expressions. await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected. the resolved value of the promise is treated as the re
turn value of the await expression. use of async / await enables the use of ordinary try / catch blocks around asynchronous code. the await keyword is only valid inside async functions. if you use it outside of an async function's body, you will get a syntaxerror. the purpose of async/await is to simplify the syntax necessary to consume promise-based apis. the behavior of async/await is similar t...
... use of ordinary try / catch blocks around asynchronous code. the await keyword is only valid inside async functions. if you use it outside of an async function's body, you will get a syntaxerror. the purpose of async/await is to simplify the syntax necessary to consume promise-based apis. the behavior of async/await is similar to combining generators and promises. async functions always re
turn a promise. if the re
turn value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. for example, the following: async function foo() { re
turn 1 } ...is equivalent to: function foo() { re
turn promise.resolve(1) } the body of an async function can be thought of as being split by zero or more await expressions. top-level code, up to and including...
...And 19 more matches
nsIMsgIncomingServer
nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
...simsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
...chema for the local mail store, such as "mailbox", "imap", or "news" used to construct uris. read only. loginatstartup boolean logonfallback boolean maxmessagesize long offlinesupportlevel long password acstring passwordpromptrequired boolean if the password for the server is available either via authentication in the current session or from password manager stored entries, re
turn false. otherwise, re
turn true. if password is obtained from password manager, set the password member variable. read only. performingbiff boolean port long prettyname astring pretty name - should be "userid on hostname" if the pref is not set. realhostname acstring real hostname of the server (if server name is changed it is stored here) realusername acstring real username of the se...
...And 18 more matches
Navigator - Web APIs
s. a navigator object can be retrieved using the read-only window.navigator property. properties doesn't inherit any properties, but implements those defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia. ...
...roperties doesn't inherit any properties, but implements those defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia. standard navigatorid.appcodename read only re
turns the internal "code" name of the current browser. do not rely on this property to re
turn the correct value. ...
...ose defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia. standard navigatorid.appcodename read only re
turns the internal "code" name of the current browser. do not rely on this property to re
turn the correct value. navigatorid.appname read only re
turns a domstring with the official name of the browser. do not rely on this property to re
turn the correct value. navigatorid.appversion read only re
turns the version of the browser as a domstring. do not rely on this property to re
turn the correct value. navigator.battery read only re
turns a batterymanager object you can use to get information about the battery charging status. navigator.con...
...And 18 more matches
String - JavaScript
ns. see "string primitives and string objects" below. string literals can be specified using single or double quotes, which are treated identically, or using the backtick character `. this last form specifies a template literal: with this form you can interpolate expressions. character access there are two ways to access an individual character in a string. the first is the charat() method: re
turn 'cat'.charat(1) // re
turns "a" the other way (introduced in ecmascript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index: re
turn 'cat'[1] // re
turns "a" when using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. the properties involved are neither writable nor conf...
... } else { console.log(a + ' and ' + b + ' are equal.') } a similar result can be achieved using the localecompare() method inherited by string instances. note that a == b compares the strings in a and b for being equal in the usual case-sensitive way. if you wish to compare without regard to upper or lower case characters, use a function similar to this: function isequal(str1, str2) { re
turn str1.touppercase() === str2.touppercase() } // isequal upper case is used instead of lower case in this function, due to problems with certain utf-8 character conversions. string primitives and string objects note that javascript distinguishes between string objects and primitive string values. (the same is true of boolean and numbers.) string literals (denoted by double or single quotes) an...
...rcase() === str2.touppercase() } // isequal upper case is used instead of lower case in this function, due to problems with certain utf-8 character conversions. string primitives and string objects note that javascript distinguishes between string objects and primitive string values. (the same is true of boolean and numbers.) string literals (denoted by double or single quotes) and strings re
turned from string calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. javascript automatically converts primitives to string objects, so that it's possible to use string object methods for primitive strings. in contexts where a method is to be invoked on a primitive string or a property lookup occurs, javascript will automatically wrap the string ...
...And 18 more matches
Making asynchronous programming easier with async and await - Learn web development
c 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. ...
... 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 console: function hello() { re
turn "hello" }; hello(); the function re
turns "hello" — nothing special, right? but what if we
turn this into an async function? try the following: async function hello() { re
turn "hello" }; hello(); ah. invoking the function now re
turns a promise. this is one of the traits of async functions — their re
turn values are guaranteed to be converted to promises. you can also create an async functi...
...hing special, right? but what if we
turn this into an async function? ...
...And 17 more matches
How to implement a custom autocomplete search component
er and slightly simplified mechanism that is used in "toolkit" applications such as firefox and xulrunner. thunderbird 2.x and seamonkey 1.1.x support the toolkit interfaces, although they do not use the same autocomplete widget. to use autocomplete with a xul textbox, all you need to do is set some attributes: <textbox type="autocomplete" autocompletesearch="history"/> the type="autocomplete"
turns on the autocomplete mechanism and the autocompletesearch="history" sets the source for the autocomplete. there are more options and features, see xul:textbox_(firefox_autocomplete) for more details. the toolkit mechanism has built-in support for several autocomplete sources, including: history: search the browser's url history (firefox: 1.0+; seamonkey: 1.1+) form-history: search the values t...
...t, otherwise you might have problems if your component gets installed along another component derived from those same examples. that can happen! so, get a uuid from http://www.famkruithof.net/uuid/uuidgen, for example, and paste it in. basic example for gecko 2.0 and up (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this example is your first best try because: it has no specific logic (it just re
turns a dummy array of choices) it doesn't care about compatibility with older gecko versions first copy the following javascript code into a file named basic_autocomplete.js into the components directory (or whatever components folder is appropriate in your case): warning: the uuid used below in chrome.manifest and assigned to class_id must be changed before use. const ci = components.interfa...
...mments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._errordescription = errordescription; this._results = results; this._comments = comments; } providerautocompleteresult.prototype = { _searchstring: "", _searchresult: 0, _defaultindex: 0, _errordescription: "", _results: [], _comments: [], /** * @re
turn {string} the original search string */ get searchstring() { re
turn this._searchstring; }, /** * @re
turn {number} the result code of this result object, either: * result_ignored (invalid searchstring) * result_failure (failure) * result_nomatch (no matches found) * result_success (matches found) */ get searchresult() { re
turn this._searchresult...
...And 17 more matches
CustomizableUI.jsm
h it, until the area has been registered. registermenupanel() register the menu panel node. this method should not be called by anyone apart from the built-in panelui. parameters apanel the panel dom node being registered. unregisterarea() unregister a customizable area. the inverse of registerarea. unregistering an area will remove all the (removable) widgets in the area, which will re
turn to the panel, and destroy all other traces of the area within customizableui. note that this means the contents of the area's dom nodes will be moved to the panel or removed, but the area's dom node(s) themselves will stay. furthermore, by default the placements of the area will be kept in the saved state (!) and restored if you re-register the area at a later point. this is useful for add-ons t...
...rcedirty=true, we will flush to the prefs file. parameters aforcedirty force customizableui to flush to the prefs file when all batch updates have finished. createwidget() create a widget. to create a widget, you should pass an object with its desired properties. for a list of supported properties, see api-provided widgets. parameters aproperties the specification for the widget re
turn value a wrapper around the created widget. note: if your extension is compatible with versions of firefox below 29, i.e. before customizableui was introduced, then you have to make sure that in case of running on newer browsers, xul overlay does not contain description of the button that you are creating with createwidget() method. otherwise, conflicting static xul overlay button and dynamic cu...
...es. however, it will keep the widget in the placements for whatever area it was in at the time. you can remove it from there yourself by calling customizableui.removewidgetfromarea(awidgetid). parameters awidgetid the id of the widget to destroy getwidget() get a wrapper object with information about the widget. parameters awidgetid the id of the widget whose information you need re
turn value a wrapper around the widget as described above, or null if the widget is known not to exist (any more). nb: non-null re
turn is no guarantee the widget exists because we cannot know in advance if an xul widget exists or not. getunusedwidgets() get an array of widget wrappers for all the widgets which are currently not in any area (so which are in the palette). parameters awindowpalett...
...And 17 more matches
Examples
n your temporary directory."); } else { throw new error("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a promise re
turned by a function (verbose) this example uses a verbose syntax, showing all the involved promises. components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directo...
...ry directory."); } }); // unexpected errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(null, components.utils.reporterror); in this case, if the file existence check succeeds, the onfulfill callback is invoked. when the callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not re
turn any value. when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the re
turn value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this state will propagate to newpomise, and components.utils.reporterror will report all the details of the excep...
..., nothing happens, because no fulfillment callback is specified and the re
turn value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this state will propagate to newpomise, and components.utils.reporterror will report all the details of the exception to the console. ...
...And 17 more matches
Index
t as a personal certificate. (a personal certificate is a certificate for which the private key is in possession, and which could be used for signing data or for decrypting data.) a unique nickname can/should be assigned to the certificate at the time of import, which can later be used to easily identify and retrieve it. it's important to note that nss requires strict cleanup for all handles re
turned by nss. the application should always call the appropriate dereference (destroy) functions once a handle is no longer needed. this is particularly important for applications that might need to close a database and reinitialize nss using a different one, without restarting. such an operation might fail at runtime if data elements are still being referenced. in addition to the freebl, softoken...
... use your application code that supports proxies. when using hashing, encryption, and decryption functions, it is possible to stream data (as opposed to operating on a large buffer). create a context handle while providing all the parameters required for the operation, then call an “update” function multiple times to pass subsets of the input to nss. the data will be processed and either re
turned directly or sent to a callback function registered in the context. when done, you call a finalization function that will flush out any pending data and free the resources. this line is a placeholder for future sections that should explain how libpkix works and is designed. if you want to work with nss, it's often helpful to use the command line utilities that are provided by the nss devel...
...def struct { const char *hashname; secoidtag oid; } nametagpair; /* the hash algorithms supported */ static const nametagpair hash_names[] = { { "md2", sec_oid_md2 }, { "md5", sec_oid_md5 }, { "sha1", sec_oid_sha1 }, { "sha256", sec_oid_sha256 }, { "sha384", sec_oid_sha384 }, { "sha512", sec_oid_sha512 } }; /* maps a hash name to a secoidtag. ...
...And 17 more matches
Using the CSS Typed Object Model - Web APIs
ties — that are impacting an element. let's see how this works by creating our first example, which explores computedstylemap(). we start with some html: a paragraph with a link, as well as a definition list to which we will add all the css property / value pairs. <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and re
turn back a definition list of all the default css property values impacting the link using computedstylemap(). // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const defaultcomputedstyles = myelement.computedstylemap(); // iterat...
...we iterate through the style map, creating a <dt> and <dd> for each property and value respectively. in browsers that support computedstylemap(), you'll see a list of all the css properties and values. in other browsers, you'll just see a link. did you realize how many defaul...
...the link has inherited font-weight: bold; from the paragraph's styles, listing it as font-weight: 700. custom properties, like our --color: red , are properties. as such, they are accessible via get(). you'll note that custom properties retain the value as written in the stylesheet, whereas computed styles will be listed as the computed value — color was listed as an rgb() val...
...And 17 more matches
NSS PKCS11 Functions
has the following parameters: modulespec is a pkcs #11 modulespec. parent is the moduledb that presented this module spec. for applications this value should be null. recurse is a boolean indicates whether or not the module should also launch additional pkcs #11 modules. this is only applicable if the loaded module is actually a moduledb rather than a pkcs #11 module (see pkcs11_module_specs). re
turns the function re
turns one of these values: if successful, a pointer to a secmodmodule. caller owns the reference if unsuccessful, null. description secmod_loadusermodule loads a new pkcs #11 module into nss and connects it to the current nss trust infrastructure. once the the module has been successfully loaded, other nss calls will use it in the normal course of searching. modulespec specifies...
...pecified in module specs used by secmod_loadusermodule. module will continue to function in the nss infrastructure until unloaded with secmod_unloadusermodule. secmod_unloadusermodule unload a pkcs #11 module. syntax #include "secmod.h" extern secstatus secmod_unloadusermodule(secmodmodule *module); parameters this function has the following parameters: module is the module to be unloaded. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. description secmod_unloadusermodule detaches a module from the nss trust domain and unloads it. the module should have previously been loaded by secmod_loadusermodule. secmod_closeuserdb close an already opened user database. note: the database must be in the internal token, and must be one create...
...ith secmod_openuserdb(). once the database is closed, the slot will remain as an empty slot until it's used again with secmod_openuserdb(). syntax #include <pk11pub.h> secstatus secmod_closeuserdb(pk11slotinfo *slot) parameters this function has the following parameter: slot a pointer to a slot info structure. this slot must a a slot created by secmod_openuserdb() at some point in the past. re
turns the function re
turns one of these values: if successful, secsuccess). if unsuccessful, secfailure. secmod_openuserdb open a new database using the softoken. syntax #include "pk11pub.h" pk11slotinfo *secmod_openuserdb(const char *modulespec) parameters this function has the following parameters: modulespec is the same data that you would pass to softoken at initialization time under the 'to...
...And 16 more matches
HTMLMediaElement - Web APIs
ally playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. see the autoplay guide for media and web audio apis for more information. keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working. htmlmediaelement.buffered read only re
turns a timeranges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed. htmlmediaelement.controller is a mediacontroller object that represents the media controller assigned to the element, or null if none is assigned. htmlmediaelement.controls is a boolean that reflects the controls html attribute, indicating ...
... buffered property is accessed. htmlmediaelement.controller is a mediacontroller object that represents the media controller assigned to the element, or null if none is assigned. htmlmediaelement.controls is a boolean that reflects the controls html attribute, indicating whether user interface items for controlling the resource should be displayed. ...
... htmlmediaelement.currenttime a double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. setting this value seeks the media to the new time. ...
...And 16 more matches
Starting up and shutting down a WebXR session - Web APIs
will learn how to do these things in this article. accessing the webxr api your app's access to the webxr api begins with the xrsystem object. this object represents the overall webxr device suite available to you through the hardware and drivers available on the user's equipment. there is a global xrsystem object available for use by your document through the the navigator property xr, which re
turns the xrsystem object if suitable xr hardware is available for your use given the hardware available and your document's environment. thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available. webxr availability as a new and still in development api, webxr support is limited to specific devices and b...
...fill, provided by the immersive web working group that's in charge of the webxr standardization process. the polyfill brings support for webxr to browsers that don't have native webxr support, and smooths out the inconsistencies among implementations in the browsers that do have it, so it can sometimes also be useful even if webxr is natively available. here we define a getxr() function, which re
turns the xrsystem object after optionally installing the polyfill, assuming that the polyfill has been included or loaded using a prior <script> tag. let webxrpolyfill = null; function getxr(usepolyfill) { let tempxr; let temppoly; switch(usepolyfill) { case "if-needed": if (!navigator.xr) { webxrpolyfill = new webxrpolyfill(); } tempxr = navigator.xr; bre...
...the global variable webxrpolyfill is used only to retain a reference to the...
...And 16 more matches
Proxy - JavaScript
handler functions are sometimes called traps, presumably because they trap calls to the target object. the very simple trap in handler2 above redefines all property accessors: console.log(proxy2.message1); // worl...
...andler2 above redefines all property accessors: console.log(proxy2.message1); // world console.log(proxy2.message2); // world with the help of the reflect class we can give some accessors the original behavior and redefine others: const target = { message1: "hello", message2: "everyone" }; const handler3 = { get: function (target, prop, receiver) { if (prop === "message2") { re
turn "world"; } re
turn reflect.get(...arguments); }, }; const proxy3 = new proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world constructor proxy() creates a new proxy object. static methods proxy.revocable() creates a revocable proxy object. examples basic example in this simple example, the number 37 gets re
turned as the de...
... hello console.log(proxy3.message2); // world constructor proxy() creates a new proxy object. static methods proxy.revocable() creates a revocable proxy object. examples basic example in this simple example, the number 37 gets re
turned as the default value when the property name is not in the object. it is using the get handler. const handler = { get: function(obj, prop) { re
turn prop in obj ? obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it. const target = {}; const p = new proxy(target, {})...
...And 16 more matches
nsIHTMLEditor
roperty(in nsiatom aproperty, in astring aattribute, in astring avalue); void setparagraphformat(in astring aparagraphformat); void updatebaseurl(); attributes attribute type description iscssenabled boolean a boolean which is true is the htmleditor has been instantiated with css knowledge and if the css pref is currently checked. re
turninparagraphcreatesnewparagraph boolean a boolean indicating if a re
turn key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret. constants constant value description eleft 0 ecenter 1 eright 2 ejustify 3 methods adddefaultproperty() registers a default style p...
... for insertion override. void addinsertionlistener( in nsicontentfilter infilter ); parameters infilter function which callers want called during insertion. align() document me! void align( in astring aalign ); parameters aalign breakisvisible() checks whether a br node is visible to the user. boolean breakisvisible( in nsidomnode anode ); parameters anode re
turn value candrag() decides if a drag should be started (for example, based on the current selection and mousepoint). boolean candrag( in nsidomevent aevent ); parameters aevent re
turn value checkselectionstateforanonymousbuttons() checks if the anonymous nodes created by the html editor have to be refreshed or hidden depending on a possible new state of the selection. void chec...
...if aiscreatedhidden is true, the class "hidden" is added to the created element. ...
...And 15 more matches
eval() - JavaScript
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 eval(string) parameters string a string representing a javascript expression, statement, or sequence of statements. the expression can include variables and properties of existing objects. re
turn value the completion value of evaluating the given code. if the completion value is empty, undefined is re
turned. description eval() is a function property of the global object. the argument of the eval() function is a string. if the string represents an expression, eval() evaluates the expression. if the argument represents one or more javascript statements, eval() evaluates the statements. ...
... if you construct an arithmetic expression as a string, you can use eval() to evaluate it at a later time. for example, suppose you have a variable x. you can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script. if the argument of eval() is not a string, eval() re
turns the argument unchanged. in the following example, the string constructor is specified and eval() re
turns a string object rather than evaluating the string. eval(new string('2 + 2')); // re
turns a string object containing "2 + 2" eval('2 + 2'); // re
turns 4 you can work around this limitation in a generic fashion by using tostring(). var expression = new string('2 + 2'); eval(expr...
...lowing example, the string constructor is specified and eval() re
turns a string object rather than evaluating the string. eval(new string('2 + 2')); // re
turns a string object containing "2 + 2" eval('2 + 2'); // re
turns 4 you can work around this limitation in a generic fashion by using tostring(). var expression = new string('2 + 2'); eval(expression.tostring()); // re
turns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope. this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called. function test() { var x = 2, y =...
...And 15 more matches
Understanding WebAssembly text format - WebAssembly
y_magic 0000004: 0100 0000 ; wasm_binary_version adding functionality to your module ok, that’s not very interesting, let’s add some executable code to this module. all code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <body> ) the signature declares what the function takes (parameters) and re
turns (re
turn values). the locals are like vars in javascript, but with explicit types declared. the body is just a linear list of low-level instructions. so this is similar to functions in other languages, even if it looks different because it is an s-expression. signatures and parameters the signature is a sequence of parameter type declarations followed by a list of re
turn type declarations. ...
... the body is just a linear list of low-level instructions. so this is similar to functions in other languages, even if it looks different because it is an s-expression. signatures and parameters the signature is a sequence of parameter type declarations followed by a list of re
turn type declarations. it is worth noting here that: the absence of a (result) means the function doesn’t re
turn anything. in the current iteration, there can be at most 1 re
turn type, but later this will be relaxed to any number. each parameter has a type explicitly declared; wasm currently has four available number types (plus reference types; see the reference types) section below): i32: 32-bit integer i64: 64-bit integer f32: 32-bit float f64: 64-bit float a single parameter is written (par...
...) after the signature, locals are listed with their type, for example (local i32). ...
...And 15 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is created by setting the type attribute of a textbox to autocomplete. it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type. the autocomplete functionality is handled through one of more session objects, each of which can re
turn a set of results given the current value of the textbox. the sessions can be set using the searchsessions attribute or by calling the addsession method. attributes accesskey, alwaysopenpopup, autocompletesearch, autocompletesearchparam, autofill, autofillaftermatch, autofill, completedefaultindex, crop, disableautocomplete, disableautocomplete, disabled, disablehistory, enablehisto...
... maxlength type: integer the maximum number of characters that the textbox allows to be entered. maxrows type: integer the number of rows to show in the results list at a time. a scrollbar will appear so the user can scroll through the remaining items. minresultsforpopup obsolete since gecko 1.9.1 type: integer the minimum number of results that must be re
turned for the popup to be displayed. the default value is 1. a zero value will always open the popup unless the textbox is empty. this can be used to display additional items that are not autocomplete results. as of gecko 1.9.1, this attribute is now always specified in lower case. minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number...
...layed. the default value is 1. a zero value will always open the popup unless the textbox is empty. this can be used to display additional items that are not autocomplete results. as of gecko 1.9.1, this attribute is now always specified in lower case. minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be re
turned for the popup to be displayed. the default value is 1. new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup. this can be used to display additional items that are not autocomplete results. nomatch type: boolean this attribute will be set to true if the last search resulted in no matches. overview an onchange attribute is an event listener to the obje...
...And 14 more matches
Gecko info for Windows accessibility vendors
event_system_alert. msaa tree vs. dom tree - what's the relation? the msaa tree and the dom tree are parallel structures, although the msaa tree is a subset of the dom tree. queryservice() can be used to switch between the interfaces (iaccessible, isimpledomdocument, isimpledomnode and isimpledomtext). if there is no msaa node for a dom node, or vice-versa, queryservice() will re
turn null. anything that is focusable or conveys important information about the structure of the document is exposed in the msaa tree of iaccessibles. windows applications based on the gecko layout engine gecko is a rendering engine that mozilla, netscape and other new browsers use. gecko can render a variety of content, not just html and supports key web standards such as cascading style ...
...leobjectfromevent(), or on the root accessible of a window with any iaccessible method that takes a variant, such as get_accchild(). because screen readers usually cache an entire document's worth of data, it can be extremely useful for them to receive a child id that helps them correlate back to a known object. we provide support for this technique via isimpledomnode::get_nodeinfo(), which re
turns a uniqueid for any iaccessible that can be cached in the internal model. when an event is received, the negative childid should match one of these cached uniqueid's, if the entire document has been stored and kept current. keeping an internal cache current means getting new subtrees of iaccessibles whenever an event_reorder is received, indicating important changes have invalidated part of the m...
...otes about what we support intentional differences with internet explorer for the most part, where we support an msaa feature, we have tried to duplicate internet explorer's use of it. please let us know if you find any differences not listed here: accessible relations are supported the accnavigate() method can be used with new constants defined for gecko. the results are always re
turned via vt_dispatch. enum { navrelation_label_for = 0x1002 }; enum { navrelation_description_for = 0x100f }; these two relations can be used on object to determine what form control is being labelled or desribed. enum { navrelation_labelled_by = 0x1003 }; enum { navrelation_described_by = 0x100e }; these two relations are they inverse; they can be used on form controls. if the for...
...And 14 more matches
Utilities for nss samples
en); pr_fprintf(out, "%s", b64data); pr_fprintf(out, "\n"); if (b64data) { port_free(b64data); } } /* * printashex */ void printashex(prfiledesc* out, const unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); re
turn; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } ...
...mn += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { re
turn -1; } if (c <= '9' && c >= '0') { re
turn c - '0'; } if (c <= 'f' && c >= 'a') { re
turn c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { re
turn c - 'a' + 0xa; } re
turn -1; } /* * hextobuf */ int hextobuf(unsigned char *instring, secitem *outbuf, prbool ishexdata) { int len = strlen((const char *)instring); int outlen = len+1/2; int...
...& c >= 'a') { re
turn c - 'a' + 0xa; } re
turn -1; } /* * hextobuf */ int hextobuf(unsigned char *instring, secitem *outbuf, prbool ishexdata) { int len = strlen((const char *)instring); int outlen = len+1/2; int truelen = 0; int digit1, digit2; outbuf->data = ishexdata ? ...
...And 14 more matches
nss tech note5
padding is the application's responsibility. you can find a list of cipher mechanisms in security/nss/lib/softoken/pkcs11.c - grep for ckf_en_de_. ...
...lib/softoken/pkcs11.c - grep for ckf_en_de_. ...
...iv is relevant only wh...
...And 14 more matches
nsITreeView
r 1 indropbefore 0 obsolete since gecko 1.8 indropon 1 obsolete since gecko 1.8 indropafter 2 obsolete since gecko 1.8 methods candrop() methods used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always re
turn false when the orientation is not drop_on. note: drop_on will only be passed to candrop() if the item is a container; see iscontainer(). boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfer ); parameters index the index of the row. orientation the position around the given row. defined in constants. datatransfer this parameter, added in gecko ...
...a container; see iscontainer(). boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfer ); parameters index the index of the row. orientation the position around the given row. defined in constants. datatransfer this parameter, added in gecko 1.9.2, provides the data being dragged, so that it can be examined to determine if a drop is possible. re
turn value true if a drop is allowed at the current location; otherwise false. candropbeforeafter() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always ret...
...drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always re
turn false from candropbeforeafter(). boolean candropbeforeafter( in long index, in boolean before ); parameters index the index of the item. before true to test drop before. false to test drop after. re
turn value true if a drop event can occur. otherwise false. ...
...And 14 more matches
nsIVariant
g getaswstring(); native code only! void getaswstringwithsize(out pruint32 size, [size_is(size), retval] out wstring str); native code only! attributes attribute type description datatype pruint16 read only. native code only! methods native code only!getasacstring acstring getasacstring(); parameters none. re
turn value the value is converted to an 8-bit string in the iso-8859-1 character set. if the value was utf16 then the high bits are lost. if the value was utf8 then it is converted to utf16 and the high bits are discarded. arrays and interface pointers cannot be converted to a string. violates the xpcom interface guidelines getasarray() nsresult getasarray( out pruint16 type, out nsiid iid, ...
...iid, out pruint32 count, out voidptr ptr ); parameters type the type of the array elements. iid the iid of the array elements, if they are interface pointers. count the number of elements in the array. ptr a copy of the array of underlying elements. (reference counted elements are not cloned, but their reference count is increased.) re
turn value native code only!getasastring astring getasastring(); parameters none. re
turn value the internal value is converted to a utf16 string. arrays and interface pointers cannot be converted to a string. native code only!getasautf8string autf8string getasautf8string(); parameters none. re
turn value the internal value is converted to a utf8 string. an iso-8859-1 string is widened to a utf16 str...
...g. arrays and interface pointers cannot be converted to a string. native code only!getasautf8string autf8string getasautf8string(); parameters none. re
turn value the internal value is converted to a utf8 string. an iso-8859-1 string is widened to a utf16 string first. arrays and interface pointers cannot be converted to a string. native code only!getasbool prbool getasbool(); parameters none. re
turn value if possible, the internal value is converted to a double, which is then compared to zero. native code only!getaschar char getaschar(); parameters none. ...
...And 14 more matches
Using the CSS Painting API - Web APIs
the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerpaint('headerhighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. ...
... we have then used the paint() function to paint to our canvas. a paint() function can take three arguments. here we have provided one argument: the rendering context (we'll look at more in due course), often refered to by the variable name ctx. ...
...s proportional to the size of the element's box model size. in the above image, the background proportional to the size of the element. the 3rd example has width: 50%; set on the block level element, making the element narrower and therefore the background image narrower. ...
...And 14 more matches
Element.classList - Web APIs
a domtokenlist with the length property equal to 0. the domtokenlist itself is read-only, although you can modify it using the add() and remove() methods. ...
...a domtokenlist with the length property equal to 0. the domtokenlist itself is read-only, although you can modify it using the add() and remove() methods. ...
...a domtokenlist with the length property equal to 0. ...
...And 14 more matches
Using IndexedDB - Web APIs
nd such feature will not be available."); } opening a database we start the whole process like this: // let 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 re
turns 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 - re
turn 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...
...he transaction can either be in readonly or readwrite mode. to make changes to an existing object store, the transaction must be in readwrite mode. you open such transactions with idbdatabase.transaction. the method accepts two parameters: the storenames (the scope, defined as an array of object stores that you want to access) and the mode (readonly or readwrite) for the transaction. the method re
turns a transaction object containing the idbindex.objectstore method, which you can use to access your object store. by default, where no mode is specified, transactions open in readonly mode. note: as of firefox 40, indexeddb transactions have relaxed durability guarantees to increase performance (see bug 1112702.) previously in a readwrite transaction idbtransaction.oncomplete was fired only when...
...ion = db.transaction(["customers"], "readwrite"); // note: older experimental implementations use the deprecated constant idbtransaction.read_write instead of "readwrite". // in case you want to support such an implementation, you can write: // var transaction = db.transaction(["customers"], idbtransaction.read_write); the transaction() function takes two arguments (though one is optional) and re
turns a transaction object. the first argument is a list of object stores that the transaction will span. you can pass an empty array if you want the transaction to span all object stores, but don't do it because the spec says an empty array should generate an invalidaccesserror. if you don't specify anything for the second argument, you get a read-only transaction. since you want to write to it here ...
...And 14 more matches
SubtleCrypto.wrapKey() - Web APIs
ect specifying the algorithm to be used to encrypt the exported key, and any required extra parameters: to use rsa-oaep, pass an rsaoaepparams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. to use aes-kw, pass the string "aes-kw", or an object of the form { "name": "aes-kw }. re
turn value result is a promise that fulfills with an arraybuffer containing the encrypted exported key. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the wrapping key is not a key for the requested wrap algorithm. notsupported raised when trying to use an algorithm that is either unknown or isn't suitable for encrypti...
...e wraps an aes key. it uses "raw" as the export format and aes-kw, with a password-derived key, to encrypt it. see the complete code on github. let salt; /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. ...
... */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); re
turn window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2. */ function getkey(keymaterial, salt) { re
turn 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 =...
...And 14 more matches
WebGLRenderingContext - Web APIs
canvas. webglrenderingcontext.drawingbufferwidth the read-only width of the current drawing buffer. should match the width of the canvas element associated with this context. webglrenderingcontext.drawingbufferheight the read-only height of the current drawing buffer. should match the height of the canvas element associated with this context. webglrenderingcontext.getcontextattributes() re
turns a webglcontextattributes object that contains the actual context parameters. might re
turn null, if the context is lost. webglrenderingcontext.iscontextlost() re
turns true if the context is lost, otherwise re
turns false. webglrenderingcontext.makexrcompatible() ensures the context is compatible with the user's xr hardware, re-creating the context if necessary with a new configuration to do so...
...lized device coordinates to window or viewport coordinates. webglrenderingcontext.disable() disables specific webgl capabilities for this context. webglrenderingcontext.enable() enables specific webgl capabilities for this context. webglrenderingcontext.frontface() specifies whether polygons are front- or back-facing by setting a winding orientation. webglrenderingcontext.getparameter() re
turns a value for the passed parameter name. webglrenderingcontext.geterror() re
turns error information. webglrenderingcontext.hint() specifies hints for certain behaviors. the interpretation of these hints depend on the implementation. webglrenderingcontext.isenabled() tests whether a specific webgl capability is enabled or not for this context. webglrenderingcontext.linewidth() sets the line...
...context.bindbuffer() binds a webglbuffer object to a given target. webglrenderingcontext.bufferdata() updates buffer data. webglrenderingcontext.buffersubdata() updates buffer data starting at a passed offset. webglrenderingcontext.createbuffer() creates a webglbuffer object. webglrenderingcontext.deletebuffer() deletes a webglbuffer object. webglrenderingcontext.getbufferparameter() re
turns information about the buffer. webglrenderingcontext.isbuffer() re
turns a boolean indicating if the passed buffer is valid. framebuffers webglrenderingcontext.bindframebuffer() binds a webglframebuffer object to a given target. webglrenderingcontext.checkframebufferstatus() re
turns the status of the framebuffer. webglrenderingcontext.createframebuffer() creates a webglframebuffer obje...
...And 14 more matches
Arrow function expressions - JavaScript
is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. arrow function expressions are ill suited as methods, and they cannot be used as constructors. ...
...am1, param2, …, paramn) => expression // equivalent to: => { re
turn expression; } // parentheses are optional when there's only one parameter name: (singleparam) => { statements } singleparam => { statements } // the parameter list for a function with no parameters should be written with a pair of parentheses. ...
...ported var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6 description see also "es6 in depth: arrow functions" on hacks.mozilla.org. two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword. ...
...And 14 more matches
Date - JavaScript
ngdom.) the user's device provides the local time. in addition to methods to read and alter individual components of the local date and time (such as getday() and sethours()), there are also versions of the same methods that read and manipulate the date and time using utc (such as getutcday() and setutchours()). constructor date() creates a new date object. static methods date.now() re
turns the numeric value corresponding to the current time—the number of milliseconds elapsed since january 1, 1970 00:00:00 utc, with leap seconds ignored. date.parse() parses a string representation of a date and re
turns the number of milliseconds since 1 january, 1970, 00:00:00 utc, with leap seconds ignored. note: parsing of strings with date.parse is strongly discouraged due to browser diff...
...eap seconds ignored. date.parse() parses a string representation of a date and re
turns the number of milliseconds since 1 january, 1970, 00:00:00 utc, with leap seconds ignored. note: parsing of strings with date.parse is strongly discouraged due to browser differences and inconsistencies. date.utc() accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored. instance methods date.prototype.getdate() re
turns the day of the month (1–31) for the specified date according to local time. ...
...ser differences and inconsistencies. date.utc() accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc, with leap seconds ignored. instance methods date.prototype.getdate() re
turns the day of the month (1–31) for the specified date according to local time. date.prototype.getday() re
turns the day of the week (0–6) for the specified date according to local time. date.prototype.getfullyear() re
turns the year (4 digits for 4-digit years) of the specified date according to local time. ...
...And 14 more matches
core/heritage - Archive of obsolete content
or writing such code requires sharp eye and lot's of discipline, mainly due to code fragmentation and lots of machinery being exposed: // defining a simple class function dog(name) { // classes are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. ...
... behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof dog)) re
turn new dog(name); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. this is too much machinery exposed. dog.prototype.type = 'dog'; dog.prototype.bark = function bark() { re
turn 'ruff! ruff!' }; // subclassing a `dog` function pet(name, breed) { // once again we do our little dance if (!(this instanceof pet)) re
turn new pet(name, breed); dog.call(this, name); this.breed = breed; } // to subclass, you need to make another special dance with special // 'prototype' properties. pet.prototype = object.create(dog.prototype); // if you want correct instanceof behavior...
...her special dance with special // 'prototype' properties. pet.prototype = object.create(dog.prototype); // if you want correct instanceof behavior you need to make a dance with // another special `constructor` property of the `prototype` object. object.defineproperty(pet.prototype, 'constructor', { value: pet }); // finally you can define some properties. pet.prototype.call = function(name) { re
turn this.name === name ? this.bark() : ''; }; since sdk apis may be interacting with untrusted code an extra security measures are required to guarantee that documented behavior can't be changed at runtime. to do that we need to freeze constructor's prototype chain to make sure functions are frozen: object.freeze(dog.prototype); object.freeze(pet.prototype); note: also, this is not quite enough as...
...And 13 more matches
listbox - Archive of obsolete content
be -1. (or, on some platforms, typeof(listboxcurrentindex) will be undefined) in a single selection list, the current index will always be the same as the selected index. in a multiple selection list, the currently focused row may be modified by the user without changing the selection by pressing the control key and pressing the cursor keys to navigate. currentitem type: listitem element re
turns the currently focused item in the list box, which is only useful in a multiple selection list box. disabled type: boolean gets and sets the value of the disabled attribute. disablekeynavigation type: boolean gets or sets the value of the disablekeynavigation attribute. itemcount type: integer read only property holding the number of child items. ...
... itemcount type: integer read only property holding the number of child items. listboxobject type: nsilistboxobject the nsilistboxobject behind the list box. this property is read-only. most of the features of the list box are already available directly in the listbox, so you will rarely have need to use this box object directly. ...
...ct type: nsilistboxobject the nsilistboxobject behind the list box. this property is read-only. most of the features of the list box are already available directly in the listbox, so you will rarely have need to use this box object directly. selectedcount type: integer re
turns the number of items that are currently selected. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selecteditem type: element holds the currently selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a ...
...And 13 more matches
richlistbox - Archive of obsolete content
be -1. (or, on some platforms, typeof(listboxcurrentindex) will be undefined) in a single selection list, the current index will always be the same as the selected index. in a multiple selection list, the currently focused row may be modified by the user without changing the selection by pressing the control key and pressing the cursor keys to navigate. currentitem type: listitem element re
turns the currently focused item in the list box, which is only useful in a multiple selection list box. disabled type: boolean gets and sets the value of the disabled attribute. disablekeynavigation type: boolean gets or sets the value of the disablekeynavigation attribute. itemcount type: integer read only property holding the number of child items. ...
... type: boolean gets or sets the value of the disablekeynavigation attribute. itemcount type: integer read only property holding the number of child items. scrollboxobject type: nsiscrollboxobject the scroll box object implements the nsiscrollboxobject interface, which may be used to retrieve and adjust the scroll position of the list box. ...
...ger read only property holding the number of child items. scrollboxobject type: nsiscrollboxobject the scroll box object implements the nsiscrollboxobject interface, which may be used to retrieve and adjust the scroll position of the list box. selectedcount type: integer re
turns the number of items that are currently selected. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selecteditem type: element holds the currently selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a...
...And 13 more matches
Componentizing our React app - Learn web development
ou run these! mkdir src/components touch src/components/todo.js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. ...
...js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. ...
...g the code for that to todo.js too, as follows. ...
...And 13 more matches
XPCOMUtils.jsm
using a form similar to this. mycomponent.prototype = { // properties required for xpcom registration: classdescription: "unique text description", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", // [optional] custom factory (an object implementing nsifactory). if not // provided, the default factory is used, which re
turns // |(new mycomponent()).queryinterface(iid)| in its createinstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry(). 'true' is passed for // both apersist and areplace params. category: "some-categor...
...tegory only on the specified applications. apps: [ ... ] }], // queryinterface implementation, e.g. using the generateqi helper queryinterface: xpcomutils.generateqi( [components.interfaces.nsiobserver, components.interfaces.nsimyinterface, "nsifoo", "nsibar" ]), // [optional] classinfo implementation, e.g. using the generateci helper. // will be automatically re
turned from queryinterface if that was // generated with the generateqi helper. classinfo: xpcomutils.generateci( {classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", classdescription: "unique text description", interfaces: [components.interfaces.nsiobserver, components.interfaces.nsimyinterface, ...
... methods definelazygetter() getter functions in javascript give you a way to define a property of an object, but not calculate the property's value until it is accessed. a getter defers the cost of calculating the value until the value is needed, and if it is never needed, you never pay the cost. a "lazy getter" provides an additional optimization: the...
...And 13 more matches
NSS Sample Code Utilities_1
en); pr_fprintf(out, "%s", b64data); pr_fprintf(out, "\n"); if (b64data) { port_free(b64data); } } /* * printashex */ void printashex(prfiledesc* out, const unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); re
turn; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } ...
...mn += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { re
turn -1; } if (c <= '9' && c >= '0') { re
turn c - '0'; } if (c <= 'f' && c >= 'a') { re
turn c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { re
turn c - 'a' + 0xa; } re
turn -1; } /* * hextobuf */ int hextobuf(unsigned char *instring, secitem *outbuf, prbool ishexdata) { int len = strlen(instring); int outlen = len+1/2; int truelen = 0; ...
...if (c <= 'f' && c >= 'a') { re
turn c - 'a' + 0xa; } re
turn -1; } /* * hextobuf */ int hextobuf(unsigned char *instring, secitem *outbuf, prbool ishexdata) { int len = strlen(instring); int outlen = len+1/2; int truelen = 0; int digit1, digit2; outbuf->data = ishexdata ? ...
...And 13 more matches
Avoiding leaks in JavaScript XPCOM components
ns that cause leaks. basics of memory management creating objects that are not a fixed size for the lifetime of the program (global variables) or a fixed size for the lifetime of a function (stack variables) requires a system for dynamic memory allocation: a system that allocates memory from a space called the heap. the requirements for such a memory allocation system are: memory should be re
turned to the heap when the program no longer needs it (or soon thereafter) so that the amount of memory consumed by the program does not increase. programs should not dereference pointers pointing to memory that has been re
turned to the heap (and potentially reused). meeting both requirements at the same time can be tricky. many programming languages guarantee a solution for (2) and handle all the...
...nguages guarantee a solution for (2) and handle all the heap management for the programmer. however, this doesn't mean that (1) is also solved. the most common strategies for managing heap allocation are the following: malloc and free (or new and delete) the simplest strategy for heap allocation is that the programmer makes one function call to request memory from the heap and another one to re
turn it. in c, these are malloc and free. in c++, they're new and delete. if the programmer forgets to re
turn the memory to the heap, it leaks. if the programmer accesses the memory after re
turning it to the heap, the program will access whatever happens to be at that location, and will likely either behave nondeterministically or crash. with this strategy, a single pointer to the object is considered...
...ies the potential for crashes just like malloc and free). the potential causes of leaks with garbage collection (the next strategy) also apply to reference counting as well. garbage collection garbage collection is generally used to refer to algorithms that (1) determine which objects are still needed by starting from a set of roots and finding all objects reachable from those objects and (2) re
turning all remaining objects to the heap. the roots include things like global variables and variables on the current call stack. mozilla's javascript engine uses one of the most common garbage collection algorithms, mark and sweep, in which the garbage collector clears the mark bit on each object, sets the mark bits on all roots and all objects reachable from them, and then finalizes all objects not...
...And 13 more matches
IAccessible2
an extended role is a role which is dynamically generated by the application. it is not predefined by the ...
...pe, [in] long x, [in] long y ); [propget] hresult states([out] accessiblestates states ); [propget] hresult uniqueid([out] long uniqueid ); [propget] hresult windowhandle([out] hwnd windowhandle ); methods attributes() re
turns the attributes specific to this iaccessible2 object, such as a cell's formula. [propget] hresult attributes( [out] bstr attributes ); parameters attributes re
turn value s_false re
turned if there is nothing to re
turn, [out] value is null. s_ok. extendedrole() re
turns the extended role. ...
...an extended state is a state which is dynamically generated by the application. it is not predefined by the iaccessible2 specification. ...
...And 13 more matches
nsIMsgHeaderParser
exceptions thrown missing exception missing description n...
...n boolean preserveintegrity); methods extractheaderaddressmailboxes() given a string which contains a list of header addresses, re
turns a comma-separated list of just the 'mailbox' portions. if any of the addresses doesn't have a mailbox, then the user name is used instead. autf8string extractheaderaddressmailboxes( in string line ); parameters line the header line to parse. re
turn value a comma-separated list of just the mailbox parts of the addresses. exceptions thrown missing exception missing description native code only!extractheaderaddressnames given a string which contains a list of header addresses, re
turns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string ex...
...missing exception missing description native code only!extractheaderaddressnames given a string which contains a list of header addresses, re
turns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to parse. re
turn value a comma-separated list of just the name parts of the addresses. ...
...And 13 more matches
nsISessionStore
ers awindow the window in which to delete the value. akey the key whose value is to be deleted. duplicatetab() duplicates a specified tab as thoroughly as possible. nsidomnode duplicatetab( in nsidomwindow awindow, in nsidomnode atab ); parameters awindow the window in which the duplicated tab will be created. atab the tab to duplicate (can come from a different window). ...
...icate (can come from a different window). re
turn value an nsidomnode representing the new tab, the content of which is a duplicate of atab. forgetclosedtab() nsidomnode forgetclosedtab( in nsidomwindow awindow, in unsigned long aindex ); parameters awindow is the browser window associated with the closed tab. aindex is the index of the closed tab to be removed (fifo ordered). re
turn value forgetclosedwindow() nsidomnode forgetclosedwindow( in unsigned long aindex ); parameters aindex is the index of the closed window to be removed (fifo ordered). re
turn value exceptions thrown ns_error_invalid_arg when aindex does not map to a closed window. getbrowserstate() re
turns the current state of all of windows and all of their tabs. astring getbrowserstate()...
...dow() nsidomnode forgetclosedwindow( in unsigned long aindex ); parameters aindex is the index of the closed window to be removed (fifo ordered). re
turn value exceptions thrown ns_error_invalid_arg when aindex does not map to a closed window. getbrowserstate() re
turns the current state of all of windows and all of their tabs. astring getbrowserstate(); parameters none. re
turn value a json string representing the current state of all windows in the web browser. getclosedtabcount() re
turns the number of restorable tabs for a given window. unsigned long getclosedtabcount( in nsidomwindow awindow ); parameters awindow the window whose restorable tab count should be re
turned. re
turn value the number of restorable tabs in the window. getclosedtabdata() retu...
...And 13 more matches
Using readable streams - Web APIs
xample, our simple stream pump example goes on to enqueue each chunk in a new, custom readablestream (we will find more about this in the next section), then create a new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...each chunk in a new, custom readablestream (we will find more about this in the next section), then create a new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...will find more about this in the next section), then create a new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched. ...
...And 13 more matches
Inputs and input sources - Web APIs
target ray is emitted (such as the front tip of the controller, or the end of a gun barrel if the controller is being rendered as a gun, for example), and the space's orientation vector extends outward along the path of the target ray. you can easily obtain the target ray corresponding to the targetrayspace from within the drawing handler for a given frame using xrframe's getpose() method. the re
turned xrpose's transform is the transform corresponding to the target ray. thus, for an input controller primaryinput: let targetraypose = frame.session.getpose(primaryinput.targetrayspace, viewerrefspace); let targetrayorigin = targetraypose.transform.position; let targetrayvector = targetraypose.transform.orientation; with this, you now have the point from which the target...
...t handler is replaced with the function realselecthandler(), which will be used for handling all future select events. then we pass the event through to realselecthandler() to allow the event to be processed as normal. let primaryinputsource = xrsession.inputsources[0]; xrsession.onselect = function(event) { primaryinputsource = event.inputsource; xrsession.onselect = realselecthandler; re
turn realselecthandler(event); }; the effect is that we set the primary input source the first time a select event is received, regardless of which input source it comes from, handle the event as normal from there, and from then on simply handle the events as usual without any further worries about which input source is primary. user-selected the most complex way to determine a primary input sourc...
... event. xrsession.addeventlistener("select", event => { let inputsource = event.inputsource; let frame = event.frame; /* handle the event */ }); some actions may send these events very quickly, one after the other. the time that elapses between these events depends on both the hardware apparatus that causes the action as well as the software drivers that interpret the hardware action and
turn it into a series of events. do not presume these events will happen with any particular amount of time between them. for example, if the hardware that causes the primary action to occur is a button, you would receive selectstart when the user presses the button, then select and selectend when the user releases it. there are a number of examples showing how to handle select events throughout the...
...And 13 more matches
Closures - JavaScript
ested. the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. nested functions have access to variables declared in their outer scope. closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } re
turn displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is re
turned from the outer function before being executed. at first glance, it might seem unintuitive that this code still works. in some programming languages, the loca...
...nstance of the function displayname created when makefunc is run. the instance of displayname maintains a reference to its lexical environment, within which the variable name exists. for this reason, when myfunc is invoked, the variable name remains available for use, and "mozilla" is passed to alert. here's a slightly more interesting example—a makeadder function: function makeadder(x) { re
turn function(y) { re
turn x + y; }; } var add5 = makeadder(5); var add10 = makeadder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 in this example, we have defined a function makeadder(x), that takes a single argument x, and re
turns a new function. the function it re
turns takes a single argument y, and re
turns the sum of x and y. in essence, makeadder is a function factory. ...
...using the relative em unit: body { font-family: helvetica, arial, sans-serif; font-size: 12px; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; } such interactive text size buttons can change the font-size property of the body element, and the adjustments are picked up by other elements on the page thanks to the relative units. here's the javascript: function makesizer(size) { re
turn function() { document.body.style.fontsize = size + 'px'; }; } var size12 = makesizer(12); var size14 = makesizer(14); var size16 = makesizer(16); size12, size14, and size16 are now functions that resize the body text to 12, 14, and 16 pixels, respectively. you can attach them to buttons (in this case hyperlinks) as demonstrated in the following code example. document.getelementbyid('siz...
...And 13 more matches
Numbers and dates - JavaScript
ng table summarizes the number object's properties. ...
...y description number.max_value the largest representable number (±1.7976931348623157e+308) number.min_value the smallest representable number (±5e-324) number.nan special "not a number" value number.negative_infinity special negative infinite value; re
turned on overflow number.positive_infinity special positive infinite value; re
turned on overflow number.epsilon difference between 1 and the smallest value greater than 1 that can be represented as a number (2.220446049250313e-16) number.min_safe_integer minimum safe integer in javascript (−253 + 1, or −9007199254740991) number.max_safe_integer maximum safe integer in javascript (+253 − 1, or +9007199254740991) methods of numbe...
... same as the global parseint() function. number.isfinite() determines whether the passed value is a finite number. number.isinteger() determines whether the passed value is an integer. ...
...And 13 more matches
Object - JavaScript
re seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. this provides a very powerful although potentially dangerous mechanism to override or extend object behavior. the object constructor creates an object wrapper for the given value. if the value is null or undefined, it will create and re
turn an empty object. otherwise, it will re
turn an object of a type that corresponds to the given value. if the value is an object already, it will re
turn the value. when called in a non-constructor context, object behaves identically to new object(). see also the object initializer / literal syntax. deleting a property from an object there isn't any method in an object itself to delete its own...
...ues of all enumerable own properties from one or more source objects to a target object. object.create() creates a new object with the specified prototype object and properties. object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. ...
...operty described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. object.entries() re
turns an array containing all of the [key, value] pairs of a given object's own enumerable string properties. object.freeze() freezes an object. other code cannot delete or change its properties. object.fromentries() re
turns a new object from an iterable of [key, value] pairs. (this is the reverse of object.entries). object.getownpropertydescriptor() re
turns a property descriptor for a named property on an object. ...
...And 13 more matches
Promise - JavaScript
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 re
turn values like synchronous methods: instead of immediately re
turning the final value, the asynchronous method re
turns 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 successfully. rejected: meaning that the operation failed. a pending promise...
...hese 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 re
turn 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 happening, which can be chained with callback functions. if you are looking to lazily evaluate an expression, consider the arrow function with n...
...ill also hear the term resolved used with promises — this means that the promise is settled or “locked in” to match the state of another promise. states and fates contains more details about promise terminology. chained promises the methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. these methods also re
turn a newly generated promise object, which can optionally be used for chaining; for example, like this: const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda,handlerejecteda) .then(handlefulfilledb,handlerejectedb) .then(handlefulfilledc,handlerejectedc); // or, perhaps better ... const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda) .then(hand...
...And 13 more matches
Iteration protocols - JavaScript
r, such as array or map, while other types (such as object) are not. in order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that re
turns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the re
turned iterator is used to obtain the values to be iterated. note that when this zero-argument function is called, it is invoked as a method on the iterable object. therefore inside of the funct...
...iterated. note that when this zero-argument function is called, it is invoked as a method on the iterable object. therefore inside of the function, the this keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration. this function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is re
turned. inside of this generator function, each entry can be provided by using yield. the iterator protocol the iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a re
turn value when all values have been generated. an object is an iterator when it implements a next() method with the following semantics: property value ...
...rovided by using yield. the iterator protocol the iterator protocol defines a standard way to produce a sequence of values (either finite or infinite), and potentially a re
turn value when all values have been generated. an object is an iterator when it implements a next() method with the following semantics: property value next() a zero-argument function that re
turns an object with at least the following two properties: done (boolean) has the value false if the iterator was able to produce the next value in the sequence. (this is equivalent to not specifying the done property altogether.) has the value true if the iterator has completed its sequence. in this case, value optionally specifies the re
turn value of the iterator. va...
...And 13 more matches
Index - XPath
tors, xpath this article seeks to document the difference between css selectors and xpath for web developers to be able to better choose the right tool for the right job. 17 functions transforming_xml_with_xslt, xpath, xpath_reference, xslt, xslt_reference no summary! 18 boolean xslt, xslt_reference the boolean function evaluates an expression and re
turns true or false. 19 ceiling xslt, xslt_reference the ceiling function evaluates a decimal number and re
turns the smallest integer greater than or equal to the decimal number. 20 choose function, xpath, xslt the choose function re
turns one of the specified objects based on a boolean parameter. 21 concat xslt, xslt_reference the co...
..._reference the ceiling function evaluates a decimal number and re
turns the smallest integer greater than or equal to the decimal number. 20 choose function, xpath, xslt the choose function re
turns one of the specified objects based on a boolean parameter. 21 concat xslt, xslt_reference the concat function concatenates two or more strings and re
turns the resulting string. 22 contains xslt, xslt_reference the contains function determines whether the first argument string contains the second argument string and re
turns boolean true or false. 23 count xslt, xslt_reference the count function counts the number of nodes in a node-set and re
turns an integer. 24 current xslt, xslt_referenc...
... xslt, xslt_reference the count function counts the number of nodes in a node-set and re
turns an integer. 24 current xslt, xslt_reference the current function can be used to get the context node in an xslt instruction. 25 document xslt, xslt_reference the document finds a node-set in an external document, or multiple external documents, and re
turns the resulting node-set. 26 element-available xslt, xslt_reference the element-available function determines if an element is available and re
turns true or false. 27 false xslt, xslt_reference the false function re
turns boolean false. ...
...And 13 more matches
lang/type - Archive of obsolete content
functions for working with type detection. globals functions isundefined(value) re
turns true if value is undefined, false otherwise. let { isundefined } = require('sdk/lang/type'); var foo; isundefined(foo); // true isundefined(0); // false parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is undefined. isnull(value) re
turns true if value is null, false otherwise. let { isnull } = require('sdk/lang/type'); isnull(null); // true isnull(false); // false parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is null. isstring(value) re
turns true if value is a string, false otherwise. uses typeof operator to check type, and will only properly detect string primitives: for example, a string ...
... require('sdk/lang/type'); isnull(null); // true isnull(false); // false parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is null. isstring(value) re
turns true if value is a string, false otherwise. uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new string() will always re
turn false. let { isstring } = require('sdk/lang/type'); isstring('my string'); // true isstring(100); // false isstring('100'); // true parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is a string. isnumber(value) re
turns true if value is a number, false otherwise. uses typeof operator to check type, and will only properly detect number primitives...
...'my string'); // true isstring(100); // false isstring('100'); // true parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is a string. isnumber(value) re
turns true if value is a number, false otherwise. uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new number() will always re
turn false. let { isnumber } = require('sdk/lang/type'); isnumber(3.1415); // true isnumber(100); // true isnumber('100'); // false parameters value : mixed the variable to check. re
turns boolean : boolean indicating if value is a number. isregexp(value) re
turns true if value is a regexp, false otherwise. let { isregexp } = require('sdk/lang/type'); isregexp(/[^\.]*\.js$/); // true isregexp...
...And 12 more matches
places/bookmarks - Archive of obsolete content
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 re
turn 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. examples creating a new bookmark let { boo...
...be saved since all bookmarks are children // of `group`. this will be saved implicitly. save(bookmarks).on("data", function (saved, input) { // a data event is called once for each item saved, as well // as implicit items, like `group` console.log(input === group || ~bookmarks.indexof(input)); // true }).on("end", function (saves, inputs) { // like the previous example, the "end" event re
turns an // array of all of our updated saves. only explicitly saved // items are re
turned in this array -- the `group` won't be // present here. console.log(saves[0].title); // "ran" console.log(saves[2].group.title); // "guitars" }); searching for bookmarks bookmarks can be queried with the search() function, which accepts a query object or an array of query objects, as well as a query o...
... p...
...And 12 more matches
window/utils - Archive of obsolete content
functions for working with browser windows. usage private windows with this module your add-on will see private browser windows even if it has not explicitly opted into private browsing, so you need to take care not to store any user data derived from private browser windows. the exception is the windows() function which re
turns an array of currently opened windows. ...
...ed windows. private windows will not be included in this list if your add-on has not opted into private browsing. to learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. globals functions getmostrecentbrowserwindow() get the topmost browser window, as an nsidomwindow instance. re
turns nsidomwindow: the topmost browser window. getinnerid(window) re
turns the id of the specified window's current inner window. this function wraps nsidomwindowutils.currentinnerwindowid. parameters window : nsidomwindow the window whose inner window we are interested in. re
turns id: the given window's id. getouterid(window) re
turns the id of the specified window's outer window. this funct...
...function wraps nsidomwindowutils.currentinnerwindowid. parameters window : nsidomwindow the window whose inner window we are interested in. re
turns id: the given window's id. getouterid(window) re
turns the id of the specified window's outer window. this function wraps nsidomwindowutils.outerwindowid. parameters window : nsidomwindow the window whose outer window we are interested in. re
turns id: the outer window's id. ...
...And 12 more matches
Client-side form validation - Learn web development
button> element) htmlfieldsetelement (represents a <fieldset> element) htmlinputelement (represents an <input> element) htmloutputelement (represents an <output> element) htmlselectelement (represents a <select> element) htmltextareaelement (represents a <textarea> element) the constraint validation api makes the following properties available on the above elements. ...
...tarea> element) the constraint validation api makes the following properties available on the above elements. validationmessage: re
turns a localized message describing the validation constraints that the control doesn't satisfy (if any). if the control is not a candidate for constraint validation (willvalidate is false) or the element's value satisfies its constraints (is valid), this will re
turn an empty string. validity: re
turns a validitystate object that contains several properties describing the validity state of the element. you can find full details of all the available properties in the validitystate reference page; below is listed a few of the more common ones: patternmismatch: re
turns true if the value does not match the specified pattern, and false if it does match. if t...
...ins several properties describing the validity state of the element. you can find full details of all the available properties in the validitystate reference page; below is listed a few of the more common ones: patternmismatch: re
turns true if the value does not match the specified pattern, and false if it does match. if true, the element matches the :invalid css pseudo-class. toolong: re
turns true if the value is longer than the maximum length specified by the maxlength attribute, or false if it is shorter than or equal to the maximum. if true, the element matches the :invalid css pseudo-class. tooshort: re
turns true if the value is shorter than the minimum length specified by the minlength attribute, or false if it is greater than or equal to the minimum. if true, the element mat...
...And 12 more matches
Making decisions in your code — conditionals - Learn web development
seudocode: if (condition) { code to run if condition is true } else { run some other code instead } here we've got: the keyword if followed by some parentheses. a condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). the condition makes use of the comparison operators we discussed in the last module and re
turns true or false. a set of curly braces, inside which we have some code — this can be any code we like, and it only runs if the condition re
turns true. the keyword else. another set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false. this code is pretty human-readab...
... inside which we have some code — this can be any code we like, and it only runs if the condition re
turns true. the keyword else. another set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false. ...
...this is not necessarily a bad thing, but it might not be what you want — often you want to run one block of code or the other, not both. as a final point, you may sometimes see if...else statements written without the curly braces, in the following shorthand style: if (condition) code to run if condition is true else run some other code instead this is perfectly valid code, b...
...And 12 more matches
Fetching data from the server - Learn web development
request method to use to request the resource from the network, and what its url is. we'll just use the get method here and set the url as our url variable. add this below your previous line: request.open('get', url); next, we'll set the type of response we are expecting — which is defined by the request's responsetype property — as text. ...
...when this has occurred, the response data will be available in the response property of the xhr request object. ...
...when this has occurred, the response data will be available in the response property of the xhr request object. add the following below your last addition. ...
...And 12 more matches
Sqlite.jsm
al) if defined, the connection will attempt to minimize its memory usage after this many milliseconds of connection idle. the connection is idle when no statements are executing. there is no default value which means no automatic memory minimization will occur. please note that this is not a timer on the idle service and this could fire while the application is active. openconnection(options) re
turns a promise that resolves to an opened connection instance or is rejected if an error occurred while opening the database. here is an example: components.utils.import("resource://gre/modules/sqlite.jsm"); try { const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); // connection is the opened sqlite connection (see below for api). } catch (error) ...
... instance. connection management these apis are used to manage and inspect the state of the connection. close() close this database connection. this must be called on every opened connection or else application shutdown will fail due to waiting on the opened connection to close (gecko doesn't force close connections because it doesn't know that you are really done with them). this function re
turns a promise that will be resolved when the database has closed. if a transaction is in progress at the time this function is called, the transaction will be forcibly rolled back. if statements are in progress at the time this function is called, they will be cancelled. callers should not attempt to use the connection after calling this method as the connection will be unusable. it is possible ...
...sed 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 re
turns 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-only, the clone will be, regardless of this option. if the original connection is using the shared cache, this parameter will be ignored and the clone will be as privileged as the o...
...And 12 more matches
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. ...
...ts until the promise is resolved. task.spawn() re
turns a promise that is resolved when the task completes successfully, or is rejected if an exception occurs. you can use the yield operator inside the generator function to wait on a promise, spawn another task, or propagate a value: let resolutionvalue = yield (promise/generator/iterator/value); if you specify a promise, the yield operator re
turns its resolution value as soon as the promise is resolved. if the promise is rejected, its rejection reason is thrown as an exception. if you specify a generator function or the iterator re
turned by a generator function, then task.spawn() is implicitly called, and the yield operator works on the re
turned promise. this reduces the syntax overhead of calling task.spawn() explicitly when you want to...
...ecify a generator function or the iterator re
turned by a generator function, then task.spawn() is implicitly called, and the yield operator works on the re
turned promise. this reduces the syntax overhead of calling task.spawn() explicitly when you want to recurse into other task functions. if you specify a function that is not a generator, it is called with no arguments, and the yield operator re
turns the re
turn 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 re
turns exactly what you specified. method overview function async(atask); promise spawn(atask); properties attribute type description result rea...
...And 12 more matches
nsIWindowMediator
the value of inbelow will be ignored for zleveltop and zlevelbottom.) inbelow if inposition is set to zlevelbelow, the window below which inwindow wants to be placed. otherwise this variable is ignored. outposition constrained position, values like inposition. outbelow the window below which inwindow should be placed, if outposition equals zlevelbelow. otherwise this value will be null. re
turn value pr_true if the position re
turned is different from the position given. getenumerator() re
turn an enumerator which iterates over all windows of type awindowtype from the oldest window to the youngest. nsisimpleenumerator getenumerator( in wstring awindowtype ); parameters awindowtype the re
turned enumerator will enumerate only windows of this type. ("type" is the |windowtype| att...
...tenumerator() re
turn an enumerator which iterates over all windows of type awindowtype from the oldest window to the youngest. nsisimpleenumerator getenumerator( in wstring awindowtype ); parameters awindowtype the re
turned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the xml <window> element.) if null, all windows will be enumerated. re
turn value an enumerator of nsidomwindows. getmostrecentwindow() this is a shortcut for simply fetching the first window in front to back order. nsidomwindow getmostrecentwindow( in wstring awindowtype ); parameters awindowtype re
turn the topmost window of this type. ...
...ull, all windows will be enumerated. re
turn value an enumerator of nsidomwindows. getmostrecentwindow() this is a shortcut for simply fetching the first window in front to back order. nsidomwindow getmostrecentwindow( in wstring awindowtype ); parameters awindowtype re
turn the topmost window of this type. ("type" is the |windowtype| attribute of the xml <window> element.) if null, re
turn the topmost window of any type. re
turn value the topmost window. note: starting in gecko 8.0, the re
turned value is an nsidomwindow; previously, it was an nsidomwindowinternal. you may need to update your code or recompile binary components, if they use this method. getouterwindowwithid() re
turn the outer window with the given id, if any. nsidomwindow getouterwindowwithid( in unsigned ...
...And 12 more matches
nsIXPCScriptable
js/src/xpconnect/idl/nsixpcscriptable.idlnot scriptable please add a summary to this article. ...
... js/src/xpconnect/idl/nsixpcscriptable.idlnot scriptable please add a summary to this article. ...
...fo_interfaces_only 1 << 23 allow_prop_mods_during_resolve 1 << 24 allow_prop_mods_to_prototype 1 << 25 dont_share_prototype 1 << 26 dont_reflect_interface_names 1 << 27 want_equality 1 << 28 want_outer_object 1 << 29 want_inner_object 1 << 30 reserved 1 << 31 the high order bit is reserved for consumers of these flags. no implementor of this interface should ever re
turn flags with this bit set. methods precreate() void precreate( in nsisupports nativeobj, in jscontextptr cx, in jsobjectptr globalobj, out jsobjectptr parentobj ); parameters nativeobj cx globalobj parentobj create() void create( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj ); parameters wrapper cx obj postcreate() ...
...And 12 more matches
Microdata DOM API - Web APIs
and removed from all browsers and are therefore deprecated. you can't use them anymore and this document is kept as information only. microdata becomes even more useful when scripts can use it to expose information to the user, for example offering it in a form that can be used by other applications. the document.getitems(typenames) method provides access to the top-level microdata items. it re
turns a nodelist containing the items with the specified types, or all types if no argument is specified. each item is represented in the dom by the element on which the relevant itemscope attribute is found. these elements have their element.itemscope idl attribute set to true. the type(s) of items can be obtained using the element.itemtype idl attribute on the element with the itemscope attribute. ...
...ecified types, or all types if no argument is specified. each item is represented in the dom by the element on which the relevant itemscope attribute is found. these elements have their element.itemscope idl attribute set to true. the type(s) of items can be obtained using the element.itemtype idl attribute on the element with the itemscope attribute. methods document . getitems( [ types ] ) re
turns a nodelist of the elements in the document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed. the types argument is interpreted as a space-separated list of types. the document.getitems(typenames) method takes a string that contains an unordered set of unique space-separated tokens that are case-sensitive, representing types...
...he document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed. the types argument is interpreted as a space-separated list of types. the document.getitems(typenames) method takes a string that contains an unordered set of unique space-separated tokens that are case-sensitive, representing types. ...
...And 12 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
for references to the <div> elements into which we'll output the matrices when we want to show them to the user. logging errors a function called logglerror() is implemented to provide an easily customized way to output logging information for errors that occur while executing webgl functions. function logglerror(where) { let err = gl.geterror(); if (err) { console.error(`webgl error re
turned by ${where}: ${err}`); } } this takes as its only input a string, where, which is used to indicate what part of the program generated the error, since similar errors can have in multiple situations. the vertex and fragment shaders the vertex and fragment shaders are both exactly the same as those used in the example for our article lighting in webgl. refer to that if you're interested in ...
...he example for our article lighting in webgl. refer to that if you're interested in the glsl source code for the basic shaders used here. suffice it to say that the vertex shader computes the position of each vertex given the initial positions of each vertex and the transforms that need to be applied to convert them to simulate the viewer's current position and orientation. the fragment shader re
turns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. starting up and shutting down webxr upon initially loading the script, we install a handler for the load event, so that we can perform initialization. window.addeventlistener("load", onload); function onload() { xrbutton = document.queryselector("#enter-xr"); xrbutton...
...out process manually in this situation. starting up the webxr session the sessionstarted() function handles actually setting up and starting the session, by setting up event handlers, compiling and installing the glsl code for the vertex and fragment shaders, and attaching the webgl layer to the webxr session before kicking off the rendering loop. it gets called as the handler for the promise re
turned by issessionsupported(). function sessionstarted(session) { let refspacetype; xrsession = session; xrbutton.innertext = "exit webxr"; xrsession.addeventlistener("end", sessionended); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); if (allowmouserotation) { canvas.addeventlistener("pointermove", handlepointermove); ...
...And 12 more matches
Using the Web Speech API - Web APIs
echanisms. this article provides a simple introduction to both areas, along with demos. speech recognition speech recognition involves receiving speech through a device's microphone, which is then checked by a speech recognition service against a list of grammar (basically, the vocabulary you want to have recognised in a particular app.) when a word or phrase is successfully recognised, it is re
turned as a result (or list of results) as a text string, and further actions can be initiated as a result. the web speech api has a main controller interface for this — speechrecognition — plus a number of closely-related interfaces for representing grammar, results, etc. generally, the default speech recognition system available on the device will be used for the speech recognition — most mod...
...tion instance before we move on: speechrecognition.continuous: controls whether continuous results are captured (true), or just a single result each time recognition is started (false). speechrecognition.lang: sets the language of the recognition. setting this is good practice, and therefore recommended. speechrecognition.interimresults: defines whether the speech recognition system should re
turn interim results, or just final results. final results are good enough for this simple demo. speechrecognition.maxalternatives: sets the number of alternative potential matches that should be re
turned per result. this can sometimes be useful, say if a result is not completely clear and you want to display a list if alternatives for the user to choose the correct one from. but it is not needed for...
...result is received: recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log('confidence: ' + event.results[0][0].confidence); } the second line here is a bit complex-looking, so let's explain it step by step. the speechrecognitionevent.results property re
turns a speechrecognitionresultlist object containing speechrecognitionresult objects. it has a getter so it can be accessed like an array — so the first [0] re
turns the speechrecognitionresult at position 0. each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual recognised words. these also have getters so they can be accessed like arrays — the s...
...And 12 more matches
Array.prototype.map() - JavaScript
results of calling a provided function on every element in the calling array. 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 let new_array = arr.map(function callback( currentvalue[, index[, array]]) { // re
turn element for new_array }[, thisarg]) parameters callback function that is called for every element of arr. each time callback executes, the re
turned value is added to new_array. the callback function accepts the following arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arra...
... description map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined). ...
...nstructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including undefined). it is not called for missing elements of the array; that is: indexes that have never been set; which have been deleted; or which have never been assigned a value. when not to use map() since map builds a new array, using it when you aren't using the re
turned array is an anti-pattern; use foreach or for-of instead. you shouldn't be using map if: you're not using the array it re
turns; and/or you're not re
turning a value from the callback. parameters in detail callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped. if a thisarg parameter is provided, it will be used as c...
...And 12 more matches
Array - JavaScript
console.log(vegetables) // ["cabbage", "carrot"] (the original arra...
...x of an item in the array fruits.push('mango') // ["strawberry", "banana", "mango"] let pos = fruits.indexof('banana') // 1 remove an item by index position let removeditem = fruits.splice(pos, 1) // this is how to remove an item // ["strawberry", "mango"] remove items from an index position let vegetables = ['cabbage', '
turnip', 'radish', 'carrot'] console.log(vegetables) // ["cabbage", "
turnip", "radish", "carrot"] let pos = 1 let n = 2 let removeditems = vegetables.splice(pos, n) // this is how to remove items, n defines the number of items to be removed, // starting at the index position specified by pos and progressing toward the end of array. console.log(vegetables) // ["cabbage", "carrot"] (the original array is changed) console.log(removeditems) // ["
turnip", "radish"] co...
...onsole.log(removeditems) // ["
turnip", "radish"] copy an array let shallowcopy = fruits.slice() // this is how to make a copy // ["strawberry", "mango"] accessing array elements javascript arrays are zero-indexed. the first element of an array is at index 0, and the last element is at the index value equal to the value of the array's length property minus 1. using an invalid index number re
turns undefined. let arr = ['this is the first element', 'this is the second element', 'this is the last element'] console.log(arr[0]) // logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' array elements are object properties in the same way that tostring is a propert...
...And 12 more matches
Object.defineProperty() - JavaScript
the static method object.defineproperty() defines a new property directly on an object, or modifies an existing property on an object, and re
turns the object. 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 object.defineproperty(obj, prop, descriptor) parameters obj the object on which to define the property. prop the name or symbol of the property to be defined or modified. descriptor the descriptor for the property being defined or modified. re
turn value the object that was passed to the function. description this method allows a precise addition to or modification of a property on an object.
...false. an accessor descriptor also has the following optional keys: get a function which serves as a getter for the property, or undefined if there is no getter. when the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). the re
turn value will be used as the value of the property. defaults to undefined. set a function which serves as a setter for the property, or undefined if there is no setter. when the property is assigned, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned. defaults to undefined. if a descriptor ...
...and ... object.defineproperty(obj, 'key', withvalue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (object.freeze || object)(object.prototype); examples if you want to see how to use the object.defineproperty method with a binary-flags-like syntax, see additional example...
...And 12 more matches
Creating Reusable Modules - Archive of obsolete content
ptforfile() { const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); var window = require("sdk/window/utils").getmostrecentbrowserwindow(); fp.init(window, "select a file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filterall | nsifilepicker.filtertext); var rv = fp.show(); if (rv == nsifilepicker.re
turnok || rv == nsifilepicker.re
turnreplace) { var file = fp.file; // get the path as string. note that you usually won't // need to work with the string paths. var path = fp.file.path; // work with re
turned nsilocalfile... } re
turn path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for t...
.... var path = fp.file.path; // work with re
turned nsilocalfile... } re
turn path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for that interface includes an example of calculating an md5 hash of a file's contents, given its path. ...
...n path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for that interface includes an example of calculating an md5 hash of a file's contents, given its path. ...
...And 11 more matches
Promises - Archive of obsolete content
it is also available for use off-main-thread in workers as a synchron...
...es 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) re
turn; timestamp = info.lastmodificationdate; // read the file as a utf-8 string, parse as json. let config = json.parse( yield os.file.read(configpath, { encoding: "utf-8" })); let files = []; // get the directory contents from a list of directories. for (let dir of config.directories) { // iterate over the contents of the directory. let iter = new os...
...ure 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. ...
...And 11 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
as to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. in order to make it still possible to script plugins, some changes have been made to the mozilla code. the changes allow to make existing 4.x plugins scriptable with only minor modifications in their code. the present document describes the steps of what should be done to the plugin code to
turn it scriptable again. what's in the mozilla code? a couple of lines have been added to the dom code asking a plugin to re
turn a scriptable iid and a pointer to a scriptable instance object. the old plugin api call npp_getvalue is used to retrieve this information from the plugin. so the plugin project should be aware of two new additions to nppvariable enumeration type which are now defined in npa...
... necessary nsiclassinfo method stubs // and to set flags used by the security system class nsclassinfomixin : public nsiclassinfo { // these flags are used by the dom and security systems to signal that // javascript callers are allowed to call this object's scritable methods. ...
...the dom and security systems to signal that // javascript callers are allowed to call this object's scritable methods. ns_imethod getflags(pruint32 *aflags) {*aflags = nsiclassinfo::plugin_object | nsiclassinfo::dom_object; re
turn ns_ok;} ns_imethod getimplementationlanguage(pruint32 *aimplementationlanguage) {*aimplementationlanguage = nsiprogramminglanguage::cplusplus; re
turn ns_ok;} // the rest of the methods can safely re
turn error codes... ...
...And 11 more matches
Client-Server Overview - Learn web development
browser with an http response message. the response contains an http response status code indicating whether or not the request succeeded (e.g. "200 ok" for success, "404 not found" if the resource cannot be found, "403 forbidden" if the user isn't authorised to see the resource, etc). the body of a successful response to a get request would contain the requested resource. when an html page is re
turned it is rendered by the web browser. as part of processing the browser may discover links to other resources (e.g. an html page usually references javascript and css pages), and will send separate http requests to download these files. both static and dynamic websites (discussed in the following sections) use exactly the same communication protocol/patterns. get request/response example you ca...
...line includes the response code 200 ok, which tells us that the request succeeded. we can see that the response is text/html formatted (content-type). we can also see that it uses the utf-8 character set (content-type: text/html; charset=utf-8). the head also tells us how big it is (content-length: 41823). at the end of the message we see the body content — which contains the actual html re
turned by the request. http/1.1 200 ok server: apache x-backend-server: developer1.webapp.scl3.mozilla.com vary: accept,cookie, accept-encoding content-type: text/html; charset=utf-8 date: wed, 07 sep 2016 00:11:31 gmt keep-alive: timeout=5, max=999 connection: keep-alive x-frame-options: deny allow: get x-cache-info: caching content-length: 41823 <!doctype html> <html lang="en-us" dir="ltr" class...
... using web sniffers (e.g. websniffer) or browser extensions like httpfox. you can try this yourself. use any of the linked tools, and then navigate through a site and edit profile information to see the different requests and responses. most modern browsers also have tools that monitor network requests (for example, the network monitor tool in firefox). static sites a static site is one that re
turns the same hard coded content from the server whenever a particular resource is requested. so for example if you have a page about a product at /static/myproduct1.html, this same page will be re
turned to every user. if you add another similar product to your site you will need to add another page (e.g. myproduct2.html) and so on. this can start to get really inefficient — what happens when you g...
...And 11 more matches
Handling common accessibility problems - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross browser testing. objective: to be able to diagnose common accessibility problems, and use appropriate tools and techniques to fix them. ...
...t. i'd love people to be able to find this content!</p> <h2>my 2nd subheading</h2> <p>this is the second subsection of my content. i think it is more interesting than the last one.</p> in addition, your content should make logical sense in its source order — you can always place it where you want using css later on, but you should get the source order right to start with. as a test, you can
turn off a site's css and see how understandable it is without it. you could do this manually by just removing the css from your code, but the easiest way is to use browser features, for example: firefox: select view > page style > no style from the main menu. safari: select develop > disable styles from the main menu (to enable the develop menu, choose safari > preferences > advanced > show devel...
...html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/re
turn to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the <select> element can have its options displayed and cycled between using the up and down arrow keys). note that different browsers may have different keyboard control options av...
...And 11 more matches
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. ...
...ways handle, forward, or report errors (rejection reasons). if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code. see handling errors and common pitfalls below. documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. for example, the os.file.exists function re
turns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unless otherwise specified. method overview promise then([optional] function onfulfill, [optional] function onreject); promise catch([optional] function onrejec...
...catch([optional] function onreject); constructor creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state. new promise(executor); parameters executor this function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not re
turn until the executor has completed. the resolving functions can be used at any time, before or after the executor has completed, to control the final state of the promise. if the executor throws an exception, its value will be passed to the reject resolving function. resolving functions resolve() fulfills the associated promise with the specified value, or propagates the state of an existing ...
...And 11 more matches
PromiseWorker.jsm
summary a promiseworker is a chromeworker except instead of calling postmessage() to send a message, you call post(), which re
turns a promise. javascript files imported into the worker scope and main thread scope which allows posting to the worker and receiving in the form of a promise. like chromeworker objects, promiseworker is mostly used for js-ctypes but it is not limited to that. there is no xpcom access, similar to chromeworker. this answers the question "when should i use a promiseworker?", and the answer is, whenever you would normally use a chromeworker, but want postmessage to re
turn promises. the promiseworker object is used to deliver all of the os.file functionality to the main thread. here is the test case from firefox codebase: mozilla dxr :: test_promise.js. promiseworker ...
... in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). let worker = new promiseworker.abstractworker() worker.dispatch = function(method, args = []) { // dispatch a call to method `method` with args `args` re
turn self[method](...args); }; worker.postmessage = function(...args) { // post a message to the main thread self.postmessage(...args); }; worker.close = function() { // close the worker self.close(); }; worker.log = function(...args) { // log (or discard) messages (optional) dump('worker: ' + args.join(' ') + '\n'); }; // connect it to message port. self.addeventlistener('message', msg =...
...objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from, and it becomes available only to the worker it was sent to. only messageport and arraybuffer objects can be transferred. to learn more on how to achieve this see the section in this article titled transferring special data from main thread to worker. re
turns a promise object. transferring special data from main thread to worker the regular rules of workers apply; special data of messageport and arraybuffer objects can be transferred as of firefox 40. there are two ways to transfer data. the first is with atransferlist argument and other with basepromiseworker.meta. both are done by the post function described above. atransferlist to transfer an...
...And 11 more matches
Mozilla DOM Hacking Guide
a jsfunction, a jsobject, a jsval, ... this means that when we use the dom from javascript, we pass arguments that have no type. however, since the dom is coded in c++, we expect to receive an argument of the correct type for our function. this is one of the jobs of xpconnect. xpconnect will "wrap" the argument in a wrapper that will be of the type expected by our c++ function. similarly, then re
turn type of the c++ function will be wrapped by xpconnect so that javascript can use it safely. when, in javascript, a client tries to access a dom object or a dom method on a dom object, the js engine asks xpconnect to search for the relevant c++ method to call. for example, when we ask for |document.getelementbyid("myid");|, xpconnect will find that |document| is a property of the window object, s...
...hen, in javascript, a client tries to access a dom object or a dom method on a dom object, the js engine asks xpconnect to search for the relevant c++ method to call. for example, when we ask for |document.getelementbyid("myid");|, xpconnect will find that |document| is a property of the window object, so it will look on the interface nsidomwindow, and it will find the getdocument() method. the re
turn value of getdocument() is a nsidomdocument. so xpconnect will then try to find a method named getelementbyid() on the nsidomdocument interface. and indeed it will find it, and thus call it. this is the schema used most of the time when using w3c dom objects and methods. it is however different for some dom level 0 objects and methods. i'll take two very different examples. the first one is the w...
... of. let's begin with the public interface. constructor: it is called for each created helper class through the member initialization list. it simply initializes the mid data member with the aid argument. the nsixpcscriptable, nsisupports, and nsiclassinfo member functions, declared with ns_decl_x macros. static nsiclassinfo* getclassinfoinstance(nsdomclassinfoid aid): this helper method re
turns a non-refcounted nsiclassinfo pointer to an instance of the helper class corresponding to the id passed in. the implementation is detailed in section 1.6. static nsiclassinfo* getclassinfoinstance(nsdomclassinfodata* adata);: this helper method re
turns a non-refcounted nsiclassinfo pointer to an instance of the helper class corresponding to the data passed in. the implementation is detailed i...
...And 11 more matches
Secure Development Guidelines
ointer (eip) points to register being executed; can’t be modified directly introduction: gaining control (2) eip is modified using call or jump instructions attacks usually rely on obtaining control over the eip otherwise the attacker can try to control memory pointed to by an existing function pointer a vulnerability is required to modify the eip or sensitive memory saved re
turn addr or function pointer get altered introduction: gaining control (3) common issues used to gain control buffer overflows format string bugs integer overflows/underflows writing secure code: input validation input validation most vulnerabilities are a result of un-validated input always perform input validation could save you without knowing it examples: if i...
... with a sql string sql is a language used to interact with databases code injection attack that is similar to xss but targeted at sql rather than html and javascript if input is mixed with sql, it could itself become an sql instruction and be used to: query data from the database (passwords) insert value into the database (a user account) change application logic based on results re
turned by the database sql injection: example snprintf(str, sizeof(str), "select * from account where name ='%s'", name); sqlite3_exec(db, str, null, null, null); sql injection: prevention use parameterized queries insert a marker for every piece of dynamic content so data does not get mixed with sql instructions example: sqlite3_stmt *stmt; char *str = "select * from acco...
...short -32768 - +32767 unsigned short 0 - +65535 32 signed int -2147483648 - +2147483647 unsigned int 0 - +4294967295 64 signed long long -9223372036854775808 - +9223372036854775807 unsigned long long 0 - +18446744073709551615 int vuln_funct(int size) { char buf[1024]; if (size > sizeof(buf) - 1) re
turn -1; } signedness issues: don’t mix signed and unsigned integers use unsigned integers for sizes, offsets, and indexes casting and truncation example: void vuln_funct() { u_int32_t size1 = 0xffffffff; u_int16_t size2 = size1; void *ptr = malloc(size2); if (!ptr) exit(exit_failure); memcpy(ptr, user_data, size1); } casting issues: sign extension exampl...
...And 11 more matches
XPCOM array guide
mponentmanager.createinstance() and the contract id "@mozilla.org/array;1". the created array implements nsimutablearray and nsiarray. since nsimutablearray derives from nsiarray, the resulting array can be cast to a read-only array. c++ example void getlist(nsiarray** aresult) { nscomptr<nsimutablearray> array = do_createinstance(ns_array_contractid); // append some elements ... ...
...access to specific elements is through queryelementat, which is similar to queryinterface, but it takes a specific index. ...
...access to specific elements is through queryelementat, which is similar to queryinterface, but it takes a specific index. ...
...And 11 more matches
Mozilla internal string guide
avoided. iterators because mozilla strings are always a single buffer, iteration over the characters in the string is done using raw pointers: /** * find whether there is a tab character in `data` */ bool hastab(const nsastring& data) { const char16_t* cur = data.beginreading(); const char16_t* end = data.endreading(); for (; cur < end; ++cur) { if (char16_t('\t') == *cur) re
turn true; } re
turn false; } note that `end` points to the character after the end of the string buffer. it should never be dereferenced. writing to a mutable string is also simple: /** * replace every tab character in `data` with a space. */ void replacetabs(nsastring& data) { char16_t* cur = data.beginwriting(); char16_t* end = data.endwriting(); for (; cur < end; ++cur) { if (ch...
...) takes four arguments: the new capacity (which may be rounded up), the number of code units at the beginning of the string to preserve (typically the old logical length), a boolean indicating whether reallocating a smaller buffer is ok if the requested capacity would fit in a buffer that's smaller than current one, and a reference to an nsresult for indicating failure on oom. (don't access the re
turn value if the nsresult indicates failure. unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() re
turns a mozilla::bulkwritehandle<t>, where t is either char or char16_t. the actual writes are performed through this handle. you must not access the string except via the handle until you call finish() on the handle in the success case or you let the handle go out of sc...
...ngth of the buffer. the buffer exposed via these methods includes the prefix that you may have requested to be preserved. it's up to you to skip past it so as to not overwrite it. if there's a need to request a different capacity before you are ready to call finish(), you can call restartbulkwrite() on the handle. it takes three arguments that match the first three arguments of bulkwrite(). it re
turns mozilla::result<mozilla::ok, nsresult> to indicate success or oom. calling restartbulkwrite() invalidates previously-obtained span, raw pointer or length. once you are done writing, call finish(). it takes two arguments: the new logical length of the string (which must not exceed the capacity retuned by the length() method of the handle) and a boolean indicating whether it's ok to attempt to re...
...And 11 more matches
NS_ConvertUTF16toUTF8
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
NS_LossyConvertUTF16toASCII
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsAdoptingCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsCAutoString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. ...
...d print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
...- source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsDependentCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsFixedCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsPromiseFlatCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
nsXPIDLCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 11 more matches
imgIContainer
frameindex unsigned long the index of the current frame that would be drawn if the image was to be drawn now. read only. obsolete since gecko 2.0 currentframeisopaque boolean whether the current frame is opaque; that is, needs the background painted behind it. read only. height print32 the height of the container rectangle. in the case of any error, zero is re
turned, and an exception will be thrown. read only. loopcount long number of times to loop the image. note: -1 means forever. obsolete since gecko 2.0 numframes unsigned long the total number of frames in this image. read only. obsolete since gecko 2.0 preferredalphachannelformat gfx_format read only. obsolete since gecko 1.9.2 type uns...
...es unsigned long the total number of frames in this image. read only. obsolete since gecko 2.0 preferredalphachannelformat gfx_format read only. obsolete since gecko 1.9.2 type unsigned short the type of this image (one of the type_* values above). read only. width print32 the width of the container rectangle. in the case of any error, zero is re
turned, and an exception will be thrown. read only. constants constant value description type_raster 0 enumerated values for the 'type' attribute (below). type_vector 1 flag_none 0x0 flags for imgicontainer operations. meanings: flag_none: lack of flags. flag_sync_decode: forces synchronous/non-progressive decode of a...
... read only. constants constant value description type_raster 0 enumerated values for the 'type' attribute (below). type_vector 1 flag_none 0x0 flags for imgicontainer operations. meanings: flag_none: lack of flags. flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call re
turns. it is an error to pass this flag from a call stack that originates in a decoder (that is, from a decoder observer event). flag_decode_no_premultiply_alpha: do not premultiply alpha if it is not already premultiplied in the image data. flag_decode_no_colorspace_conversion: do not do any colorspace conversion; ignore any embedded profiles, and do not convert to any particular destination ...
...And 11 more matches
inIDOMUtils
onstant value description exclude_shorthands (1<<0) include_aliases (1<<1) content state flags the content state flags are used in a bitmask. ...
...:active 2 :focus 4 :hover 8 :-moz-drag-over 16 :target 1<<29 :-moz-focusring methods getbindingurls() re
turns an array of nsiuri objects representing the current xml binding for the specified element. nsiarray getbindingurls( in nsidomelement aelement ); parameters aelement a dom element to retrieve the bindings of. re
turn value an array of nsiuri objects representing the current xbl binding (if any) for the element and its hierarchy of base bindings. getchildrenfornode() re
turns a list of dom nodes that are children of the specified node. nsidomnodelist getchildrenfornode( in nsidomnode anode, in boolean ashowinganonymouscontent ); parameters anode a dom node for which to retrieve the style nodes. a...
...r the element and its hierarchy of base bindings. getchildrenfornode() re
turns a list of dom nodes that are children of the specified node. nsidomnodelist getchildrenfornode( in nsidomnode anode, in boolean ashowinganonymouscontent ); parameters anode a dom node for which to retrieve the style nodes. ashowinganonymouscontent whether you are interested in the xbl flattened tree. re
turn value a dom nodelist of the child nodes. if you have requested anonymous content, then if the element has an xbl binding then this will be the binding's anonymous nodes, otherwise if the element is itself an anonymous node containing an insertion point then this will be a list combining the element's explicit children from its binding parent's anonymous nodes and any children inserted as a resul...
...And 11 more matches
nsIAccessibleText
ng endindex, in unsigned long coordinatetype, in long x, in long y); void setselectionbounds(in long selectionnum, in long startoffset, in long endoffset); attributes attribute type description caretoffset long the current current caret offset. if set < 0 then caret will be placed at the end of the text. charactercount long read only. defaulttextattributes nsipersistentproperties re
turn the text attributes that apply to the entire accessible. read only. selectioncount long read only. constants text offset constants constant value description text_offset_end_of_text -1 will be treated as the equal to the end of the text. text_offset_caret -2 will be treated as the caret position. text boundary constants constant value description boundary_char 0 boundary...
...e description coord_type_screen 0 coord_type_window 1 methods addselection() void addselection( in long startoffset, in long endoffset ); parameters startoffset endoffset getattributerange() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) get the accessible and start/end offsets around the given offset. this accessible get re
turn the dom node and layout frame with the uniform attributes for this range of text. nsiaccessible getattributerange( in long offset, out long rangestartoffset, out long rangeendoffset ); parameters offset rangestartoffset rangeendoffset re
turn value getcharacteratoffset() it would be better to re
turn an unsigned long here, to allow unicode chars > 16 bits. wchar getcharacteratoffset( ...
...form attributes for this range of text. nsiaccessible getattributerange( in long offset, out long rangestartoffset, out long rangeendoffset ); parameters offset rangestartoffset rangeendoffset re
turn value getcharacteratoffset() it would be better to re
turn an unsigned long here, to allow unicode chars > 16 bits. wchar getcharacteratoffset( in long offset ); parameters offset re
turn value getcharacterextents() re
turns the bounding box of the specified position. the virtual character after the last character of the represented text, that is the one at position length is a special case. it represents the current input position and will therefore typically be queried by at more often than other positions. because it does not represent an existing character its bounding box is ...
...And 11 more matches
nsIFile
each element in the enumeration is an nsifile. read only. exceptions thrown ns_error_file_not_directory indicates that this nsifile does not reference a directory. diskspaceavailable print64 the number of bytes available to non-superuser on the disk volume containing the nsifile. read only. filesi...
...ute is a platform-specific file path. read only. native code only! nativetarget acstring this attribute exposes the full target of the nsifile - the full path with any symbolic links dereferenced. [native character encoding variant] the value of this attribute is a platform-specific file path. read only. ...
... changing the permissions of a nsifile operates on the underlying filesystem. ...
...And 11 more matches
Getting Started Guide
unt goes to zero, the interface may delete itself. clients are expected to keep this reference count accurate by incrementing it when they acquire a reference to the interface, and decrementing it before they let go. to facilitate this, all interfaces inherit from an abstract base class that provides the member functions addref, and release. a rule of xpcom is that any function that creates or re
turns an interface pointer will have already addrefed it. the caller can then hold onto the reference indefinitely, calling release when it no longer needs it. when the last pointer to an interface is released, the interface (and consequently, typically the underlying object) will delete itself. as long as there is an outstanding addref against the interface, it continues to exist. if you forget to ca...
...rison 1, below). you don't need an owning reference when the object is passed in as a parameter, and you don't need to keep it any longer than the scope of this function; the object's lifetime is known to contain yours in some well defined way, e.g., in the nodes of a tree, parent nodes keep owning references to their children, children need not keep owning references to their parents. it
turns out that reference counting by hand is hard for programmers to get right. it may sound simple, but in practice it's very easy to forget to release at the appropriate moment. or to addref too many or too few times. how does nscomptr help? nscomptr manages addref, release, and other red-tape for you. an nscomptr looks and acts as much like a raw xpcom interface pointer as c allows, but it knows ...
...uctor to ensure that mfooptr is initially set to null (or some other reasonable value). nscomptr helps you write code that is leak-proof, exception safe, and significantly less verbose than you would with raw xpcom interface pointers. with nscomptr, you may never have to call addref, release, or queryinterface by hand. you still have to understand xpcom. you still have to know which functions re
turn interface pointers that have already been addrefed and which don't. you still have to ensure your program logic doesn't produce circularly referencing garbage. nscomptr is not a panacea. it is, however, helpful, easy to use, well-tested, and polite. it doesn't require that a function author cooperate with you, nor does your use force others to use it. using nscomptr the basics in most cases, y...
...And 11 more matches
Reference Manual
any, and addref the new. at its own destructor time it must release as well. nscomptr only does exactly the work you would have done, if you always remembered to do the right thing. safety features type safeguards it is an invariant of nscomptr that it holds the xpcom-correct interface pointer for it's underlying type. for example, an nscomptr<nsifoo> will always hold the pointer that would be re
turned by queryinterface, when querying an xpcom object for its nsifoo interface. in debug builds, if you subvert this invariant with one of the assignment forms that doesn't call queryinterface, nscomptr will assert at runtime in the bad assignment. // given two un-related interfaces |nsifoo| and |nsibar|... nsibar* bar = ...; // ... nscomptr<nsifoo> foo = bar; // ns_asser...
...foo> foo; // note: default initialized to |0| foo->dosomething(); // ns_precondition: "you can't dereference a null nscomptr with operator->()" a similar precondition intervenes on behalf of operator*. reference-counting safeguards all of the operations that extract the underlying raw pointer out of an nscomptr use a c trick to implement another safety feature. the pointer re
turned cannot be addrefed, released, or deleted. nscomptr<nsifoo> foo = ...; foo->addref(); // error: |addref| is private delete foo.get(); // error: |operator delete| is private ns_release(foo); // error: |release| is private of course, the most important safety feature provided by nscomptr is that it addrefs and releases automatically at the appropria...
...ove, illegal by making operator& private. see bug 59414. implementation details and debugging machinery although it is a class, nscomptr has no virtual methods, and therefore, no vtable or vptr. because a few key routines are factored out into a common non-template base class, the actual underlying pointer is stored as an nsisupports* (except in debug builds where nscap_feature_debug_ptr_types is
turned on). it is because of these factored routines that nscomptr users must link with the xpcom library. when nscap_feature_debug_ptr_types is
turned on, instead of holding its underlying pointer in a variable of type nsisupports*, the nscomptr holds it in a pointer matching the underlying type. this allows source level debuggers to more easily "follow" the pointer. however, the routines that would ...
...And 11 more matches
UInt64
eed) to use data represented using a 64-bit data type. you use the uint64 object to create and manipulate 64-bit unsigned integers. note: it's important to note that the 64-bit integer objects created by uint64 are not uint64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the uint64 object. see 64-bit integers for details. syntax creates and re
turns a new 64-bit unsigned integer. uint64 uint64( value ); parameters value the value to assign the new 64-bit unsigned integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "...
...er 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. re
turn value a new object representing the specified value. exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point num...
...epresented as a 64-bit integer. method overview number compare(a, b); number hi(a); uint64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. re
turn value the re
turned value is -1 if a < b, 0 if a == b, and 1 if a > b. exceptions thrown typeerror one or both of the specified values is not a 64-bit integer (either signed or unsigned). hi() re
turns the high 32 bits of the specified value. number hi( num ); parameters num the value whose high 32 bits are to be re
turned. re
turn value the high 32 bits of num are re
turned. th...
...And 11 more matches
Background audio processing using AudioWorklet - Web APIs
ltiple modules from over the network or even the user's local disk. basic code framework the barest framework of an audio processor class looks like this: class myaudioprocessor extends audioworkletprocessor { constructor() { super(); } process(inputlist, outputlist, parameters) { /* using the inputs (or not, as needed), write the output into each of the outputs */ re
turn true; } }; registerprocessor("my-audio-processor", myaudioprocessor); after the implementation of the processor comes a call to the global function registerprocessor(), which is only available within the scope of the audio context's audioworklet, which is the invoker of the processor script as a result of your call to audioworklet.addmodule(). this call to registerprocessor() registers your ...
...nd may in fact vary depending on circumstances, so you should always check the array's length rather than assuming a particular size. it is, however, guaranteed that the inputs and outputs will have the same block length. each input can have a number of channels. a mono input has a single channel; stereo input has two channels. surround sound might have six or more channels. so each input is, in
turn, an array of channels. that is, an array of float32array objects. then, there can be multiple inputs, so the inputlist is an array of arrays of float32array objects. each input may have a different number of channels, and each channel has its own array of samples. thus, given the input list inputlist: const numberofinputs = inputlist.length; const firstinput = inputlist[0]; const firstinputch...
...the same check is performed when determining how many channels to process in the current input; we only process as many as there are room for in the destination output. this av...
...And 11 more matches
Using Web Workers - Web APIs
ction to using web workers. web workers api a worker is an object created using a constructor (e.g. worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. thus, using the window shortcut to get the current global scope (instead of self) within a worker will re
turn an error. the worker context is represented by a dedicatedworkerglobalscope object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use sharedworkerglobalscope). a dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. note: see the web workers api landing pa...
...indexeddb. see functions and classes available to workers for more details. data is sent between workers and the main thread via a system of messages — both sides send their messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data attribute.) the data is copied rather than shared. workers may, in
turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the exception that the responsexml and channel attributes on xmlhttprequest always re
turn null. dedicated workers as mentioned above, a dedicated worker is only accessible by the script that called it. in this section we'll discuss ...
... this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. ...
...And 11 more matches
Border-radius generator - CSS: Cascading Style Sheets
nput.setattribute('type', 'text'); input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { var value = parseint(e.target.value); if (isnan(value) === true) setvalue(obj.topic, obj.value); else setvalue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + obj.unit; }); re
turn input; } var slidercomponent = function slidercomponent(obj, sign) { var slider = document.createelement('div'); var startx = null; var start_value = 0; slider.addeventlistener("click", function(e) { setvalue(obj.topic, obj.value + obj.step * sign); }); slider.addeventlistener("mousedown", function(e) { startx = e.clientx; start_value = obj.value; document.body.style.
...er("mouseup", function(e) { document.removeeventlistener("mousemove", slidermotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }); var slidermotion = function slidermotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientx - startx) / obj.sensivity | 0; var value = delta * obj.step + start_value; setvalue(obj.topic, value); } re
turn slider; } var inputslider = function(node) { var min = node.getattribute('data-min') | 0; var max = node.getattribute('data-max') | 0; var step = node.getattribute('data-step') | 0; var value = node.getattribute('data-value') | 0; var topic = node.getattribute('data-topic'); var unit = node.getattribute('data-unit'); var name = node.getattribute('data-info'); var sensivity =...
...ame; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); node.classname = 'ui-input-slider ui-input-slider-container'; this.input = input; sliders[topic] = this; setvalue(topic, value); } var setvalue = function setvalue(topic, value, send_notify) { var slider = sliders[topic]; if (slider === undefined) re
turn; if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setattribute('data-value', value); if (send_notify !== undefined && send_notify === false) { slider.input.value = value + slider.unit; re
turn; } notify.call(slider); } var setmax = function setmax(topic, value) { var slider = sliders[topic]; if ...
...And 11 more matches
Array.prototype.sort() - JavaScript
the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of utf-16 code units values. the time and space complexity of the sort cannot be guaranteed as it depends on the implementation. 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 arr.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. ...
...tive-examples and send us a pull request. syntax arr.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. if omitted, the array elements are converted to strings, then sorted according to each character's unicode code point value. firstel the first element for comparison. secondel the second element for comparison. re
turn value the sorted array. note that the array is sorted in place, and no copy is made. description if comparefunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in utf-16 code units order. for example, "banana" comes before "cherry". in a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes...
...te : in utf-16, unicode characters above \uffff are encoded as two surrogate code units, of the range \ud800-\udfff. the value of each code unit is taken separately into account for the comparison. thus the character formed by the surrogate pair \ud655\ude55 will be sorted before the character \uff3a. ...
...And 11 more matches
BigInt64Array - JavaScript
orm byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). constructor bigint64array() creates a new bigint64array object. static properties bigint64array.bytes_per_element re
turns a number value of the element size. 8 in the case of a bigint64array. bigint64array.name re
turns the string value of the constructor name. in the case of the bigint64array type, this is "bigint64array". static methods bigint64array.from() creates a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a varia...
...string value of the constructor name. in the case of the bigint64array type, this is "bigint64array". static methods bigint64array.from() creates a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a variable number of arguments. see also array.of(). ...
...es a new bigint64array from an array-like or iterable object. see also array.from(). bigint64array.of() creates a new bigint64array with a variable number of arguments. see also array.of(). instance properties bigint64array.prototype.buffer re
turns the arraybuffer referenced by the bigint64array. this is fixed at construction time and thus read only. bigint64array.prototype.bytelength re
turns the length (in bytes) of the bigint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. ...
...And 11 more matches
Uint8ClampedArray - JavaScript
ead; if you specify a non-integer, the nearest integer will be set. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint8clampedarray() creates a new uint8clampedarray object. static properties uint8clampedarray.bytes_per_element re
turns a number value of the element size. 1 in the case of an uint8clampedarray. uint8clampedarray.name re
turns the string value of the constructor name. in the case of the uint8clampedarray type: "uint8clampedarray". static methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8...
...constructor name. in the case of the uint8clampedarray type: "uint8clampedarray". static methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments. see also array.of(). ...
...lampedarray from an array-like or iterable object. see also array.from(). uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments. see also array.of(). instance properties uint8clampedarray.prototype.buffer re
turns the arraybuffer referenced by the uint8clampedarray fixed at construction time and thus read only. uint8clampedarray.prototype.bytelength re
turns the length (in bytes) of the uint8clampedarray from the start of its arraybuffer. fixed at construction time and thus read only. ...
...And 11 more matches
tooltip - Archive of obsolete content
1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. re
turning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. page type: boolean setting the page attribute to true will result in the tooltip being filled automatically as appropriate for a browser content area tool...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, tr...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) ...
...And 10 more matches
Index - Learn web development
e way through your javascript learning, so it's a good idea to get this out of the way now. if you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short. 79 handling text — strings in javascript article, beginner, codingscripting, guide, javascript, join, quotes, concatenation, l10n:priority, strings next, we'll
turn our attention to strings — this is what pieces of text are called in programming. in this article, we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in strings, and joining strings together. 80 silly story generator arrays, assessment, beginner, codingscripting, javascript, learn, nu...
... article, beginner, codingscripting, debugging, developer tools, error, javascript, learn, tutorial, console.log, l10n:priority so there we have it, the basics of figuring out errors in simple javascript programs. ...
...you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. ...
...And 10 more matches
A first splash into JavaScript - Learn web development
y: sans-serif; } body { width: 50%; max-width: 800px; min-width: 480px; margin: 0 auto; } .lastresult { color: white; padding: 3px; } </style> </head> <body> <h1>number guessing game</h1> <p>we have selected a random number between 1 and 100. see if you can guess it in 10
turns or fewer. we'll tell you if your guess was too high or too low.</p> <div class="form"> <label for="guessfield">enter a guess: </label><input type="text" id="guessfield" class="guessfield"> <input type="submit" value="submit guess" class="guesssubmit"> </div> <div class="resultparas"> <p class="guesses"></p> <p class="lastresult"></p> <p class="loworhi"></p> </...
....floor(math.random() * 100) + 1; } </script> </body> </html> have a go at playing it — familiarize yourself with the game before you move on. let's imagine your boss has given you the following brief for creating this game: i want you to create a simple guess the number type game. it should choose a random number between 1 and 100, then challenge the player to guess the number in 10
turns. after each
turn the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. it should also tell the player what numbers they previously guessed. the game will end once the player guesses correctly, or once they run out of
turns. when the game ends, the player should be given an option to start playing again. upon looking at this brie...
...start it on 1. provide the player with a way to guess what the number is. once a guess has been submitted first record it somewhere so the user can see their previous guesses. next, check whether it is the correct number. if it is correct: display congratulations message. ...
...And 10 more matches
Getting started with React - Learn web development
able module that renders a part of our app. these parts can be big or small, but they are usually clearly defined: they serve a single, obvious purpose. let's open src/app.js, since our browser is prompting us to edit it. this file contains our first component, app, and a few other lines of code: import react from 'react'; import logo from './logo.svg'; import './app.css'; function app() { re
turn ( <div classname="app"> <header classname="app-header"> <img src={logo} classname="app-logo" alt="logo" /> <p> edit <code>src/app.js</code> and save to reload. </p> <a classname="app-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > learn react </a> ...
..., and an export statement at the bottom. most react components follow this pattern. import statements the import statements at the top of the file allow app.js to use code that has been defined elsewhere. let's look at these statements more closely. import react from 'react'; import logo from './logo.svg'; import './app.css'; the first statement imports the react library itself. because react
turns the jsx we write into react.createelement(), all react components must import the react module. if you skip this step, your application will produce an error. the second statement imports a logo from './logo.svg'. note the use of ./ at the beginning of the path, and the .svg extension at the end — these tell us that the file is local and that it is not a javascript file. indeed, the logo.svg ...
...unction named app. whereas most of the javascript community prefers camel-case names like helloworld, react components use pascal-case variable names, like helloworld, to make it clear that a given jsx element is a react component, and not a regular html tag. if you were to rename the app function to app, your browser would show you an error. let's look at app more closely. function app() { re
turn ( <div classname="app"> <header classname="app-header"> <img src={logo} classname="app-logo" alt="logo" /> <p> edit <code>src/app.js</code> and save to reload. </p> <a classname="app-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > learn react </a> ...
...And 10 more matches
Extending a Protocol
, as we will need to convert it to utf-8 (using nscstring) to send it to the parent process. now let's implement the method in ./dom/base/navigator.cpp - we add a little bit of error boilerplate stuff, as is customary: already_addrefed<promise> navigator::echo(const nsastring& astring, errorresult& arv) { if (!mwindow || !mwindow->getdocshell()) { arv.throw(ns_error_unexpected); re
turn nullptr; } refptr<promise> echopromise = promise::create(mwindow->asglobal(), arv); if (ns_warn_if(arv.failed())) { re
turn nullptr; } // message passing magic will happen here! re
turn echopromise.forget(); } ok, let's ./mach build and make sure everything is compiling ok. once it's compiled, ./mach run and you should be able to spin up the developer console and type: naviga...
...our goal is now to get that to settle with the value we sent in. ipdl basics while you are compiling, let's cover some ipdl basics. ...
...ng 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) re
turns (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; - we include pwindowglobal, because it's going to manage the protocol for us. async refcounte...
...And 10 more matches
Dict.jsm
ct adefault); boolean has(string akey); array listitems(); array listkeys(); array listvalues(); void set(string akey, object avalue); string tojson(); string tostring(); properties attribute type description count number the number of items in the dictionary. items iterator re
turns an iterator over all of the items in the dictionary; each item is re
turned as a pair (a two-element array) with the first element being the key and the second being the value. note: the order in which items are re
turned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. keys ite...
...er all of the items in the dictionary; each item is re
turned as a pair (a two-element array) with the first element being the key and the second being the value. note: the order in which items are re
turned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. keys iterator re
turns an iterator over all the keys in the dictionary. note: the order in which items are re
turned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. values iterator re
turns an iterator over all the values in the dictionary. ...
... re
turns an iterator over all the keys in the dictionary. note: the order in which items are re
turned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. values iterator re
turns an iterator over all the values in the dictionary. note: the order in which items are re
turned is arbitrary, and may change without notice. in addition, if the dictionary changes during iteration, no guarantees are made as to what will happen. constructor dict() creates and re
turns a new dictionary object. dict dict(); dict dict( object initalkeysandvalues ); parameters initialkeysandvalues optional a object containing key/value pairs with which to initialize the d...
...And 10 more matches
Places Developer Guide
vemark title", // the title of the livemark siteuri, // the uri of the site. a nsiuri object. feeduri, // the uri of the actual feed. a nsiuri object. bookmarks.default_index); // the position of the livemark in its parent folder. ...
...euri, // the uri of the site. a nsiuri object. feeduri, // the uri of the actual feed. a nsiuri object. bookmarks.default_index); // the position of the livemark in its parent folder. ...
... // the uri of the actual feed. a nsiuri object. bookmarks.default_index); // the position of the livemark in its parent folder. accessing bookmarks and related items accessing item properties for all items: string getitemtitle(aitemid) - re
turns an item's title int64 getitemindex(aitemid) - re
turns an item's position in it's parent folder prtime getitemtype(aitemid) - re
turns the type of an item (bookmark, folder, separator) prtime getitemdateadded(aitemid) - re
turns the time in microseconds that an item was added prtime getitemlastmodified(aitemid) - re
turns the time in microseconds that an item was last modified int64 getfolderidforitem(aitemid) - re
turns the id of the folder containing the given item. string getitemguid(aitemid) obsolete since gecko 14.0 -...
...And 10 more matches
An Overview of XPCOM
shown below. see a reference implementation of queryinterface for detailed information. ...
...he reference count to 0 sample::sample() : mrefcnt(0) { } sample::~sample() { } // typical, generic implementation of qi ns_imethodimp sample::queryinterface(const nsiid &aiid, void **aresult) { if (!aresult) { re
turn ns_error_null_pointer; } *aresult = null; if (aiid.equals(kisupportsiid)) { *aresult = (void *) this; } if (!*aresult) { re
turn ns_error_no_interface; } // add a reference addref(); re
turn ns_ok; } ns_imethodimp_(nsrefcnt) sample::addref() { re
turn ++mrefcnt; } ns_imethodimp_(nsrefcnt) sample::release() { if (--mrefcnt == 0) { delete this; re
turn 0; } // optional: re
turn the reference count re
turn mrefcnt; } object interface discovery inheritance is another very important topic in object ori...
...to be cast to a circle. but enabling exceptions and rtti may not be an option because of performance overhead and compatibility on many platforms, so xpcom does things differently. exceptions in xpcom c++ exceptions are not supported directly by xpcom. instead all exceptions must be handled within a given component, before crossing interface boundaries. in xpcom, all interface methods should re
turn an nsresult error value (see the xpcom api reference for a listing of these error codes). these error code results become the "exceptions" that xpcom handles. instead of leveraging c++ rtti, xpcom uses the special queryinterface method that casts the object to the right interface if that interface is supported. every interface is assigned an identifier that gets generated from a tool commonly ...
...And 10 more matches
nsIAccessibleTable
total number of selected columns. read only. note: renamed from selectedcolumnscount in gecko 1.9.2 selectedrowcount unsigned long the total number of selected rows. read only. note: renamed from selectedrowscount in gecko 1.9.2 summary astring the summary description for the table. for example, @summary attribute on html:table element. read only. methods re
turn the accessible object at the specified row and column in the table. if both row and column index are valid then the corresponding accessible object is re
turned that represents the requested cell regardless of whether the cell is currently visible (on the screen). nsiaccessible getcellat( in long rowindex, in long columnindex ); parameters rowindex the row index of the cell. columninde...
...ed row and column in the table. if both row and column index are valid then the corresponding accessible object is re
turned that represents the requested cell regardless of whether the cell is currently visible (on the screen). nsiaccessible getcellat( in long rowindex, in long columnindex ); parameters rowindex the row index of the cell. columnindex the column index of the cell. re
turn value an nsiaccessible object. translate the given row and column indices into the corresponding cell index. long getcellindexat( in long rowindex, in long columnindex ); parameters rowindex the row index of the cell. columnindex the column index of the cell. re
turn value a cell index. getcolumndescription() re
turn the description text of the specified column in the table. as...
... index. long getcellindexat( in long rowindex, in long columnindex ); parameters rowindex the row index of the cell. columnindex the column index of the cell. re
turn value a cell index. getcolumndescription() re
turn the description text of the specified column in the table. astring getcolumndescription( in long columnindex ); parameters columnindex the column index. re
turn value the column description. getcolumnextentat() re
turn the number of columns occupied by the accessible cell at the specified row and column in the table. ...
...And 10 more matches
nsIMicrosummaryService
i generatoruri ); parameters generatoruri the uri of the resource providing the generator. createmicrosummary() create a microsummary for a given page uri and generator uri. nsimicrosummary createmicrosummary( in nsiuri pageuri, in nsiuri generatoruri ); parameters pageuri the uri of the page to be summarized. generatoruri the uri of the microsummary generator. ...
...i ); parameters generatoruri the uri of the resource providing the generator. createmicrosummary() create a microsummary for a given page uri and generator uri. nsimicrosummary createmicrosummary( in nsiuri pageuri, in nsiuri generatoruri ); parameters pageuri the uri of the page to be summarized. generatoruri the uri of the microsummary generator. re
turn value re
turns an nsimicrosummary for the given page and generator uris. getbookmarks() get the set of bookmarks with microsummaries. in the old rdf-based bookmarks datastore, bookmark ids are nsirdfresource objects. in the new places-based datastore, they are nsiuri objects. nsisimpleenumerator getbookmarks(); parameters none. re
turn value re
turns an nsisimpleenumerator enumeration of bookmark ids. getgenera...
...microsummary for the given page and generator uris. getbookmarks() get the set of bookmarks with microsummaries. in the old rdf-based bookmarks datastore, bookmark ids are nsirdfresource objects. in the new places-based datastore, they are nsiuri objects. nsisimpleenumerator getbookmarks(); parameters none. re
turn value re
turns an nsisimpleenumerator enumeration of bookmark ids. getgenerator() re
turn a microsummary generator for the given uri. ...
...And 10 more matches
nsIMsgDBHdr
headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. ...
... headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. ...
... headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. ...
...And 10 more matches
nsIPromptService
e dialog. if set to null the parent window will be nsiwindowwatcher.activewindow. adialogtitle text to appear in the title of the dialog. atext text to appear in the body of the dialog. acheckmsg text to appear with the checkbox. acheckstate contains the initial checked state of the checkbox when this method is called and the final checked state after this method re
turns. if you call this method from javascript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). see also the alertcheck_example. confirm() shows a dialog with ok and cancel buttons. boolean confirm( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext ); parameters aparent the parent window for the dialog. i...
...irm() shows a dialog with ok and cancel buttons. boolean confirm( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext ); parameters aparent the parent window for the dialog. if set to null the parent window will be nsiwindowwatcher.activewindow. adialogtitle text to appear in the title of the dialog. atext text to appear in the body of the dialog. re
turn value true for ok, false for cancel see also the confirm_example. confirmcheck() shows a dialog with ok and cancel buttons and a labeled checkbox. see also the confirm_example. boolean confirmcheck( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, in wstring acheckmsg, inout boolean acheckstate ); parameters aparent the parent window for the dialog. if...
...e dialog. if set to null the parent window will be nsiwindowwatcher.activewindow. adialogtitle text to appear in the title of the dialog. atext text to appear in the body of the dialog. acheckmsg text to appear with the checkbox. acheckstate contains the initial checked state of the checkbox when this method is called and the final checked state after this method re
turns. if you call this method from javascript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). re
turn value true for ok, false for cancel confirmex() puts up a dialog with up to 3 buttons and an optional, labeled checkbox. the buttons are numbered 0 - 2. the implementation can decide what order the buttons appear in, and it may no...
...And 10 more matches
Add to iPhoto
fstringref = new ctypes.pointertype("cfstringref"); now that we've declared the core type, we can declare the methods we use that work with cfstring objects. let's take a look at one of these. ...
... ctypes.voidptr_t, // allocator ctypes.jschar.ptr, // pointer to the unicode string ctypes.int32_t); // length of the string cfstringcreatewithcharacters() is used to create a new cfstring object using a unicode string as the source string, which is copied into the new cfstring object. it re
turns a cfstringref, which is a pointer to the new string, and accepts, as input, three parameters: an allocator, which is a pointer to a routine that will allocate the memory to contain the new object (we use the ctypes.voidptr_t type for this), a pointer to the unicode string to copy into the new string object (ctypes.jschar.ptr), and the length of the unicode string in characters. cfurl the cfurl...
...ervices routine we'll be using to launch iphoto and pass it the image to import uses cfurl for the file references. let's take a look at two of the routines declared here: this.cfurlcreatefromfilesystemrepresentation = this.lib.declare("cfurlcreatefromfilesystemrepresentation", ctypes.default_abi, this.cfurlref, // re
turns ctypes.voidptr_t, // input: allocator ctypes.unsigned_char.ptr, // input: pointer to string cfindex, // input: string length ctypes.bool) // input: isdirectory this method is used to convert a unix pathname into an url. the intere...
...And 10 more matches
Using Objective-C from js-ctypes
". it uses the default system voice and waits until the speaking is done. #import <appkit/appkit.h> int main(void) { nsspeechsynthesizer* synth = [[nsspeechsynthesizer alloc] initwithvoice: nil]; [synth startspeakingstring: @"hello, firefox!"]; // wait until start speaking. while (![synth isspeaking]) {} // wait while speaking. while ([synth isspeaking]) {} [synth release]; re
turn 0; } save this file as test.m, and run with the following command, inside the same directory as the saved file (needs xcode). $ clang -framework appkit test.m && ./a.out class, message, and selector our task at hand is to convert objective-c syntax to c syntax. let's look at the following codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in...
...ough this objective-c syntax: get the nsspeechsynthesizer class definition. register the alloc selector for the message. send a message to the class, with the selector. get a reference to a class class definitions are retrieved with the objc_getclass function, declared in /usr/include/objc/runtime.h. the objc_getclass function receives the name of the class, looks up the definition, and re
turns it. class objc_getclass(const char *name); in /usr/include/objc/objc.h, class is defined as an opaque type by the following: typedef struct objc_class *class; in this example, we need the classnsspeechsynthesizer, which is retrieved with the following code: class nsspeechsynthesizer = objc_getclass("nsspeechsynthesizer"); registering a selector selectors can be registered and retrieved...
...f struct objc_class *class; in this example, we need the classnsspeechsynthesizer, which is retrieved with the following code: class nsspeechsynthesizer = objc_getclass("nsspeechsynthesizer"); registering a selector selectors can be registered and retrieved with sel_registername function, also declared in /usr/include/objc/runtime.h. sel_registername receives the name of the selector, and re
turns the selector. sel sel_registername(const char *str); sel is defined as follows, in /usr/include/objc/objc.h. it's also an opaque type. typedef struct objc_selector *sel; in this example, we need to send alloc, its selector can be retrieved with the following code: sel alloc = sel_registername("alloc"); sending a message once target class and selector are ready, you can send a message. ...
...And 10 more matches
Debugger.Frame - Firefox Developer Tools
d so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame. this allows the code using each debugger instance to place whatever properties it likes on its debugger.frame instances, without worrying about interfering with other debuggers.) when the debuggee pops a stack frame (say, because a function call has re
turned or an exception has been thrown from it), the debugger.frame instance referring to that frame becomes inactive: its live property becomes false, and accessing its other properties or calling its methods throws an exception. note that frames only become inactive at times that are predictable for the debugger: when the debuggee runs, or when the debugger removes frames from the stack itself. vis...
... push a "debugger" frame on the stack, witholder as its older property. invoke the debuggee code as appropriate for the given invocation function, with the "debugger" frame as its continuation. for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame. when the debuggee code completes, whether by re
turning, throwing an exception or being terminated, pop the "debugger" frame, and re
turn an appropriate completion value from the invocation function to the debugger. when a debugger calls an invocation function to run debuggee code, that code’s continuation is the debugger, not the next debuggee code frame. pushing a "debugger" frame makes this continuation explicit, and makes it easier to find...
...alled as a constructor, false otherwise. arguments the arguments passed to the current frame, or null if this is not a "call" frame. when non-null, this is an object, allocated in the same global as the debugger, with array.prototype on its prototype chain, a non-writable length property, and properties whose names are array indices. each property is a read-only accessor property whose getter re
turns the current value of the corresponding parameter. when the referent frame is popped, the argument value’s properties’ getters throw an error. handler methods of debugger.frame instances each debugger.frame instance inherits accessor properties holding handler functions for spidermonkey to call when given events occur in the frame. calls to frames’ handler methods are cross-compartment,...
...And 10 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
in the dom can cause layout problems and make manipulation of the content tree difficult in unexpected ways, depending on where it is located. this article explores when difficulties can occur, and looks at what can be done to mitigate resulting problems. what is whitespace? whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, crlf sequences, carriage re
turns or line feeds). these characters allow you to format your code in a way that will make it easily readable by yourself and other people. in fact, much of our source code is full of these whitespace characters, and we only tend to get rid of it in a production build step to reduce code download sizes. html largely ignores whitespace? in the case of html, whitespace is largely ignored — whitesp...
...9 * "\n" lf \u000a * "\r" cr \u000d * " " spc \u0020 * * this does not use javascript's "\s" because that includes non-breaking * spaces (and also some other characters). */ /** * determine whether a node's text content is entirely whitespace. ...
... /** * determine whether a node's text content is entirely whitespace. * * @param nod a node implementing the |characterdata| interface (i.e., * a |text|, |comment|, or |cdatasection| node * @re
turn true if all of the text content of |nod| is whitespace, * otherwise false. */ function is_all_ws( nod ) { // use ecma-262 edition 3 string and regexp features re
turn !(/[^\t\n\r ]/.test(nod.textcontent)); } /** * determine if a node should be ignored by the iterator functions. * * @param nod an object implementing the dom1 |node| interface. ...
...And 10 more matches
Key Values - Web APIs
ymbol modifier key (found on certain virtual keyboards). keycode_sym (63) [3] "symbollock" the symbol lock key. [1] in internet explorer (tested on release 9 and 11), as well as in all versions of firefox, the windows key is reported as "os" instead of as "meta". this will be changed in firefox per bug 1232918. until that's fixed, these keys are re
turned as "os" by firefox: vk_lwin (0x5b) and vk_rwin (0x5c) on windows, and gdk_key_super_l (0xffeb), gdk_key_super_r (0xffec), gdk_key_hyper_l (0xffed), and gdk_key_hyper_r (0xffee) on linux. [2] internet explorer (tested on release 9 and 11) reports "scroll" instead of "scrolllock" for the scroll lock key. [3] firefox did not add support for the symbol key until firefox 37. [4] firefox generates...
... and "hyper". [5] chrome 67 and firefox 63 now correctly interpret the right alt key for keyboard layouts which map that key to altgr. see firefox bug bug 900750 and chrome bug 25503 for further details. ...
...[5] chrome 67 and firefox 63 now correctly interpret the right alt key for keyboard layouts which map that key to altgr. see firefox bug bug 900750 and chrome bug 25503 for further details. whitespace keys keyboardevent.key value description virtual keycode windows mac linux android "enter" the enter or ↵ key (sometimes labeled re
turn). ...
...And 10 more matches
RTCIceServers.urls - Web APIs
examples let's look a few examples of varying complexity. ...
... examples let's look a few examples of varying complexity. ...
...er.example.org to negotiate connections. mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed. ...
...And 10 more matches
BigUint64Array - JavaScript
byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0n. once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation). constructor biguint64array() creates a new biguint64array object. static properties biguint64array.bytes_per_element re
turns a number value of the element size. 8 in the case of a biguint64array. biguint64array.name re
turns the string value of the constructor name. in the case of the biguint64array type this is "biguint64array". static methods biguint64array.from() creates a new biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with ...
... value of the constructor name. in the case of the biguint64array type this is "biguint64array". static methods biguint64array.from() creates a new biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with a variable number of arguments. see also array.of(). ...
...ew biguint64array from an array-like or iterable object. see also array.from(). biguint64array.of() creates a new biguint64array with a variable number of arguments. see also array.of(). instance properties biguint64array.prototype.buffer re
turns the arraybuffer referenced by the biguint64array. this is fixed at construction time and thus read only. biguint64array.prototype.bytelength re
turns the length (in bytes) of the biguint64array from the start of its arraybuffer. this is fixed at construction time and thus read only. ...
...And 10 more matches
Destructuring assignment - JavaScript
o variables values can be swapped in one destructuring expression. without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the xor-swap trick). ...
...expression. without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the xor-swap trick). let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr = [1,2,3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] parsing an array re
turned from a function it's always been possible to re
turn an array from a function. ...
...temporary variable (or, in some low-level languages, the xor-swap trick). let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr = [1,2,3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] parsing an array re
turned from a function it's always been possible to re
turn an array from a function. destructuring can make working with an array re
turn value more concise. ...
...And 10 more matches
Logical AND (&&) - JavaScript
the logical and (&&) operator (logical conjunction) for a set of operands is true if and only if all of its operands are true. it is typically used with boolean (logical) values. when it is, it re
turns a boolean value. however, the && operator actually re
turns the value of one of the specified operands, so if this operator is used with non-boolean values, it will re
turn a non-boolean value. 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 expr1 && expr2 description if expr1 can be converted to true, re
turns expr2; else, re
turns expr1. if a value can be converted to true, the value is so-called truthy. if ...
...a value can be converted to true, the value is so-called truthy. if a value can be converted to false, the value is so-called falsy. examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined. even though the && operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its re
turn value can always be converted to a boolean primitive. to explicitly convert its re
turn value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. short-circuit evaluation the logical and expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some falsy expression)...
...hort-circuit evaluated to the falsy expression; short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). this happens because the value of the operator is already determined after the evaluation of the first operand. see example: function a(){ console.log('called a'); re
turn false; } function b(){ console.log('called b'); re
turn true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && fal...
...And 10 more matches
menupopup - Archive of obsolete content
/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. re
turning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attribute determines where the popup appears relative to the element the user clicked to invoke the popup. this allows you to...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, ...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) ...
...And 9 more matches
Basic math in JavaScript — numbers and operators - Learn web development
yint; myfloat; number values are typed in without quote marks — try declaring and initializing a couple more variables containing numbers before you move on. now let's check that both our original variables are of the same datatype. there is an operator called typeof in javascript that does this. enter the below two lines as shown: typeof myint; typeof myfloat; you should get "number" re
turned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. phew! useful number methods the number object, an instance of which represents all standard numbers you'll use in your javascript, has a number of useful methods available on it for you to manipulate numbers. we don't cover these in detai...
...decimal.tofixed(2); twodecimalplaces; converting to number data types sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. this most commonly happens when data is entered into a form input, and the input type is text. there is a way to solve this problem — passing the string value into the number() constructor to re
turn a number version of the same value. for example, try typing these lines into your console: let mynumber = '74'; mynumber + 3; you end up with the result 743, not 77, because mynumber is actually defined as a string. you can test this by typing in the following: typeof mynumber; to fix the calculation, you can do this: number(mynumber) + 3; arithmetic operators arithmetic operators are the...
... operator name purpose example + addition adds two numbers together. 6 + 9 - subtraction subtracts the right number from the left. 20 - 15 * multiplication multiplies two numbers together. 3 * 7 / division divides the left number by the right. 10 / 5 % remainder (sometimes called modulo) re
turns the remainder left over after you've divided the left number into a number of integer portions equal to the right number. 8 % 3 (re
turns 2, as three goes into 8 twice, leaving 2 left over). ** exponent raises a base number to the exponent power, that is, the base number multiplied by itself, exponent times. it was first introduced in ecmascript 2016. 5 ** 2 (ret...
...And 9 more matches
WebRequest.jsm
onal opt_extrainfospec argument lets you pass extra instructions for the handling of events. the instructions you can pass here vary depending on the event you're listening to: see the event-specific documentation for details. in particular, "blocking" may be passed to several event types, and will make the event dispatch synchronous, so the browser will wait for the event listener to re
turn before continuing with the request. this then enables the event listener to modify or cancel the request. see modifying & canceling requests. some examples of using addlistener(). to remove a listener for an event, call removelistener on the event in question, passing it the listener to remove. filtering the filter argument is the second argument to addlistener(). if you don't pass ...
...st: that is, the webrequest event that your listener is attached to. for example, it obviously doesn't make sense to cancel a network request after it has completed. the general approach to modifying and canceling requests is this: first, pass an array containing the string "blocking" as the third argument to your addlistener() call. ...
...er is attached to. for example, it obviously doesn't make sense to cancel a network request after it has completed. the general approach to modifying and canceling requests is this: first, pass an array containing the string "blocking" as the third argument to your addlistener() call. this tells the browser to wait for your event listener to re
turn before continuing with the request. ...
...And 9 more matches
NSS API Guidelines
when it becomes too difficult. many routines are defined to take an nssarena *arenaopt argument. this means if an arena is specified (non-null), it is used, otherwise (null) the routine uses the heap. you can think of the heap as a default arena you can't destroy. error handling nss 3.0 introduces the concept of an error stack. when something goes wrong, the call stack unwinds, with routines re
turning an error indication. each level which flags a problem, adds its own error number to the stack. at the bottom of the stack is the fundamental error, for example: file not found, and on top is an error precisely relating to what you are doing. note: error stacks are vertical, and never horizontal. if multiple things go wrong simultaneously, and you want to report them all, use another mechanis...
...er horizontal. if multiple things go wrong simultaneously, and you want to report them all, use another mechanism. errors, though not integers, are done as external constants, instead of preprocessor definitions. this is so any additional error doesn't trigger the entire tree to rebuild. likewise, the external references to errors are made in the prototypes files, with the functions which can re
turn them. error stacks are thread-private. the usual semantic is that public routines clear the stack first, private routines don't. usually, every public routine has a private counterpart, and the implementation of the public routine looks like this: nssimplement rv * nsstype_method ( nsstype *t, nssfoo *arg1, nssbar *arg2 ) { nss_clearerrorstac...
... routines clear the stack first, private routines don't. usually, every public routine has a private counterpart, and the implementation of the public routine looks like this: nssimplement rv * nsstype_method ( nsstype *t, nssfoo *arg1, nssbar *arg2 ) { nss_clearerrorstack(); #ifdef debug if( !nssfoo_verifypointer(arg1) ) re
turn (rv *)null; if( !nssbar_verifypointer(arg2) ) re
turn (rv *)null; #endif /* debug */ re
turn nsstype_method(t, arg1, arg2); } aside from error cases, all documented entry points should check pointers in a debug, wherever possible. pointers to user-supplied buffers, and templates, should be checked against null. pointers to context-style functions should be checked...
...And 9 more matches
NSS Sample Code Sample1
&pubkey, pr_true, pr_true, 0); if (!prvkey) { rv = 1; goto done; } // set the nickname on the private key so that it // can be found later. ...
... if (rv) goto done; } // do the mac key if (!mwrappedmackey) { pk11symkey *key = 0; // the key size is 160 bits (20 bytes) key = pk11_keygen(slot, ckm_generic_secret_key_gen, 0, 160/8, 0); if (!key) { rv = 1; goto mac_done; } rv = wrapkey(key, pubkey, &mwrappedmackey); mac_done: if (key) pk11_freesymkey(key); } done: if (slot) pk11_freeslot(slot); re
turn rv; } int server::exportpublickey(secitem **pubkeydata) { int rv = 0; seckeypublickey *pubkey = 0; rv = getpublickey(&pubkey); if (rv) goto done; *pubkeydata = seckey_encodedersubjectpublickeyinfo(pubkey); if (!*pubkeydata) { rv = 1; goto done; } done: if (pubkey) seckey_destroypublickey(pubkey); re
turn rv; } int server::exportkeys(secitem *pubkeydata, secitem **wrappedencke...
... key rv = wrapkey(menckey, pubkey, &data); if (rv) goto done; // export the mac key rv = wrapkey(mmackey, pubkey, wrappedmackey); if (rv) goto done; // commit the rest of the operation *wrappedenckey = data; data = 0; done: if (data) secitem_freeitem(data, pr_true); if (pubkey) seckey_destroypublickey(pubkey); if (keyinfo) seckey_destroysubjectpublickeyinfo(keyinfo); re
turn rv; } int server::importkeys(secitem *wrappedenckey, secitem *wrappedmackey) { int rv = 0; if (mwrappedenckey || mwrappedmackey) { rv = 1; goto done; } mwrappedenckey = secitem_dupitem(wrappedenckey); if (!mwrappedenckey) { rv = 1; goto done; } mwrappedmackey = secitem_dupitem(wrappedmackey); if (!mwrappedmackey) { rv = 1; goto done; } done: re
turn rv; } int server::start() { ...
...And 9 more matches
Python binding for NSS
/nspr objects which have "get" and "set" api function calls are exposed as python properties. all nss/nspr python objects can print their current value by evaluting the python object in a string context or by using the python str() function. support threading. the python global interpreter lock (gil) is released prior to calling nss/nspr c functions and reaquired after the nss/nspr c function re
turns. this allows other python threads to execute during the time a nss/nspr function is progress in another thread. also, any "global" values which are set in python-nss are actually thread-local. examples of this are the various callbacks which can be set and their parameters. thus each thread gets it own set of callbacks. many methods/functions provide sane default (keyword) parameters freeing th...
...values which are set in python-nss are actually thread-local. examples of this are the various callbacks which can be set and their parameters. thus each thread gets it own set of callbacks. many methods/functions provide sane default (keyword) parameters freeing the python programmer from having to specify all parameters yet allowing them to be overriden when necessary. error codes are never re
turned from methods/functions. python-nss follows the existing python exception mechanism. any error reported by nss/nspr is converted into a python exception and raised. the exact error code, error description, and often contextual error information will be present in the exception object. enumerated constants used in the nss/nspr api's are available in the python module under the exact same name as...
...ed certifcate validation including ca certs can be done via certificate.verify() or certificate.is_ca_cert(). when cert validation fails you can now obtain diagnostic information as to why the cert failed to validate. this is encapsulated in the certverifylog class which is a iterable collection of certverifylognode objects. most people will probablby just print the string representation of the re
turned certverifylog object. cert validation logging is handled by the certificate.verify() method. support has also been added for the various key usage and cert type entities which feature prominently during cert validation. certificate() constructor signature changed from certificate(data=none, der_is_signed=true) to certificate(data, certdb=cert_get_default_c...
...And 9 more matches
pkfnc.html
nickname a pointer to the nickname in the certificate database or to the nickname in the token. wincx a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. ...
... a pointer to the nickname in the certificate database or to the nickname in the token. wincx a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. re
turns the function re
turns one of these values: if successful, a pointer to a certificate structure. if unsuccessful, null. description a nickname is an alias for a certificate subject. there may be multiple certificates with the same subject, and hence the same nickname. this function will re
turn the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate. whe...
...to a certificate structure. if unsuccessful, null. description a nickname is an alias for a certificate subject. there may be multiple certificates with the same subject, and hence the same nickname. this function will re
turn the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate. when you are finished with the certificate structure re
turned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate. the pk11_findcertfromnickname function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_findkeybyanycert finds the private key associated with a specified certificate in any available slot. syntax #include <pk11func.h> #in...
...And 9 more matches
sslcrt.html
a certusageemailsigner certusageemailrecipient certusageobjectsigner certusageusercertimport certusageverifyca certusageprotectedobjectsigner wincx the pin argument value to pass to pk11 functions. see description below for more information. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. description the cert_verifycertnow function must call one or more pk11 functions to obtain the services of a pkcs #11 module. some of the pk11 functions require a pin argument (see ssl_setpkcs11pinarg for details), which must be specified in th...
...<cert.h> secstatus cert_verifycertname( certcertificate *cert, char *hostname); parameters this function has the following parameters: cert a pointer to the certificate against which to check the hostname referenced by hostname. hostname the hostname to be checked. re
turns the function re
turns one of these values: if the common name in the subject dn for the certificate matches the domain name passed in the hostname parameter, secsuccess. if the common name in the subject dn for the certificate is not identical to the domain name passed in the hostname parameter, secfailure. use pr_geterror to obtain the error code. description the comparison perform...
...ert, int64 t); parameters this function has the following parameters: cert a pointer to the certificate whose validity period you want to check against. t the time to check against the certificate's validity period. for more information, see the nspr header pr_time.h. re
turns the function re
turns an enumerator of type seccerttimevalidity: typedef enum { seccerttimevalid, seccerttimeexpired, seccerttimenotvalidyet } seccerttimevalidity; nss_cmpcertchainwcanames determines whether any of the signers in the certificate chain for a specified certificate are on a specified list of ca names. syntax #include <nss.h> secstatus nss_cmpcertchainwcanames( c...
...And 9 more matches
Finishing the Component
*acompmgr, nsifile *apath, const char *registrylocation, const char *componenttype, const nsmodulecomponentinfo *info) { nsresult rv; nscomptr<nsiservicemanager> servman = do_queryinterface((nsisupports*)acompmgr, &rv); if (ns_failed(rv)) re
turn rv; nscomptr<nsicategorymanager> catman; servman->getservicebycontractid(ns_categorymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); if (ns_failed(rv)) re
turn rv; char* previous = nsnull; rv = catman->addcategoryentry("xpcom-startup", "weblock", ...
...a similar step is required for unregistration. implementing the nsicontentpolicy at this point, you can take the weblock component and install it into a gecko installation. when the component is loaded, gecko calls the nsicontentpol...
...categoryentry in the same way we did in registering for notifications. a similar step is required for unregistration. implementing the nsicontentpolicy at this point, you can take the weblock component and install it into a gecko installation. when the component is loaded, gecko calls the nsicontentpolicy implementation in weblock on every page load, and this prevents pages from displaying by re
turning the proper value when the load method is called. the web locking policy that we are going to put into place is quite simple: for every load request that comes through, we will ensure that the uri is in the list of "good" urls on the white list. if you care to extend this implementation so that the list of urls is held remotely on a server somewhere - as might be the case when the weblock co...
...And 9 more matches
NS_ConvertASCIItoUTF16
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
NS_ConvertUTF8toUTF16
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsAdoptingString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsAutoString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsDependentString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsFixedString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsPromiseFlatString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsXPIDLString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use ...
...ind print32 find(const nscstring&, prbool, print32, print32) const - source search for the given substring within this string. @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the whole string. ...
... - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching. use -1 to search from the end of the string. @param acount tells us how many iterations to make starting at the given offset. ...
...And 9 more matches
nsIAccessibleRetrieval
nsidomnode getrelevantcontentnodefor(in nsidomnode anode); astring getstringeventtype(in unsigned long aeventtype); astring getstringrelationtype(in unsigned long arelationtype); astring getstringrole(in unsigned long arole); nsidomdomstringlist getstringstates(in unsigned long astates, in unsigned long aextrastates); methods getaccessiblefor() re
turn an nsiaccessible for a dom node in pres shell 0. create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessiblefor( in nsidomnode anode ); parameters anode the dom node to get an accessible for. re
turn value the nsiaccessible for the given dom node. getaccessibleinshell() re
turn an nsiaccessible ...
...ode in the given pres shell. create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessibleinshell( in nsidomnode anode, in nsipresshell apresshell ); parameters anode the dom node to get an accessible for. apresshell the presentation shell which contains layout info for the dom node. re
turn value the nsiaccessible for the given dom node. getaccessibleinweakshell() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) re
turn an nsiaccessible for a dom node in the given weak shell. create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessibleinweakshell(...
...he given weak shell. create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessibleinweakshell( in nsidomnode anode, in nsiweakreference apresshell ); parameters anode the dom node to get an accessible for. apresshell the presentation shell which contains layout info for the dom node. re
turn value the nsiaccessible for the given dom node. getaccessibleinwindow() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) re
turn an nsiaccessible for a dom node in present shell for this dom window. create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists. nsiaccessible getaccessiblein...
...And 9 more matches
nsIDOMMozNetworkStatsManager
in jsval start, in jsval end, [optional] in jsval options /* networkstatsgetoptions */); parameters network the origin of the data. it can specify wifi, mobile, or null. if null, data measurement from both origins are merged. to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method re
turns an array of interfaces. start a date object representing the beginning of data measurement. end a date object representing the end of data measurement. options optional filtering options. networkstatsgetoptions is a dictionary object providing filtering options. re
turn value an nsidomdomrequest object. if successful, the request result is an nsidommoznetworkstats object describing the ...
...xbytes are undefined for those dates. if the filtering start date is greater than the end date, an exception is thrown. exceptions thrown ns_error_invalid_arg the filtering start date is greater than the end date. ns_error_not_implmented both appmanifesturl and servicetype are specified at the same time in the networkstatsgetoptions dictionary. invalidnetwork the network must be in the re
turn of getavailablenetworks. addalarm() install an alarm on a network. when total data usage reaches threshold bytes, a "networkstats-alarm" system message is sent to the application, where the optional parameter data must be a cloneable object. nsidomdomrequest addalarm(in nsisupports network, in long threshold, [optional] in jsval options /* n...
...ports network, in long threshold, [optional] in jsval options /* networkstatsalarmoptions */); parameters network the origin of the data. it can specify wifi, mobile, or null. if null, data measurement from both origins are merged. ...
...And 9 more matches
nsITextInputProcessor
stance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"]. createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window, callback)) { re
turn; } if begininputtransaction() or begininputtransactionfortests() re
turns false, it means that another instance of nsitextinputprocessor has composition on the window or is dispatching an event. in this case, other instances cannot create composition nor dispatch keyboard events on the window. the second argument, callback, should be an object which implements nsitextinputprocessorcallback or j...
...in this case, composition isn't created. so, js-ime shouldn't continue to compose the string. finally, when you commit the composition with the last composition string...
...in this case, composition isn't created. so, js-ime shouldn't continue to compose the string. ...
...And 9 more matches
nsIURI
rfc3987: internationalized resource identifiers subclasses of nsiuri, such as nsiurl, impose further structure on the uri. ...
...bility with existing internet infrastructure. read only. note: ipv6 addresses are not enclosed in square brackets. asciispec acstring (us-ascii) the uri spec with an ascii compatible encoding. the host portion follows the idna draft spec. other parts are url-escaped per the rules of rfc3986. the result is strictly ascii. read only. hasref boolean re
turns if there is a reference portion (the part after the "#") of the uri. host autf8string the host is the internet domain name to which this uri refers. it could be an ipv4 (or ipv6) address literal. if supported, it could be a non-ascii internationalized domain name. exceptions thrown ns_error_failure if host is not applicable to the uri scheme (e.
...g on the protocol). note: some characters may be escaped. port long the uri's port. a port value of -1 corresponds to the protocol's default port (for example -1 implies port 80 for http uris). exceptions thrown ns_error_failure if port is not applicable to the uri scheme (e.g. about:blank) prepath autf8string the prepath re
turns the string before the path (such as "scheme://user:password@host:port"). this is related to the web origin concept of rfc6454. this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scripting attacks while using methods such as window.postmessage(). note: some characters may be escaped. read only. ref autf8string...
...And 9 more matches
Working with Multiple Versions of Interfaces
that prompted this note, i needed to obtain the hwnd of the document (yes its on windows) in order to identify each particular extension instance. ...
...nce. to do this i used the accessibility framework: hwnd gethwnd(nsidomnode *node){ hwnd self = null; nsresult rv; nscomptr<nsiaccessibleretrieval> refp; refp = do_createinstance( "@mozilla.org/accessibleretrieval;1", &rv); if (ns_failed(rv)){ re
turn self; } //line 6. nscomptr<nsiaccessible> accnode; rv = refp->getaccessiblefor(node, getter_addrefs(accnode)); if(ns_failed(rv)){ re
turn self; } void *wh = null; nscomptr<nsiaccessibledocument> accdocnode; accdocnode = do_queryinterface(accnode, &rv); if(ns_failed(rv)){ re
turn self; } rv = accdocnode->getwindowhandle(&wh); if(ns_succeeded(rv)){ self = static_cast<hwnd>(wh); } re
turn self; } this approach worked, as is, for versions as early as firefox 1.5. the problem arises when one tries to run an extension built ...
... xpcom component so that first tries to get the interface by it's new iid, then if that fails, attempts plan b. plan b is simply trying to get the interface by it's older iid. for expository purposes we will do this in two stages; buoyed by the fact that it is the actual route we took. the optimist's solution the first thing we do is replace line 6 above by our plan b: if (ns_failed(rv)){ re
turn gethwndb(node); } //new line 6. and then implement plan b. we first dredge out the old interface identifiers from our yea olde firefox 1.5 sdk: static const nsiid iar_iid_old = { 0x663ca4a8, 0xd219, 0x4000, { 0x92, 0x5d, 0xd8, 0xf6, 0x64, 0x06, 0xb6, 0x26 }}; static const nsiid iad_iid_old = {0x8781fc88, 0x355f, 0x4439, { 0x88, 0x1f, 0x65, 0x04, 0xa0, 0xa1, 0xce, 0xb6 }}; then follow the ...
...And 9 more matches
AudioWorkletProcessor.process - Web APIs
sample array rather than assuming a particular size. this size may even be allowed to change over time, so you mustn't look at just the first block and assume the sample buffers will always be the same size. syntax var isactivelyprocessing = audioworkletprocessor.process(inputs, outputs, parameters); parameters inputs an array of inputs connected to the node, each item of which is, in
turn, an array of channels. each channel is a float32array containing 128 samples. for example, inputs[n][m][i] will access n-th input, m-th channel of that input, and i-th sample of that channel. each sample value is in range of [-1 .. 1]. the number of inputs and thus the length of that array is fixed at the construction of the node (see audioworkletnodeoptions). if there is no active node conne...
...ray will contain 128 values — one for each frame in the current audio block. if there's no automation happening during the time represented by the current block, the array may contain a single value that is constant for the entire block, instead of 128 identical values. if the automation rate is "k-rate", the array will contain a single value, which is to be used for each of 128 frames. ...
...constant for the entire block, instead of 128 identical values. if the automation rate is "k-rate", the array will contain a single value, which is to be used for each of 128 frames. re
turn value a boolean value indicating whether or not to force the audioworkletnode to remain active even if the user agent's internal logic would otherwise decide that it's safe to shut down the node. the re
turned value lets your processor have influence over the lifetime policy of the audioworkletprocessor and the node that owns it. ...
...And 9 more matches
Cache - Web APIs
use the caches only from the version of the script that they can safely operate on. see deleting old caches for more information. note: the key matching algorithm depends on the vary header in the value. so matching a new key requires looking at both key and value for entries in the cache. note: the caching api doesn't honor http caching headers. methods cache.match(request, options) re
turns a promise that resolves to the response associated with the first matching request in the cache object. cache.matchall(request, options) re
turns a promise that resolves to an array of all matching requests in the cache object. cache.add(request) takes a url, retrieves it and adds the resulting response object to the given cache. this is functionally equivalent to calling fetch(), then using ...
...ctionally equivalent to calling fetch(), then using put() to add the results to the cache. cache.addall(requests) takes an array of urls, retrieves them, and adds the resulting response objects to the given cache. cache.put(request, response) takes both a request and its response and adds it to the given cache. cache.delete(request, options) finds the cache entry whose key is the request, re
turning a promise that resolves to true if a matching cache entry is found and deleted. if no cache entry is found, the promise resolves to false. cache.keys(request, options) re
turns a promise that resolves to an array of cache keys. examples this code snippet is from the service worker selective caching sample. (see selective caching live) the code uses cachestorage.open() to open any cache obj...
...est, options) re
turns a promise that resolves to an array of cache keys. examples this code snippet is from the service worker selective caching sample. (see selective caching live) the code uses cachestorage.open() to open any cache objects with a content-type header that starts with font/. the code then uses cache.match() to see if there's already a matching font in the cache, and if so, re
turns it. if there isn't a matching font, the code fetches the font from the network and uses cache.put() to cache the fetched resource. the code handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code. the code snippet also shows a best practice for v...
...And 9 more matches
CacheStorage - Web APIs
ns (i.e. those that aren't using https, although this definition will likely become more complex in the future.) when testing, you can get around this by checking the "enable service workers over http (when toolbox is open)" option in the firefox devtools options/gear menu. note: cachestorage.match() is a convenience method. ...
...e.match() is a convenience method. equivalent functionality to match a cache entry can be implemented by re
turning an array of cache names from cachestorage.keys(), opening each cache with cachestorage.open(), and matching the one you want with cache.match(). methods cachestorage.match() checks if a given request is a key in any of the cache objects that the cachestorage object tracks, and re
turns a promise that resolves to that match. cachestorage.has() re
turns a promise that resolves to true if a cache object matching the cachename exists. ...
...ache with cachestorage.open(), and matching the one you want with cache.match(). methods cachestorage.match() checks if a given request is a key in any of the cache objects that the cachestorage object tracks, and re
turns a promise that resolves to that match. cachestorage.has() re
turns a promise that resolves to true if a cache object matching the cachename exists. ...
...And 9 more matches
DOMMatrixReadOnly - Web APIs
e are aliases for specific components of a 4×4 matrix, as shown below. 2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface doesn't inherit any methods. none of the following methods alter the original matrix. dommatrixreadonly.flipx() re
turns a new dommatrix created by flipping the source matrix around its x-axis. this is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0). the original matrix is not modified. dommatrixreadonly.flipy() re
turns a new dommatrix created by flipping the source matrix around its y-axis. this is equivalent to multiplying the matrix by dommatrix(1, 0, 0, -1, 0, 0). the original matrix i...
... matrix around its x-axis. this is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0). the original matrix is not modified. dommatrixreadonly.flipy() re
turns a new dommatrix created by flipping the source matrix around its y-axis. this is equivalent to multiplying the matrix by dommatrix(1, 0, 0, -1, 0, 0). the original matrix is not modified. dommatrixreadonly.inverse() re
turns a new dommatrix created by inverting the source matrix. if the matrix cannot be inverted, the new matrix's components are all set to nan and its is2d property is set to false. the original matrix is not altered. dommatrixreadonly.multiply() re
turns a new dommatrix created by computing the dot product of the source matrix and the specified matrix: a⋅b. if no matrix is specified as the multipl...
...by computing the dot product of the source matrix and the specified matrix: a⋅b. if no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is 0 except the bottom-right corner and the element immediately above and to its left: m33 and m34. these have the default value of 1. the original matrix is not modified. ...
...And 9 more matches
HTMLElement - Web APIs
a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, element, and implements those from documentandelementeventhandlers, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement and toucheventhandlers. htmlelement.accesskey is a domstring representing the access key assigned to the element. htmlelement.accesskeylabel read only re
turns a domstring containing the element's assigned access key. htmlelement.contenteditable is a domstring, where a value of true means the element is editable and a value of false means it isn't. htmlelement.iscontenteditable read only re
turns a boolean that indicates whether or not the content of the element can be edited. htmlelement.contextmenu is a htmlmenuelement representing the contex...
...tring, where a value of true means the element is editable and a value of false means it isn't. htmlelement.iscontenteditable read only re
turns a boolean that indicates whether or not the content of the element can be edited. htmlelement.contextmenu is a htmlmenuelement representing the contextual menu associated with the element. it may be null. htmlorforeignelement.dataset read only re
turns a domstringmap with which script can read and write the element's custom data attributes (data-*) . htmlelement.dir is a domstring, reflecting the dir global attribute, representing the directionality of the element. ...
... htmlelement.hidden is a boolean indicating if the element is hidden or not. ...
...And 9 more matches
KeyboardEvent - Web APIs
the key could originate from. the numlock key does not fall into this group and is always encoded with the location dom_key_location_standard. examples include the digits on the numeric keypad, the keypad's enter key, and the decimal point on the keypad. properties this interface also inherits properties of its parents, uievent and event. keyboardevent.altkey read only re
turns a boolean that is true if the alt ( option or ⌥ on os x) key was active when the key event was generated. keyboardevent.code read only re
turns a domstring with the code value of the physical key represented by the event. warning: this ignores the user's keyboard layout, so that if the user presses the key at the "y" position in a qwerty keyboard layout (near the middle of the row above the...
... alt ( option or ⌥ on os x) key was active when the key event was generated. keyboardevent.code read only re
turns a domstring with the code value of the physical key represented by the event. warning: this ignores the user's keyboard layout, so that if the user presses the key at the "y" position in a qwerty keyboard layout (near the middle of the row above the home row), this will always re
turn "keyy", even if the user has a qwertz keyboard (which would mean the user expects a "z" and all the other properties would indicate a "z") or a dvorak keyboard layout (where the user would expect an "f"). ...
...o that if the user presses the key at the "y" position in a qwerty keyboard layout (near the middle of the row above the home row), this will always re
turn "keyy", even if the user has a qwertz keyboard (which would mean the user expects a "z" and all the other properties would indicate a "z") or a dvorak keyboard layout (where the user would expect an "f"). keyboardevent.ctrlkey read only re
turns a boolean that is true if the ctrl key was active when the key event was generated. keyboardevent.iscomposing read only re
turns a boolean that is true if the event is fired between after compositionstart and before compositionend. ...
...And 9 more matches
SubtleCrypto.unwrapKey() - Web APIs
as with subtlecrypto.importkey(), you specify the key's import format and other attributes of the key to import details such as whether it is extractable, and which operations it can be used for. ...
...y be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key re
turn value result is a promise that fulfills with the unwrapped key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when the unwrapping key is not a key for the requested unwrap algorithm or if the cryptokey.usages value of that key doesn't contain unwrap. notsupported raised when trying to use an algo...
...171,223,14,36,201,233,233,120,164,68,217,192,226,80, 224,39,199,235,239,60,212,169,100,23,61,54,244,197,160,80,109,230,207, 225,57,197,175,71,80,209]; /* convert an array of byte values to an arraybuffer. ...
...And 9 more matches
TextEncoder.prototype.encodeInto() - Web APIs
the textencoder.prototype.encodeinto() method takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and re
turns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method especially when the target buffer is a view into a wasm heap. syntax b1 = encoder.encodeinto(string, uint8array); parameters string is a usvstring containing the text to encode. uint8array is a uint8array object instance to place the resulting utf-8 encoded text into. re
turn value a textencoderencodeintoresult dictionary, which contains two members: read the number of utf-16 units of code from the source that has been converted over to utf-8. this may be less than string.length if uint8array di...
...ritten are guaranteed to form complete utf-8 byte sequences. encode into a specific position encoder.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. var encoder = new textencoder; function encodeintoatposition(string, u8array, position) { re
turn encoder.encodeinto(string, position ? u8array.subarray(position|0) : u8array); } var u8array = new uint8array(8); encodeintoatposition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 buffer sizing to convert a javascript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes. if t...
... it makes sense to compute minimum allocation rounduptobucketsize(s.length), the maximum allocation size s.length * 3, and to have a chosen (as a tradeoff between memory usage and speed) threshold t such that if rounduptobucketsize(s.length) + t >= s.length * 3, you simply allocate for s.length * 3. otherwise, first allocate for rounduptobucketsize(s.length) and convert. if the read item it the re
turn dictionary is s.length, the conversion is done. if not, reallocate the target buffer to written + (s.length - read) * 3 and then convert the rest by taking a substring of s starting from index read and a subbuffer of the target buffer starting from index written. above rounduptobucketsize() is a function that rounds up to the allocator bucket size. for example, if your wasm allocator is known to...
...And 9 more matches
Window.open() - Web APIs
nal a domstring containing a comma-separated list of window features given with their corresponding values in the form "name=value". these features include options such as the window's default size and position, whether or not to include toolbar, and so forth. there must be no whitespace in the string. see window features below for documentation of each of the features that can be specified. re
turn value a windowproxy object, which is basically a thin wrapper for the window object representing the newly created window, and has all its features available. if the window couldn't be opened, the re
turned value is instead null. the re
turned reference can be used to access properties and methods of the new window as long as it complies with same-origin policy security requirements. description ...
...cription the open() method creates a new secondary browser window, similar to choosing new window from the file menu. the url parameter specifies the url to be fetched and loaded in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that remote urls won't load immediately. when window.open() re
turns, 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() { wi...
...indow.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/path/imagefile.png", "descriptivewindowname", "resizable,scrollbars,status" ); } if a window with the name already exists, then url is loaded into the existing window. in this case the re
turn value of the method is the existing window and windowfeatures is ignored. providing an empty string for url is a way to get a reference to an open window by its name without changing the window's location. on firefox and chrome (at least), this only works from the same parent, ie. if the current window is the opener of the window you try to get an handle on. otherwise the call to window.open() wi...
...And 9 more matches
Using CSS transitions - CSS: Cascading Style Sheets
; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width hei...
...out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width hei...
...out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width hei...
...And 9 more matches
HTTP Index - HTTP
requests while rejecting others. 22 reason: cors disabled authentication, authentication article, cors, cross-origin, disabled, errors, http, https, messages, resource, same origin, same-origin, security, sharing, validation, secure, troubleshooting a request that needs to use cors was attempted, but cors is disabled in the user's browser. when this happens, the user needs to
turn cors back on in their browser. 23 reason: cors header 'access-control-allow-origin' does not match 'xyz' cors, corsalloworiginnotmatchingorigin, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting simply put, the origin making the request does not match any of the origins permitted by the access-control-allow-origin header. 24 r...
...ence, so that it allows a user to differentiate according to the users' own preferred language. 73 content-length http, headers, reference the content-length entity header indicates the size of the entity-body, in bytes, sent to the recipient. 74 content-location http, reference, header the content-location header indicates an alternate location for the re
turned data. the principal use is to indicate the url of a resource transmitted as the result of content negotiation. 75 content-range http, http header, reference, response header, header the content-range response http header indicates where in a full body message a partial message belongs. 76 content-security-policy csp, content security policy, http, reference, ...
...ation about the acceleration of the device through the batterymanager interface obtained via navigator.getbattery(). 127 feature-policy: camera directive, feature policy, feature-policy, http, reference, camera the http feature-policy header camera directive controls whether the current document is allowed to use video input devices. when this policy is enabled, the promise re
turned by mediadevices.getusermedia() will reject with a notallowederror. 128 feature-policy: display-capture the http feature-policy header display-capture directive controls whether or not the document is permitted to use screen capture api, i.e.,getdisplaymedia() to capture the screen's contents. 129 feature-policy: document-domain directive, experimental, featu...
...And 9 more matches
Iterators and generators - JavaScript
m simple for loops to map() and filter(). iterators and generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops. for details, see also: iteration_protocols for...of function* and generator yield and yield* iterators in javascript an iterator is an object which defines a sequence and potentially a re
turn value upon its termination. specifically, an iterator is any object which implements the iterator protocol by having a next() method that re
turns an object with two properties: value the next value in the iteration sequence. done this is true if the last value in the sequence has already been consumed. if value is present alongside done, it is the iterator's re
turn value. once created, a...
... while it is easy to imagine that all iterators could be expressed as arrays, this is not true. ...
...e. once created, an iterator object can be iterated explicitly by repeatedly calling next(). iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. after a terminating value has been yielded additional calls to next() should simply continue to re
turn {done: true}. the most common iterator in javascript is the array iterator, which simply re
turns each value in the associated array in sequence. while it is easy to imagine that all iterators could be expressed as arrays, this is not true. arrays must be allocated in their entirety, but iterators are consumed only as necessary. because of this, iterators can express sequences of unlimited size, such as the range of integers between 0 and infinity. here is an example which can do just that...
...And 9 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 re
turned promises before explaining how to create them. essentially, a promise is a re
turned 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. here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file ready at url: " + result); } funct...
...le is successfully created, and the other called if an error occurs. ...
...this convention has several advantages. we will explore each one. guarantees unlike old-fashioned pass...
...And 9 more matches
Working with objects - JavaScript
object.keys(o...
...bject and the object's name as arguments to the function: function showprops(obj, objname) { var result = ``; for (var i in obj) { // obj.hasownproperty() is used to filter out properties from the object's prototype chain if (obj.hasownproperty(i)) { result += `${objname}.${i} = ${obj[i]}\n`; } } re
turn result; } so, the function call showprops(mycar, "mycar") would re
turn the following: mycar.make = ford mycar.model = mustang mycar.year = 1969 enumerate the properties of an object starting with ecmascript 5, there are three native ways to list/traverse object properties: for...in loops this method traverses all enumerable properties of an object and its prototype chain. object.keys(o) this method re
turns an array with all the own (not in the prototype c...
...object starting with ecmascript 5, there are three native ways to list/traverse object properties: for...in loops this method traverses all enumerable properties of an object and its prototype chain. object.keys(o) this method re
turns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o. object.getownpropertynames(o) this method re
turns an array containing all own properties' names (enumerable or not) of an object o. before ecmascript 5, there was no native way to list all properties of an object. however, this can be achieved with the following function: function listallproperties(o) { var objecttoinspect; var result = []; for(objecttoinspect = o; objecttoinspect !== null; objecttoinspect = object.getprototy...
...And 9 more matches
arguments.callee - JavaScript
expressions a name or use a function declaration where a function must call itself. why was arguments.callee removed from es5 strict mode? (adapted from a stack overflow answer by olliej) early versions of javascript did not allow named function expressions, and for this reason you could not make a recursive function expression. ...
...s5 strict mode? (adapted from a stack overflow answer by olliej) early versions of javascript did not allow named function expressions, and for this reason you could not make a recursive function expression. for example, this syntax worked: function factorial (n) { re
turn !(n > 1) ? 1 : factorial(n - 1) * n; } [1, 2, 3, 4, 5].map(factorial); but: [1, 2, 3, 4, 5].map(function(n) { re
turn !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; }); did not. to get around this arguments.callee was added so you could do [1, 2, 3, 4, 5].map(function(n) { re
turn !(n > 1) ? 1 : arguments.callee(n - 1) * n; }); however, this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the gener...
...1 : factorial(n - 1)*n; }); this has numerous benefits: the function can be...
...And 9 more matches
Float32Array - JavaScript
e platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor float32array() creates a new float32array object. static properties float32array.bytes_per_element re
turns a number value of the element size. 4 in the case of an float32array. float32array.name re
turns the string value of the constructor name. in the case of the float32array type: "float32array". static methods float32array.from() creates a new float32array from an array-like or iterable object. see also array.from(). float32array.of() creates a new float32array with a variable number of a...
...e re
turns the string value of the constructor name. in the case of the float32array type: "float32array". static methods float32array.from() creates a new float32array from an array-like or iterable object. see also array.from(). float32array.of() creates a new float32array with a variable number of arguments. see also array.of(). instance properties float32array.prototype.buffer re
turns the arraybuffer referenced by the float32array fixed at construction time and thus read only. float32array.prototype.bytelength re
turns the length (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.byteoffset re
turns the offset (in bytes) of the float32array from the start of its arraybuffer. fixed at constr...
...tion time and thus read only. float32array.prototype.bytelength re
turns the length (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.byteoffset re
turns the offset (in bytes) of the float32array from the start of its arraybuffer. fixed at construction time and thus read only. float32array.prototype.length re
turns the number of elements hold in the float32array. fixed at construction time and thus read only. instance methods float32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float32array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.p...
...And 9 more matches
Float64Array - JavaScript
e platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor float64array() creates a new float64array object. static properties float64array.bytes_per_element re
turns a number value of the element size. 8 in the case of an float64array. float64array.name re
turns the string value of the constructor name. in the case of the float64array type: "float64array". static methods float64array.from() creates a new float64array from an array-like or iterable object. see also array.from(). float64array.of() creates a new float64array with a variable number of a...
...e re
turns the string value of the constructor name. in the case of the float64array type: "float64array". static methods float64array.from() creates a new float64array from an array-like or iterable object. see also array.from(). float64array.of() creates a new float64array with a variable number of arguments. see also array.of(). instance properties float64array.prototype.buffer re
turns the arraybuffer referenced by the float64array fixed at construction time and thus read only. float64array.prototype.bytelength re
turns the length (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.byteoffset re
turns the offset (in bytes) of the float64array from the start of its arraybuffer. fixed at constr...
...tion time and thus read only. float64array.prototype.bytelength re
turns the length (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.byteoffset re
turns the offset (in bytes) of the float64array from the start of its arraybuffer. fixed at construction time and thus read only. float64array.prototype.length re
turns the number of elements hold in the float64array. fixed at construction time and thus read only. instance methods float64array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). float64array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.p...
...And 9 more matches
String.prototype.charAt() - JavaScript
the string object's charat() method re
turns a new string consisting of the single utf-16 code unit located at the specified offset into the string. 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 let character = str.charat(index) parameters index an integer between 0 and str.length - 1. if the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is re
turned. re
turn value a string representing the character (exactly one utf-16 code unit) at the specified index. if index is out of range, charat() re
turns an empty string. description charact...
... if no index is provided to charat(), the default is 0. ...
... character, even if the string contains characters that are not in the basic multi-lingual plane. ...
...And 9 more matches
Strict mode - JavaScript
catenation problem and it means that you have to explicitly export any shared variables out of the function scope. strict mode for functions likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements. function strict() { // function-level strict mode syntax 'use strict'; function nested() { re
turn 'and so am i!'; } re
turn "hi! i'm a strict mode function! " + nested(); } function notstrict() { re
turn "i'm not strict."; } strict mode for modules ecmascript 2015 introduced javascript modules and therefore a 3rd way to enter strict mode. the entire contents of javascript modules are automatically in strict mode, with no statement needed to initiate it. function strict() { // becau...
...sible object) will throw in strict mode: 'use strict'; // assignment to a non-writable global var undefined = 5; // throws a typeerror var infinity = 5; // throws a typeerror // assignment to a non-writable property var obj1 = {}; object.defineproperty(obj1, 'x', { value: 42, writable: false }); obj1.x = 9; // throws a typeerror // assignment to a getter-only property var obj2 = { get x() { re
turn 17; } }; obj2.x = 5; // throws a typeerror // assignment to a new property on a non-extensible object var fixed = {}; object.preventextensions(fixed); fixed.newprop = 'ohai'; // throws a typeerror third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect): 'use strict'; delete object.prototype; // throws a typeerror fourth...
... duplicated argument hides previous identically-named arguments. those previous arguments remain available through arguments[i], so they're not completely inaccessible. still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error: function sum(a, a, c) { // !!! syntax error 'use strict'; re
turn a + a + c; // wrong if this code ran } sixth, a strict mode in ecmascript 5 forbids octal syntax. the octal syntax isn't part of ecmascript 5, but it's supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%". in ecmascript 2015 octal number is supported by prefixing a number with "0o". i.e. var a = 0o10; // es2015: octal novice developers sometime...
...And 9 more matches
platform/xpcom - Archive of obsolete content
ented under the "using wrappedjsobject" section of how to build an xpcom component in javascript. ...
...e class id instead of the contract id. ...
...an find out whether a factory or service has been registered by using the isregistered() function: if (xpcom.isregistered(factory)) xpcom.unregister(factory); globals constructors factory(options) parameters options : object required options: name type component constructor constructor for the component this factory creates. this will typically re
turn a descendant of unknown, although it may re
turn a custom object that satisfies the nsisupports interface. optional options: name type contract string a contract id. users of xpcom can use this value to retrieve the factory from components.classes: var factory = components.classes['@me.org/request'] var component = factory.createinstance(ci...
...And 8 more matches
Canvas code snippets - Archive of obsolete content
for general information about using <canvas> see the canvas topic page. code usable from web content getting the number of pixels of a certain color in a canvas the following function will re
turn the number of pixels in a canvas that have the rgb color of r, g and b. this can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
...rea as explained in this blog post. ...
... cx = canvas.getcontext('2d'); var pixels = cx.getimagedata(0, 0, canvas.width, canvas.height); var all = pixels.data.length; var amount = 0; for (i = 0; i < all; i += 4) { if (pixels.data[i] === r && pixels.data[i + 1] === g && pixels.data[i + 2] === b) { amount++; } } re
turn amount; }; getting the color of a pixel in a canvas this following snippet re
turns an object with the rgba values of the pixel at position x and y of the canvas. ...
...And 8 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
things confusing. it is nonetheless the "correct" and best way to do things. ...
...httprequest;1", "nsixmlhttprequest"); here's how to load a file using it: function loadfile(url,type,re
turnresult) { var request = new xmlhttprequest(); request.open("get", url, true); // async=true request.responsetype = type; request.onerror = function(event) { logerrormessage("error attempting to load: " + url); re
turnresult(null); }; request.onload = function(event) { if (request.response) re
turnresult(request.response); else request.onerror(event); }; request.send(); } loadfile("chrome://myaddon/content/filename.ext",datatype,function(data) { /* do stuff with data */ }); note: when using xmlhttprequest to access a file:// url the request.status is n...
...: manually handle default preferences normal extensions load default preferences from a standardized file automatically. restartless extensions don't (for no good reason). this part is fairly easy to implement yourself, at least. ...
...And 8 more matches
Using Dependent Libraries In Extension Components - Archive of obsolete content
rv; // this is not the real component. we want to load the dependent libraries // of the real component, then the component itself, and call nsgetmodule on // the component. ...
...al component, then the component itself, and call nsgetmodule on // the component. ...
...dent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); prlibrary *lib; library->load(&lib); // 1) we don't care if this failed! // 2) we are going to leak this library. we don't care about that either. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) re
turn rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) re
turn ns_error_failure; re
turn getmoduleproc(acompmgr, alocation, aresult); } extensions/stub/bdsstubloader.cpp (for mac os x) the code as written above won't work for mac os x. dependant libraries on the mac must be loaded with a special system function n...
...And 8 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
type: integer the maximum number of characters that the textbox allows to be entered. maxrows type: integer the number of rows to show in the results list at a time. a scrollbar will appear so the user can scroll through the remaining items. minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be re
turned for the popup to be displayed. the default value is 1. new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup. this can be used to display additional items that are not autocomplete results. nomatch type: boolean this attribute will be set to true if the last search resulted in no matches. overview an onchange attribute is an event listener to the obje...
...this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchbegin type: script code this event handler is called when the autocomplete search begins. note: for firefox 12 and above, thi...
...3requires seamonkey 2.0 type: boolean if true, a comment column appears in the popup. for the url history, the comment column will contain the page titles associated with each url. if this attribute is not specified, the comment column doesn't appear. showimagecolumn type: boolean if true, an image column appears in the popup. there is no default styling of this image, but the class name re
turned by the results appears in the property list for the column. if this attribute is not specified, the image column doesn't appear. size type: integer the number of characters that can be displayed in the textbox. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a higher ...
...And 8 more matches
E4X for templating - Archive of obsolete content
pt 1.8 expression closures), the templates can function more dynamically, offering the power and readability of templating languages such as smarty for php (though admittedly without the currently wider cross-browser support of xslt or the strictly-xml approach of phptal or seethrough templating). ...
... currently wider cross-browser support of xslt or the strictly-xml approach of phptal or seethrough templating). ...
...mplating). security and escaping function e (str) { if (typeof str === 'xml') {str = str.tostring();} re
turn str; } function quot (s) { // useful for placing user input within inline javascript; may be combined with escape function above as well if (typeof s === 'string') { re
turn s.replace(/"/g, '"').replace(/'/g, '''); } if (typeof s === 'xml') { re
turn s.tostring().replace(/"/g, '"').replace(/'/g, '''); } re
turn string(s).replace(/"/g, '"').replace(/'/g, '''); } localization e4x works nicely with a simple utility for localizing strings of a properties file: // localization function $s(msg, args){ //get localized message var strs = cc['@mozilla.org/intl/stringbundle;1'].getservice(ci.nsistringbundleservice). ...
...And 8 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
ders: 50 cors-safelisted response header cors, fetch, glossary, http a cors-safelisted response header is an http header which has been safelisted so that it will not be filtered when responses are processed by cors, since they're considered safe (as the headers listed in access-control-expose-headers). 51 crlf cr, crlf, glossary, infrastructure, lf, carriage re
turn, line feed cr and lf are control characters or bytecode that can be used to mark a line break in a text file. 52 crud glossary, infrastructure crud (create, read, update, delete) is an acronym for ways one can operate on stored data. it is a mnemonic for the four basic functions of persistent storage. crud typically refers to operations performed in a database or datas...
...se each time. challenge-response protocols are one way to fight against replay attacks where an attacker listens to the previous messages and resends them at a later time to get the same credentials as the original message. 71 character codingscripting, glossary, strings a character is either a symbol (letters, numbers, punctuation) or non-printing "control" (e.g., carriage re
turn or soft hyphen). utf-8 is the most common character set and includes the graphemes of the most popular human languages. 72 character encoding composing, glossary an encoding defines a mapping between bytes and text. a sequence of bytes allows for different textual interpretations. by specifying a particular encoding (such as utf-8), we specify how the sequence of bytes is to...
...language specification on which javascript is based. ecma international is in charge of standardizing ecmascript. 126 effective connection type glossary, navigator, network information api, networkinformation, performance, reference, web performance, connect, effective connection type, effectivetype effective connection type (ect) refers to the measured network performance, re
turning a cellular connection type, like 3g, even if the actual connection is tethered broadband or wifi, based on the time between the browser requesting a page and effective type of the connection. 127 element codingscripting, glossary, html an element is a part of a webpage. in xml and html, an element may contain a data item or a chunk of text or an image, or perhaps nothing. ...
...And 8 more matches
Mobile accessibility - Learn web development
android and ios the most common mobile platforms have fully functional screen readers. these function in much the same way as desktop screenreaders, except they are largely operated using touch gestures rather than key combinations. let's look at the main two: talkback on android and voiceover on ios. android talkback the talkback screen reader is built into the android operating system. ...
...for example: single-tapping an app will select it, and the device will read out what the app is. swiping left and right will move between apps, or buttons/controls if you are in a control bar. ...
......
...And 8 more matches
Mozilla accessibility architecture
use similar concepts, but use different method, constant and interfaces names. given that there is a fair amount of commonality between accessibility api toolkits, it made sense to write of the code in a cross platform manner, and then deal with the platform differences on a consistent manner. the shared code makes itself available to the toolkit-specific code via generic xpcom interfaces that re
turn information about objects we want to expose. all focusable nodes, tables and text have accessibility interfaces. we call these objects "accessible nodes". each of these accessible nodes supports at minimum the generic cross-platform accessibility interface nsiaccessible (which provides a text name, enumerated role identifier and a set of state flags) and sometimes additional interfaces. for exam...
...so, what if they want to get dom information, like css rules, tag names and attributes, that msaa's iaccessible does not provide? on windows, we solve this by supporting an additional interface beyond msaa's iaccesible, for every dom node. queryinterface() can be used to switch between the two interfaces. if there is no msaa node for a dom node, paccessible->queryinterface(iid_iaccessible) will re
turn null. in addition, some vendors had asked us to provide information and support for pieces of text smaller than a text node (i.e. a word), and mozilla supports isimpledomtext for this purpose. on atk there is no such interface to get actual dom information. sun microsystems, the maintainers of mozilla's atk support, believe the atk is rich enough to provide everything the assistive technologies o...
...s to call the nsiaccessible methods in "this" to get at the information it needs. class inheritence diagram view the class inheritence diagram. 3. accessible tree construction and traversal the accessible tree is constructed on demand. ...
...And 8 more matches
Following the Android Toasts Tutorial from a JNI Perspective
for example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an l and ; around it. so this would be lblah/foo/bar;. if there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so this would be lblah/foo/bar$subclass;. when declaring methods, ...
... of this will be this in slash notation with an l and ; around it. so this would be lblah/foo/bar;. if there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so this would be lblah/foo/bar$subclass;. when declaring methods, the signatures of the types go right next to each other without any spacing. the arguments are within the parenthesis, and the re
turn type is immediately following. more on this later. so let us now declare the types for our toast example. we see we have three classes and two basic types (int and void). the class signature is looked up on the android documentation. for instance, we go to android reference :: context and we see: we see that the signature in dot notation is android.content.context. so this will be written as ...
...is static, this means that it can be called directly from the class. if it is not static, then it cannot be used on an instance of that class. how is it determined if a method is static or not? the documentation tells us. for example, in our case we have a method maketext and show, looking that up on the android documentation page shows this: there are two columns, the first column is the re
turn, and the second column is the method name and arguments. we see that maketext re
turns static toast. this means it is a static method. we see that the re
turn column of the show method does not contain the word static. therefore, it is a plain method. let's declare these methods in the third argument of loadclass we add a key-value pair, with the key being static_methods and methods and the value b...
...And 8 more matches
OS.File for the main thread
llowing 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) { re
turn decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (t...
... convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). ...
...ramming 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.bytelength ? re
turn promise.resolve(true); // loop end. } let promise = file.write(view.subarray(pos, chunksize)); // write a subset of |data| re
turn promise.then(function onsuccess(bytes) { re
turn loop(pos + bytes); // ... and loop. }); }; let promise = loop(0); ...
...And 8 more matches
Using XPCOM Utilities to Make Things Easier
ce and not an iid. inside the macro, the interface name expands to ns_get_iid(), which is another macro that extracts the iid from the generated header of the interface. when an interface is written in xpidl, the headers include static declarations of their iids. on any interface that is generated by xpidl, you can call ns_get_iid() to obtain the iid which is associated with that interface. // re
turns a reference to a shared nsiid object\ static const nsiid iid1 = ns_get_iid(nsisupports); // constructs a new nsiid object static const nsiid iid2 = ns_isupports_iid; in order to use ns_impl_isupportsn, you must be sure that a member variable of type nsrefcnt is defined and named mrefcnt in your class. but why even bother when you can use another macro? declaration macros ns_decl_nsisupports...
... summarizes the macro usage in this portion of the weblock.cpp source file: common xpcom macros ns_impl_isupportsn implements nsisupports for a given class with n number of interfaces ns_decl_isupports declares methods of nsisupports including mrefcnt ns_init_isupports initializes mrefcnt to zero. must be called in class's constructor ns_get_iid re
turns the iid given the name of an interface. interface must be generated by xpidl using the macros described here, the code for the weblock component has gone from around 340 lines of code to just under 40. clearly from a code maintenance point of view, this kind of reduction is outstanding. the entire source file with these macros included appears in weblock2.cpp. weblock2.cpp the listing b...
... abstract classes, respectively. this first example shows an nsembedcstring being used to pass an nsacstring to a method that's not expected to modify the string. // in idl: method(in acstring thing); char* str = "how now brown cow?"; nsembedcstring data(str); rv = object->method(data); in this next example, the method is going to set the value of the string - as it might need to do when it re
turns the name of the current user or the last viewed url. // in idl: attribute acstring data; nsembedcstring data; method->getdata(data); // now to extract the data from the url class: const char* astringurl = url.get(); note that the memory pointed to by astringurl after the call to url.get() is owned by the url string object. if you need to keep this string data around past the lifetime of t...
...And 8 more matches
Introduction to XPCOM for the DOM
his is why it is very important to keep track of the reference count of each object. in the first case, if we forget to addref the object, the object may delete itself before we are done using the pointer, which would cause a crash when dereferencing it. in the second case, if we forget to release the object, it will never delete itself, which will cause "memory leaks", i.e. the memory is never re
turned because we keep the object around even if we don't need it. in both cases it's very bad, and we have to be extremely careful with the refcounting. fortunately, there are nscomptr's to make our life easier. nscomptr scott collins blessed us with the nscomptr, now let's use them. nscomptr's are an extension of the c auto_ptr, managing the reference counting operations for you, and providing se...
...ke to manipulate that object with a method defined on the nsifoo interface. the goal is to retrieve a pointer to the nsifoo interface. to do so, there are two main techniques, and the context should tell you what to use. the first technique is to use a "getter", the second is to use a static cast on the "this" pointer. a getter is a function defined in global scope or in class scope that will "re
turn" a pointer to the required interface. generally getters work like this: first, declare a pointer to an interface, ifooptr without assigning it. pass the address of the pointer to the getter function. the getter function will then assign to the pointer the correct address and will queryinterface the pointer to that interface. ifooptr is now a pointer to an interface assigned to the address of a re...
... this is a contract between the caller, who says "i don't add a reference to this object because you have already done it", and the callee who says "i add a reference to this object, so don't do it!". if both the caller and the callee perform the addref, the object will be leaked, because one of the two references will never be released! please note that all getter functions have to addref the re
turned pointer. if you're just using the getter function though, you don't need to worry about it. more about this in the xpcom ownership guide. please also note that some interfaces are not refcounted, like the frames and views. for those you have to use raw interface pointers, and you don't have to perform any manual refcounting. let's say that you now want to execute a function declared on the ns...
...And 8 more matches
IAccessibleAction
[propget] hresult keybinding([in] long actionindex, [in] long nmaxbindings, [out, size_is(,nmaxbindings), length_is(, nbindings)] bstr keybindings, [out] long nbindings ); [propget] hresult localizedname([in] long actionindex, [out] bstr localizedname ); hresult nactions([out,retval] long nactions ); [propget] hresult name([in] long actionindex, [out] bstr name ); methods description() re
turns a description of the specified action of the object. [propget] hresult description( [in] long actionindex, [out] bstr description ); parameters actionindex 0 based index specifying which action's description to re
turn. if it lies outside the valid range an empty string is re
turned. description the re
turned value is a localized string of the specified action. re
turn value e_invalidarg if b...
...lt description( [in] long actionindex, [out] bstr description ); parameters actionindex 0 based index specifying which action's description to re
turn. if it lies outside the valid range an empty string is re
turned. description the re
turned value is a localized string of the specified action. re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to re
turn, [out] value is null. s_ok. doaction() performs the specified action on the object. hresult doaction( [in] long actionindex ); parameters actionindex 0 based index specifying the action to perform. ...
..."ctrl+shift+d". ...
...And 8 more matches
mozIStorageStatement
read only. parametercount unsigned long number of parameters. read only. params mozistoragestatementparams the current list of named parameters, which may be set. only available to javascript code. read only. row mozistoragestatementrow the current row, with access to all data members by name. available only to javascript code. read only. ...
...onnection.close(). void finalize(); note: this method does not need to be used from native callers because you have to release the statement in order to not leak. finalize will be called for you when the reference count on the statement goes to zero. clone() creates a copy of the statement whose state will be mozistoragestatement.moz_storage_statement_ready. mozistoragestatement clone(); re
turn value a mozistoragestatement that is a copy of the current statement. getparametername() obtains the name of the parameter for the specified index. autf8string getparametername( in unsigned long aparamindex ); 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</co...
...atement that is a copy of the current statement. getparametername() obtains the name of the parameter for the specified index. autf8string getparametername( in unsigned long aparamindex ); 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). re
turn value an autf8string representing the parameter name for the specified index. getparameterindex() obtains the index of the parameter with the specified name. this method was added in 1.9.0. in 1.8.1 you had to use getparameterindexes(). see bug 388048 for details. unsigned long getparameterindex( in autf8string aname ); parameters aname name of the parameter to get the index for. for ...
...And 8 more matches
nsIDocShell
ng on the current docshell. read only. canvashasfocus boolean tells the docshell whether the canvas should have focus. called by the focus manager when the user tabs to the frame rather than an element. obsolete since gecko 1.9.2 channelisunsafe boolean find out if the currently loaded document came from a suspicious channel (such as a jar channel where the server-re
turned content type is not a known jar type). read only. charset string the converter to use when reading the document's data. in mozilla code, all text is encoded as unicode. when reading a document, a converter is used to translate the text from its original format into unicode. this attribute lets you: see what converter was used when retrieving the document's dat...
...te. note: starting in gecko 8.0, isactive is false for documents in minimized windows. isapptab boolean sets whether a docshell is an app tab. an app tab docshell may behave differently than a non-app tab docshell in some cases, such as when handling link clicks. docshells are not app tabs unless told otherwise. isexecutingonloadhandler boolean re
turns true if the docshell is currently executing the onload handler. read only. isinunload boolean find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the new document has been set up) read only. isoffscreenbrowser boolean if true, this docshell is not visible in the traditional sense, but is bein...
...hell. this is set by browser or nswebbrowser for their root docshell. shouldsavelayoutstate boolean indicates whether the current page can be cached. read only. useerrorpages boolean attribute to access whether error pages are enabled. zoom float set/get the document scale factor. when setting this attribute, a ns_error_not_implemented error may be re
turned by implementations not supporting zoom. implementations not supporting zoom should re
turn 1.0 all the time for the get operation. 1.0 by the way is the default of zoom. this means 100% of normal scaling or in other words normal size no zoom. constants constant value description internal_load_flags_none 0x0 used as a placeholder when you don't want to explicit...
...And 8 more matches
nsILocalFile
h( in astring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/' . exceptions thrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. getrelativedescriptor() re
turns a relative file path in an opaque, cross platform format. it is therefore not a native path. acstring getrelativedescriptor( in nsilocalfile fromfile ); parameters fromfile the file from which the descriptor is relative. there is no defined result if this parameter is null. re
turn value an opaque string value with undefined character encoding. this string is not intended for display ...
...n an opaque, cross platform format. it is therefore not a native path. acstring getrelativedescriptor( in nsilocalfile fromfile ); parameters fromfile the file from which the descriptor is relative. there is no defined result if this parameter is null. re
turn value an opaque string value with undefined character encoding. this string is not intended for display to users. the result re
turned from this method may be used with setrelativedescriptor() to initialize a nsilocalfile instance. initwithfile() initializes this object with another file. void initwithfile( in nsilocalfile afile ); parameters afile the file this becomes equivalent to. initwithnativepath() used to set the full path that this nsilocalfile references. all current settings will be reset. void initwi...
... a string that specifies a platform-specific, full path to a file or directory. exceptions thrown ns_error_file_unrecognized_path indicates that filepath is not an absolute file path or that it contains characters that are invalid for the filesystem. launch() requests that the operating system attempt to open this file. void launch(); parameters none. native code only! load re
turns the result of pr_loadlibrary() on the file. the caller is responsible for calling pr_unloadlibrary() on the result. prlibrarystar load(); parameters none. re
turn value a pointer to a prlibrary. example #include "prlink.h" #include "nserror.h" #include "nsilocalfile.h" // load the dll corresponding to the given nsilocalfile... nsresult loaddll(nsilocalfile *alocalfile) { prlibrary *dl...
...And 8 more matches
nsILoginManagerStorage
ssword prompt is being shown. read only. methods addlogin() called by the login manager to store a new login. gecko 1.9.1 note default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them. void addlogin( in nsilogininfo alogin ); parameters alogin the login to add to the login storage. countlogins() implement this method to re
turn the number of logins matching the specified criteria. this method is called, for example, to check to see if there is a login that will match the criteria without having to ask the user for their master password in order to decrypt the logins. unsigned long countlogins( in astring ahostname, in astring aactionurl, in astring ahttprealm ); parameters ahostname the hostname to which to rest...
...is a login that will match the criteria without having to ask the user for their master password in order to decrypt the logins. unsigned long countlogins( in astring ahostname, in astring aactionurl, in astring ahttprealm ); parameters ahostname the hostname to which to restrict the search. specify an empty string to match all hosts. passing null should not match any logins, and should re
turn 0. aactionurl the url of the form to which the login will be submitted. to match any form login, specify an empty string. to not match to any form login, specify null. ahttprealm the http realm for which the login applies. to match logins for any realm, specify an empty string. to not match any realm, specify null. re
turn value the number of logins that match the specified criteria. findlogins()...
...od to search the login store for logins matching the specified criteria. this method is called by the login manager when looking for saved logins that might apply to a form or authentication request. void findlogins( out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins ); parameters count re
turn in this parameter the number of matching logins found by the search. ahostname the hostname to which to restrict the search. for example: "http://www.site.com". specify an empty string to match all hosts. passing null should not match any logins, and should re
turn a count of 0. aactionurl the url of the form to which the login will be submitted. to match any form login, specify an empty string. t...
...And 8 more matches
nsIMessenger
in acstring aurl); parameters awin a window. as far as i can tell this isn't used or checked. aurl the url to open. launchexternalurl() launches the nsiexternalprotocolservice and sends it the url. void launchexternalurl(in acstring aurl); parameters aurl the url to open. canundo() queries if there are any undo items in the transaction manager. ...
...e nsiexternalprotocolservice and sends it the url. void launchexternalurl(in acstring aurl); parameters aurl the url to open. canundo() queries if there are any undo items in the transaction manager. boolean canundo(); re
turn value boolean representing whether undo is available. canredo() queries if there are any redo items in the transaction manager. boolean canredo(); re
turn value boolean representing whether redo is available. getundotransactiontype() gets the type of the next undo transaction. unsigned long getundotransactiontype(); re
turn value a long representing the type of the transaction. see #constants for available types. getredotransactiontype() gets the type of the next redo transaction. available types are defined as constants in nsimessen...
...see #constants for available types. undo() performs the next undo transaction. void undo(in nsimsgwindow msgwindow); parameters msgwindow the nsimsgwindow to perform the undo transaction on. ...
...And 8 more matches
nsIScriptableIO
an empty filename string if you wish to get a reference to the directory itself. nsifile getfile( in astring alocation, in astring afilename ); parameters alocation a location key identifying a known standard directory. the afilename parameter is treated as being local to this directory. afilename the relative path of the file to generate a reference for. re
turn value re
turns an nsifile object referencing the specified file location. exceptions thrown ns_error_invalid_arg alocation was null. getfilewithpath() re
turns a file reference using an absolute file path to locate the file. note: you should avoid using this method, since file paths are platform-dependent and non-portable. instead, you should use getfile() and construct the path fro...
... to locate the file. note: you should avoid using this method, since file paths are platform-dependent and non-portable. instead, you should use getfile() and construct the path from the base location manually. nsifile getfilewithpath( in astring afilepath ); parameters afilepath the absolute pathname of the file to reference, or the value of a file's persistentdescriptor. re
turn value re
turns an nsifile object referencing the specified file location. exceptions thrown ns_error_invalid_arg afilepath was null. newuri() creates a uri object that implements the nsiuri interface. nsiuri newuri( in nsivariant auri ); parameters auri the file for which to create a new nsiuri object. this parameter may be specified either as a url string or a...
...e object referencing the specified file location. exceptions thrown ns_error_invalid_arg afilepath was null. newuri() creates a uri object that implements the nsiuri interface. nsiuri newuri( in nsivariant auri ); parameters auri the file for which to create a new nsiuri object. this parameter may be specified either as a url string or as an nsifile object. re
turn value re
turns an nsiuri object corresponding to the specified string or file. exceptions thrown ns_error_invalid_arg auri was null. newinputstream() retrieves a stream from which data can be read. nsisupports newinputstream( in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffer...
...And 8 more matches
Int64
d (or may need) values represented using a 64-bit data type. you use the int64 object to create and manipulate 64-bit signed integers. note: it's important to note that the 64-bit integer objects created by int64 are not int64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the int64 object. see 64-bit integers for details. syntax creates and re
turns a new 64-bit signed integer. int64 int64( value ); parameters value the value to assign the new 64-bit integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed ...
...er 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. re
turn value a new object representing the specified value. exceptions thrown typeerror the specified value cannot be converted into a 64-bit integer. either it's not a number, string, or 64-bit integer object, or it's a string that is incorrectly formatted or contains a value outside the range that can be represented in 64 bits. this will also be thrown if the source value is a floating-point num...
...represented as a 64-bit integer. method overview number compare(a, b); number hi(a); int64 join(high, low); number lo(a); string tosource(); string tostring([radix]); methods compare() compares two 64-bit integer values. number compare( a, b ); parameters a the first value to compare. b the second value to compare. ...
...And 8 more matches
Streams - Plugins
estroystream or the plug-in can call npn_destroystream. this applies to all plug-in modes except np_seek. note: a plug-in can also use the npn_geturl method to request a stream for an arbitrary url. telling the plug-in when a stream is deleted the browser calls the npp_destroystream method when it completes the stream sent to the plug-in, either successfully or abnormally. once the plug-in re
turns from this method, the browser deletes the npstream object. the plug-in can terminate the stream itself by calling npn_destroystream. you should delete any private data allocated in the plug-in's stream->pdata field when you destroy a stream. the plug-in can store private data associated with the stream in stream->pdata. the browser stores private data in stream->ndata; this value should not be ...
... the instance as it can handle at one time, and it helps both the browser and the plug-in to use their resources efficiently. after a call to npp_newstream, in which the plug-in requested a normal-mode stream, the browser delivers the data in the stream progressively in a series of calls to npp_writeready and npp_write. the browser calls npp_writeready before each call to npp_write. the value re
turned by npp_writeready indicates how many bytes the plug-in instance can accept for this stream. if the plug-in allocates memory for the entire stream at once, it can re
turn a large number. this number tells the browser that it can pass as much data to the instance as possible in a single call to npp_write. the browser can write a smaller amount of data if desired or necessary (for example, if only ...
...e browser that it can pass as much data to the instance as possible in a single call to npp_write. the browser can write a smaller amount of data if desired or necessary (for example, if only 8k 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. ...
...And 8 more matches
KeyboardEvent.getModifierState() - Web APIs
the keyboardevent.getmodifierstate() method re
turns the current state of the specified modifier key: true if the modifier is active (that is the modifier key is pressed or locked), otherwise, false. syntax var active = event.getmodifierstate(keyarg); re
turns a boolean parameters keyarg a modifier key value. the value must be one of the keyboardevent.key values which represent modifier keys, or the string "accel" . this is case-sensitive. modifier keys on internet explorer ie9 uses "scroll" for "scrolllock" and "win" for "os". ...
... syntax var active = event.getmodifierstate(keyarg); re
turns a boolean parameters keyarg a modifier key value. the value must be one of the keyboardevent.key values which represent modifier keys, or the string "accel" . this is case-sensitive. modifier keys on internet explorer ie9 uses "scroll" for "scrolllock" and "win" for "os". ...
... ctrl key, control key or menu key pressed. "fn" not supported function key is pressed, but we're not sure what key makes the modifier state active. fn key on mac keyboard doesn't cause this active. ...
...And 8 more matches
MediaDevices.getUserMedia() - Web APIs
ith tracks containing the requested types of media. that stream can include, for example, a video track (produced by either a hardware or virtual video source such as a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, a/d converter, or the like), and possibly other track types. it re
turns a promise that resolves to a mediastream object. if the user denies permission, or matching media is not available, then the promise is rejected with notallowederror or notfounderror respectively. note: it's possible for the re
turned promise to neither resolve nor reject, as the user is not required to make a choice at all and may simply ignore the request. generally, you will access the med...
...a mediastreamconstraints object specifying the types of media to request, along with any requirements for each type. the constraints parameter is a mediastreamconstraints object with two members: video and audio, describing the media types requested. either or both must be specified. if the browser cannot find all media tracks with the specified types that meet the constraints given, then the re
turned promise is rejected with notfounderror. the following requests both audio and video without any specific requirements: { audio: true, video: true } if true is specified for a media type, the resulting stream is required to have that type of track in it. if one cannot be included for any reason, the call to getusermedia() will result in an error. while information about a user's cameras ...
...an error. while information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. ...
...And 8 more matches
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 re
turns 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 submitte...
...entation of the sessiondescription parameter is technically of type rtcsessiondescriptioninit, but because rtcsessiondescription serializes to be indistinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. ...
...ondescription serializes to be indistinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. ...
...And 8 more matches
Using XMLHttpRequest - Web APIs
*/ /* dosomething(odata); */ /* console.log("ajaxsubmit - the form is now serialized. submitting..."); */ submitdata (odata); } function pushsegment (ofrevt) { this.owner.segments[this.segmentidx] += ofrevt.target.result + "\r\n"; this.owner.status--; processstatus(this.owner...
...egment (ofrevt) { this.owner.segments[this.segmentidx] += ofrevt.target.result + "\r\n"; this.owner.status--; processstatus(this.owner); } function plainescape (stext) { /* how should i treat a text/plain form encoding? what characters are not allowed? this is what i suppose...: */ /* "4\3\7 - einstein said e=mc2" ----> "4\\3\\7\ -\ einstein\ said\ e\=mc2" */ re
turn stext.replace(/[\s\=\\]/g, "\\$&"); } function submitrequest (otarget) { var nfile, sfieldtype, ofield, osegmreq, ofile, bispost = otarget.method.tolowercase() === "post"; /* console.log("ajaxsubmit - serializing form..."); */ this.contenttype = bispost && otarget.enctype ? otarget.enctype : "application\/x-www-form-urlencoded"; this.technique = bispost ? this.content...
....push( this.technique === 3 ? ...
...And 8 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
ers marked [important]: objid_alert objid_caret objid_client [important] objid_cursor objid_hscroll objid_nativeom [important? might be useful for supporting custom interfaces, need to research] objid_menu objid_queryclassnameidx objid_sizegrip objid_sound objid_sysmenu objid_titlebar objid_vscroll objid_window [important, but implemented automatically by microsoft windows. will re
turn object of type role_window. see windowfromaccessibleobject quirk explanation below.] dealing with the quirks of msaa msaa has a well deseved reputation for quirkiness. it is not "plug and play", and will take a lot of testing/refinement before your solution works with any product. here are some of it's quirks and some solutions/workarounds: msaa can be crash prone problem: many of msaa's cra...
...ent or ui object it refers to goes away. the easiest way to do that is to keep a pointer to an accessible in each internal ui object. if that pointer is non-null, then there is an accessible object for it. whenever the ui object is destroyed, shutdown it's accessible object as well. in gecko/mozilla we are not allowed to keep this extra pointer for each accessible object, so when accessibility is
turned on we use a hash table to cache these objects. such a cache must be kept in perfect sync with the tree of ui and document objects, which is difficult. therefore, unless 4 bytes extra on each object is criticial in your application, just keep the extra pointer around instead of using a hash table. also, don't implement event_object_create or event_object_destroy. vendors have found that watchin...
...an easily happen merely by having two listboxes visible at the same time, because selected listbox items use the system highlight color, even when the listbox itself is not focused. other problems occur when a piece of static text which has the same color background, which will cause that text to be repeated each time the focus or highlight moves. at least one major screen reader has a feature to
turn highlight tracking off, but that's only a global setting, and
turning off highlight tracking globally also
turns off the speaking of menu items. solution: don't use the system highlight color for items that you don't want spoken when the highlight or focus moves. to fix this for standard listboxes, use owner drawn list items, so that you can change the highlight color when an item doesn't have f...
...And 8 more matches
Control flow and error handling - JavaScript
objects—evaluate to true when passed to a conditional statement. ...
...ve boolean values true and false with the true and false values of the boolean object! for example: var b = new boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false example in the following example, the function checkdata re
turns true if the number of characters in a text object is three. otherwise, it displays an alert and re
turns false. function checkdata() { if (document.form1.threechar.value.length == 3) { re
turn true; } else { alert( 'enter exactly three characters. ' + `${document.form1.threechar.value} is not valid.`); re
turn false; } } switch statement a switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. if a...
...w statement use the throw statement to throw an exception. a throw statement specifies the value to be thrown: throw expression; you may throw any expression, not just expressions of a specific type. the following code throws several exceptions of varying types: throw 'error2'; // string type throw 42; // number type throw true; // boolean type throw {tostring: function() { re
turn "i'm an object!"; } }; note: you can specify an object when you throw an exception. you can then reference the object's properties in the catch block. // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the error console) userexc...
...And 8 more matches
Details of the object model - JavaScript
llowing statement: var mark = new workerbee; when javascript sees the new operator, it creates a new generic object and implicitly sets the value of the internal property [[prototype]] to the value of workerbee.prototype and passes this new object as the value of the this keyword to the workerbee constructor function. the internal [[prototype]] property determines the prototype chain used to re
turn property values. once these properties are set, javascript re
turns the new object and the assignment statement sets the variable mark to that object. this process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. when you ask for the value of a property, javascript first checks to see if the value exists in that objec...
...if no such property is found, javascript says the object does not have the property. ...
...if no such property is found, javascript says the object does not have the property. ...
...And 8 more matches
Default parameters - JavaScript
r, it's often useful to set a different default value. this is where default parameters can help. in the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. ...
...efault value. this is where default parameters can help. in the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. in the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would re
turn nan. ...
...iply is called, b's value would be undefined when evaluating a * b and multiply would re
turn nan. function multiply(a, b) { re
turn a * b } multiply(5, 2) // 10 multiply(5) // nan ! to guard against this, something like the second line would be used, where b is set to 1 if multiply is called with only one argument: function multiply(a, b) { b = (typeof b !== 'undefined') ? b : 1 re
turn a * b } multiply(5, 2) // 10 multiply(5) // 5 with default parameters in es2015, checks in the function body are no longer necessary. now, you can assign 1 as the default value for b in the function head: function multiply(a, b = 1) { re
turn a * b } multiply(5, 2) // 10 multiply(5) // 5 multiply(5, undefined) // 5 examples passing undefined vs. other falsy val...
...And 8 more matches
Functions - JavaScript
generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. like the program itself, a function is composed of a sequence of statements called the function body. values can be passed to a function, and the function will re
turn a value. in javascript, functions are first-class objects, because they can have properties and methods just like any other object. ...
...have properties and methods just like any other object. what distinguishes them from other objects is that functions can be called. in brief, they are function objects. for more examples and explanations, see also the javascript guide about functions. description every function in javascript is a function object. see function for information on properties and methods of function objects. to re
turn a value other than the default, a function must have a re
turn statement that specifies the value to re
turn. a function without a re
turn statement will re
turn a default value. in the case of a constructor called with the new keyword, the default value is the value of its this parameter. for all other functions, the default re
turn value is undefined. the parameters of a function call are the funct...
...unctions for details): ([param[, param]]) => { statements } param => expression param the name of an argument. zero arguments need to be indicated with (). for only one argument, the parentheses are not required. (like foo => 1) statements or expression multiple statements need to be enclosed in brackets. a single expression requires no brackets. the expression is also the implicit re
turn value of the function. the function constructor note: using the function constructor to create functions is not recommended since it needs the function body as a string which may prevent some js engine optimizations and can also cause other problems. as all other objects, function objects can be created using the new operator: new function (arg1, arg2, ... argn, functionbody) arg1, arg...
...And 8 more matches
Array.prototype.reduceRight() - JavaScript
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. see also array.prototype.reduce() for left-to-right. syntax arr.reduceright(callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters callback function to execute on each value in the array, taking four arguments: accumulator the value previously re
turned in the last invocation of the callback, or initialvalue, if supplied. (see below.) currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array reduceright() was called upon. initialvalueoptional value to use as accumulator to the first call of the callback. if no initial val...
... the index of the current element being processed in the array. arrayoptional the array reduceright() was called upon. initialvalueoptional value to use as accumulator to the first call of the callback. if no initial value is supplied, the last element in the array will be used and skipped. calling reduce or reduceright on an empty array without an initial value creates a typeerror. re
turn value the value that results from the reduction. description reduceright executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring. the call to the reduceright...
...value was provided, then accumulator will be equal to the last value in the array and currentvalue will be equal to the second-to-last value. if the array is empty and no initialvalue was provided, typeerror would be thrown. ...
...And 8 more matches
Array.prototype.every() - JavaScript
the every() method tests whether all elements in the array pass the test implemented by the provided function. it re
turns a boolean value. 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 arr.every(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. index optional the index of the current element being processed in the array. ...
...k(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array every was called upon. thisarg optional a value to use as this when executing callback. ...
...rameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array every was called upon. thisarg optional a value to use as this when executing callback. re
turn value true if the callback function re
turns a truthy value for every array element. otherwise, false. description the every method executes the provided callback function once for each element present in the array until it finds the one where callback re
turns a falsy value. if such an element is found, the every method immediately re
turns false. otherwise, if callback re
turns a truthy value for all elements, every re
turns true. cautio...
...And 8 more matches
Array.prototype.filter() - JavaScript
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 let newarray = arr.filter(callback(element[, index, [array]])[, thisarg]) parameters callback function is a predicate, to test each element of the array. ...
...s a predicate, to test each element of the array. re
turn true to keep the element, false otherwise. it accepts three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array filter was called upon. thisargoptional value to use as this when executing callback. re
turn value a new array with the elements that pass the test. if no elements pass the test, an empty array will be re
turned. description filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback re
turns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is ...
... if (func(t[i], i, t)){ res[c++] = kvalue; } } } } else{ while (++i !== len){ // checks to see if the key was set if (i in this){ kvalue = t[i]; if (func.call(thisarg, t[i], i, t)){ res[c++] = kvalue; } } } } res.length = c; // shrink down array to proper size re
turn res; }; } examples filtering out all small values the following example uses filter() to create a filtered array that has all elements with values less than 10 removed. function isbigenough(value) { re
turn value >= 10 } let filtered = [12, 5, 8, 130, 44].filter(isbigenough) // filtered is [12, 130, 44] find all prime numbers in an array the following example re
turns all prime numbers ...
...And 8 more matches
Date.parse() - JavaScript
2015-02-31). it is not recommended to use date.parse as until es5, parsing of strings was entirely implementation dependent. there are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated). the source for this interactive example is stored in a github repository. ...
...te to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax direct call: date.parse(datestring) implicit call: new date(datestring) parameters datestring a string representing a simplification of the iso 8601 calendar date extended format. (other formats may be used, but results are implementation-dependent.) re
turn value a number representing the milliseconds elapsed since january 1, 1970, 00:00:00 utc and the date obtained by parsing the given string representation of a date. if the argument doesn't represent a valid date, nan is re
turned. description the parse() method takes a date string (such as "2011-10-10t14:48:00") and re
turns the number of milliseconds since january 1, 1970, 00:00:00 utc. this f...
...rm), "2011-10-10t14:48:00" (date-time form), or "2011-10-10t14:48:00.000+09:00" (date-time form with milliseconds and time zone) can be passed and will be parsed. when the time zone offset is absent, date-only forms are interpreted as a utc time and date-time forms are interpreted as local time. while time zone specifiers are used during date string parsing to interpret the argument, the value re
turned is always the number of milliseconds between january 1, 1970 00:00:00 utc and the point in time represented by the argument or nan. because parse() is a static method of date, it is called as date.parse() rather than as a method of a date instance. fall-back to implementation-specific date formats this section contains implementation-specific behavior that can be inconsistent across impleme...
...And 8 more matches
Int16Array - JavaScript
in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int16array() creates a new int16array object. static properties int16array.bytes_per_element re
turns a number value of the element size. 2 in the case of an int16array. int16array.name re
turns the string value of the constructor name. in the case of the int16array type: "int16array". static methods int16array.from() creates a new int16array from an array-like or iterable object. see also array.from(). int16array.of() creates a new int16array with a variable number of arguments. see al...
...int16array.name re
turns the string value of the constructor name. in the case of the int16array type: "int16array". static methods int16array.from() creates a new int16array from an array-like or iterable object. see also array.from(). int16array.of() creates a new int16array with a variable number of arguments. see also array.of(). instance properties int16array.prototype.buffer re
turns the arraybuffer referenced by the int16array fixed at construction time and thus read only. int16array.prototype.bytelength re
turns the length (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.byteoffset re
turns the offset (in bytes) of the int16array from the start of its arraybuffer. fixed at construction tim...
...t construction time and thus read only. int16array.prototype.bytelength re
turns the length (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.byteoffset re
turns the offset (in bytes) of the int16array from the start of its arraybuffer. fixed at construction time and thus read only. int16array.prototype.length re
turns the number of elements hold in the int16array. fixed at construction time and thus read only. instance methods int16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int16array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototy...
...And 8 more matches
Int32Array - JavaScript
in the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int32array() creates a new int32array object. static properties int32array.bytes_per_element re
turns a number value of the element size. 4 in the case of an int32array. int32array.name re
turns the string value of the constructor name. in the case of the int32array type: "int32array". static methods int32array.from() creates a new int32array from an array-like or iterable object. see also array.from(). int32array.of() creates a new int32array with a variable number of arguments. see al...
...int32array.name re
turns the string value of the constructor name. in the case of the int32array type: "int32array". static methods int32array.from() creates a new int32array from an array-like or iterable object. see also array.from(). int32array.of() creates a new int32array with a variable number of arguments. see also array.of(). instance properties int32array.prototype.buffer re
turns the arraybuffer referenced by the int32array fixed at construction time and thus read only. int32array.prototype.bytelength re
turns the length (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.byteoffset re
turns the offset (in bytes) of the int32array from the start of its arraybuffer. fixed at construction tim...
...t construction time and thus read only. int32array.prototype.bytelength re
turns the length (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.byteoffset re
turns the offset (in bytes) of the int32array from the start of its arraybuffer. fixed at construction time and thus read only. int32array.prototype.length re
turns the number of elements hold in the int32array. fixed at construction time and thus read only. instance methods int32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int32array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototy...
...And 8 more matches
Int8Array - JavaScript
the int8array typed array represents an array of twos-complement 8-bit signed integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor int8array() creates a new int8array object. static properties int8array.bytes_per_element re
turns a number value of the element size. 1 in the case of an int8array. int8array.name re
turns the string value of the constructor name. in the case of the int8array type: "int8array". static methods int8array.from() creates a new int8array from an array-like or iterable object. see also array.from(). int8array.of() creates a new int8array with a variable number of arguments. see also array.of...
...array. int8array.name re
turns the string value of the constructor name. in the case of the int8array type: "int8array". static methods int8array.from() creates a new int8array from an array-like or iterable object. see also array.from(). int8array.of() creates a new int8array with a variable number of arguments. see also array.of(). instance properties int8array.prototype.buffer re
turns the arraybuffer referenced by the int8array fixed at construction time and thus read only. int8array.prototype.bytelength re
turns the length (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.byteoffset re
turns the offset (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and...
...xed at construction time and thus read only. int8array.prototype.bytelength re
turns the length (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.byteoffset re
turns the offset (in bytes) of the int8array from the start of its arraybuffer. fixed at construction time and thus read only. int8array.prototype.length re
turns the number of elements hold in the int8array. fixed at construction time and thus read only. instance methods int8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). int8array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototype.
...And 8 more matches
Comparing Reflect and Object methods - JavaScript
although some of the methods appear to be similar in their behavior, there are often subtle differences between them. the table below details the differences between the methods available on the object and reflect apis. please note that if a method does not exist in an api, it is marked as n/a. ...
...n their behavior, there are often subtle differences between them. the table below details the differences between the methods available on the object and reflect apis. please note that if a method does not exist in an api, it is marked as n/a. method name object reflect defineproperty() object.defineproperty() re
turns the object that was passed to the function. re
turns a typeerror if the property was not successfully defined on the object. reflect.defineproperty() re
turns true if the property was defined on the object and false if it was not. defineproperties() object.defineproperties() re
turns the objects that were passed to the function. re
turns a typeerror if any properties were not successfully defined on the object. n/a set() ...
...perty was not successfully defined on the object. reflect.defineproperty() re
turns true if the property was defined on the object and false if it was not. defineproperties() object.defineproperties() re
turns the objects that were passed to the function. re
turns a typeerror if any properties were not successfully defined on the object. n/a set() n/a reflect.set() re
turns true if the property was set successfully on the object and false if it was not. throws a typeerror if the target was not an object. get() n/a reflect.get() re
turns the value of the property. throws a typeerror if the target was not an object. ...
...And 8 more matches
Symbol - JavaScript
a symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. ...
... a symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. ...
...sing the symbol() function will not create a global symbol that is available in your whole codebase. to create symbols available across files and even across realms (each of which has its own global scope), use the methods symbol.for() and symbol.keyfor() to set and retrieve symbols from the global symbol registry. finding symbol properties on objects the method object.getownpropertysymbols() re
turns an 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 sym...
...And 8 more matches
TypedArray - JavaScript
fer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specified arraybuffer. the byteoffset and length parameters specify the memory range that will be exposed by the typed array view. if both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed. static properties typedarray.bytes_per_element re
turns a number value of the element size for the different typedarray objects. typedarray.name re
turns the string value of the constructor name (e.g, "int8array"). get typedarray[@@species] the constructor function used to create derived objects. typedarray.prototype prototype for typedarray objects. static methods typedarray.from() creates a new typedarray from an array-like or iterable o...
...] the constructor function used to create derived objects. typedarray.prototype prototype for typedarray objects. static methods typedarray.from() creates a new typedarray from an array-like or iterable object. see also array.from(). typedarray.of() creates a new typedarray with a variable number of arguments. see also array.of(). instance properties typedarray.prototype.buffer re
turns the arraybuffer referenced by the typed array. fixed at construction time and thus read only. typedarray.prototype.bytelength re
turns the length (in bytes) of the typed array. fixed at construction time and thus read only. typedarray.prototype.byteoffset re
turns the offset (in bytes) of the typed array from the start of its arraybuffer. fixed at construction time and thus read only. typedar...
...nced by the typed array. fixed at construction time and thus read only. typedarray.prototype.bytelength re
turns the length (in bytes) of the typed array. fixed at construction time and thus read only. typedarray.prototype.byteoffset re
turns the offset (in bytes) of the typed array from the start of its arraybuffer. fixed at construction time and thus read only. typedarray.prototype.length re
turns the number of elements held in the typed array. fixed at construction time and thus read only. instance methods typedarray.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). typedarray.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.protot...
...And 8 more matches
Uint16Array - JavaScript
the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint16array() creates a new uint16array object. static properties uint16array.bytes_per_element re
turns a number value of the element size. 2 in the case of an uint16array. uint16array.name re
turns the string value of the constructor name. in the case of the uint16array type: "uint16array". static methods uint16array.from() creates a new uint16array from an array-like or iterable object. see also array.from(). uint16array.of() creates a new uint16array with a variable number of arguments...
...ray.name re
turns the string value of the constructor name. in the case of the uint16array type: "uint16array". static methods uint16array.from() creates a new uint16array from an array-like or iterable object. see also array.from(). uint16array.of() creates a new uint16array with a variable number of arguments. see also array.of(). instance properties uint16array.prototype.buffer re
turns the arraybuffer referenced by the uint16array fixed at construction time and thus read only. uint16array.prototype.bytelength re
turns the length (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.byteoffset re
turns the offset (in bytes) of the uint16array from the start of its arraybuffer. fixed at constructio...
...struction time and thus read only. uint16array.prototype.bytelength re
turns the length (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.byteoffset re
turns the offset (in bytes) of the uint16array from the start of its arraybuffer. fixed at construction time and thus read only. uint16array.prototype.length re
turns the number of elements hold in the uint16array. fixed at construction time and thus read only. instance methods uint16array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint16array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prot...
...And 8 more matches
Uint32Array - JavaScript
the platform byte order. if control over byte order is needed, use dataview instead. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint32array() creates a new uint32array object. static properties uint32array.bytes_per_element re
turns a number value of the element size. 4 in the case of an uint32array. uint32array.name re
turns the string value of the constructor name. in the case of the uint32array type: "uint32array". static methods uint32array.from() creates a new uint32array from an array-like or iterable object. see also array.from(). uint32array.of() creates a new uint32array with a variable number of arguments...
...ray.name re
turns the string value of the constructor name. in the case of the uint32array type: "uint32array". static methods uint32array.from() creates a new uint32array from an array-like or iterable object. see also array.from(). uint32array.of() creates a new uint32array with a variable number of arguments. see also array.of(). instance properties uint32array.prototype.buffer re
turns the arraybuffer referenced by the uint32array fixed at construction time and thus read only. uint32array.prototype.bytelength re
turns the length (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.byteoffset re
turns the offset (in bytes) of the uint32array from the start of its arraybuffer. fixed at constructio...
...struction time and thus read only. uint32array.prototype.bytelength re
turns the length (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.byteoffset re
turns the offset (in bytes) of the uint32array from the start of its arraybuffer. fixed at construction time and thus read only. uint32array.prototype.length re
turns the number of elements hold in the uint32array. fixed at construction time and thus read only. instance methods uint32array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint32array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prot...
...And 8 more matches
Uint8Array - JavaScript
the uint8array typed array represents an array of 8-bit unsigned integers. the contents are initialized to 0. once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). constructor uint8array() creates a new uint8array object. static properties uint8array.bytes_per_element re
turns a number value of the element size. 1 in the case of an uint8array. uint8array.name re
turns the string value of the constructor name. in the case of the uint8array type: "uint8array". static methods uint8array.from() creates a new uint8array from an array-like or iterable object. see also array.from(). uint8array.of() creates a new uint8array with a variable number of arguments. see also array.of()...
...uint8array.name re
turns the string value of the constructor name. in the case of the uint8array type: "uint8array". static methods uint8array.from() creates a new uint8array from an array-like or iterable object. see also array.from(). uint8array.of() creates a new uint8array with a variable number of arguments. see also array.of(). instance properties uint8array.prototype.buffer re
turns the arraybuffer referenced by the uint8array fixed at construction time and thus read only. uint8array.prototype.bytelength re
turns the length (in bytes) of the uint8array. fixed at construction time and thus read only. uint8array.prototype.byteoffset re
turns the offset (in bytes) of the uint8array from the start of its arraybuffer. fixed at construction time and thus read only. uint8array.
...ferenced by the uint8array fixed at construction time and thus read only. uint8array.prototype.bytelength re
turns the length (in bytes) of the uint8array. fixed at construction time and thus read only. uint8array.prototype.byteoffset re
turns the offset (in bytes) of the uint8array from the start of its arraybuffer. fixed at construction time and thus read only. uint8array.prototype.length re
turns the number of elements held in the uint8array. fixed at construction time and thus read only. instance methods uint8array.prototype.copywithin() copies a sequence of array elements within the array. see also array.prototype.copywithin(). uint8array.prototype.entries() re
turns a new array iterator object that contains the key/value pairs for each index in the array. see also array.prototy...
...And 8 more matches
parseInt() - JavaScript
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 parseint(string [, radix]) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. ...
...ment is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. be careful—this does not default to 10! the description below explains in more detail what happens when radix is not provided. ...
...default to 10! the description below explains in more detail what happens when radix is not provided. re
turn value an integer parsed from the given string. or nan when the radix is smaller than 2 or bigger than 36, or the first non-whitespace character cannot be converted to a number. description the parseint function converts its first argument to a string, parses that string, then re
turns an integer or nan. if not nan, the re
turn value will be the integer that is the first argument taken as a number in the specified radix. (for example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.) for radices above 10, letters of the english alphabet indicate numerals greater than 9. for example, for hexadecimal numbers (base 16), a throu...
...And 8 more matches
in operator - JavaScript
the in operator re
turns true if the specified property is in the specified object or its prototype chain. 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 prop in object parameters prop a string or symbol representing a property name or array index (non-symbols will be coerced to strings). object object to check if it (or its prototype chain) contains the property with specified name (prop). examples basic usage the following examples show some uses of the in operator. ...
...ers prop a string or symbol representing a property name or array index (non-symbols will be coerced to strings). object object to check if it (or its prototype chain) contains the property with specified name (prop). examples basic usage the following examples show some uses of the in operator. ...
...presenting a property name or array index (non-symbols will be coerced to strings). object object to check if it (or its prototype chain) contains the property with specified name (prop). examples basic usage the following examples show some uses of the in operator. ...
...And 8 more matches
context-menu - Archive of obsolete content
ttern strings. when matchpattern is an array, the context occurs when the menu is invoked on a page whose url matches any of the patterns. these are the same match pattern strings that you use with the page-mod include property. read more about patterns. predicatecontext(predicatefunction) predicatefunction is called when the menu is invoked, and the context occurs when the function re
turns a true value. the function is passed an object with properties describing the menu invocaton context. array an array of any of the other types. this context occurs when all contexts in the array occur. menu items also have a context property that can be used to add and remove declarative contexts after construction. for example: var context = require("sdk/context-menu").selec...
...ontent scripts. like other apis in the sdk, the context-menu api uses content scripts to let your add-on interact with pages in the browser. each menu item you create in the top-level context menu can have a content script. a special event named "context" is emitted in your content scripts whenever the context menu is about to be shown. ...
...this is the node in the page that the user context-clicked to invoke the menu. you can use it to determine whether your item should be shown. you can both specify declarative contexts and listen for contexts in a content script. ...
...And 7 more matches
io/file - Archive of obsolete content
indows-style paths, be sure to escape backslashes in strings. for example, to specify the file at c:\users\myk, you need to use the string "c:\\users\\myk", not "c:\users\myk". read more about escaping characters in strings. globals functions basename(path) the path parameter must be an absolute path, relative paths will cause an error. use the fs/path module for relative path support. re
turns the last component of the given path. for example, basename("/foo/bar/baz") re
turns "baz". if the path has no components, the empty string is re
turned. parameters path : string the path of a file. re
turns string : the last component of the given path. dirname(path) re
turns the path of the directory containing the given file. if the file is at the top of the volume, the empty string is ret...
...ame("/foo/bar/baz") re
turns "baz". if the path has no components, the empty string is re
turned. parameters path : string the path of a file. re
turns string : the last component of the given path. dirname(path) re
turns the path of the directory containing the given file. if the file is at the top of the volume, the empty string is re
turned. parameters path : string the path of a file. re
turns string : the path of the directory containing the file. exists(path) re
turns true if a file exists at the given path and false otherwise. parameters path : string the path of a file. re
turns boolean : true if the file exists and false otherwise. join(...) takes a variable number of strings, joins them on the file system's path separator, and re
turns the result. parameters ... : strin...
...f a file exists at the given path and false otherwise. parameters path : string the path of a file. re
turns boolean : true if the file exists and false otherwise. join(...) takes a variable number of strings, joins them on the file system's path separator, and re
turns the result. parameters ... : strings a variable number of strings to join. the first string must be an absolute path. re
turns string : a single string formed by joining the strings on the file system's path separator. list(path) re
turns an array of file names in the given directory. parameters path : string the path of the directory. re
turns array : an array of file names. each is a basename, not a full path. mkpath(path) makes a new directory named by the given path. any subdirectories that do not exist are ...
...And 7 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
without risk of remote execution. json templating jsontodom.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc, nodes) { function namespace(name) { var reelemnameparts = /^(?:(.*):)?(.*)$/.exec(name); re
turn { namespace: jsontodom.namespaces[reelemnameparts[1]], shortname: reelemnameparts[2] }; } // note that 'elemnameorarray' is: either the full element name (eg. [html:]div) or an array of elements in json notation function tag(elemnameorarray, elemattr) { // array of elements? parse each one... if (array.isarray(elemnameorarray)) { var frag = doc.createdocu...
...eg. [html:]div) or an array of elements in json notation function tag(elemnameorarray, elemattr) { // array of elements? parse each one... if (array.isarray(elemnameorarray)) { var frag = doc.createdocumentfragment(); array.foreach(arguments, function(thiselem) { frag.appendchild(tag.apply(null, thiselem)); }); re
turn frag; } // single element? parse element namespace prefix (if none exists, default to defaultnamespace), and create element var elemns = namespace(elemnameorarray); var elem = doc.createelementns(elemns.namespace || jsontodom.defaultnamespace, elemns.shortname); // set element's attributes and/or callback functions (eg. onclick) for (var key in el...
...event listeners can be defined on the given nodes by passing functions rather than strings to on* attributes: var href = "http://www.google.com/"; var text = "google"; var nodes = {}; document.documentelement.appendchild( jsont...
...And 7 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
users of netscape 6, netscape 7, compuserve 7, mozilla, opera will not be able to view the site properly. misidentifying browsers a common mistake web authors make is to assume that if a browser is not netscape navigator 4, it must be internet explorer and vice versa. for example: // wrong approach - do not use! if (document.all) { // internet explorer 4+ elm = docum...
... <frameset rows="30,*"> <frame src="foo.html"> <frame src="bar.html"> <noframes> <body> <p> this page requires frames. see <a href="noframes.html">sitemap</a>. </p> </body> </noframes> </frameset> </html> using noscript to support non-scriptable browsers some browsers may not support scripting while some users may have scripting support
turned off in their browser. use the noscript tag to provide these users with alternative unscripted versions of your pages or to at least notify them of the need to use scripting in order to view your content properly. since browsers such as netscape navigator 4 and internet explorer 4 do not support some of the most recent additions to the javascript (ecmascript) standard, it is often necessary to ...
...ur content properly. since browsers such as netscape navigator 4 and internet explorer 4 do not support some of the most recent additions to the javascript (ecmascript) standard, it is often necessary to limit the use of advanced javascript features such as exception processing. one approach is to require that users of browsers which do not support the level of javascript used in your content to
turn off javascript in order to be able to use your content. you can do this by providing an error message for users of older browsers as well as alternative content contained in noscript tags. <html> <head> <title>noscript</title> </head> <body> <script language="javascript"> window.onerror = function () { // redirect user to a page describing the limitations ...
...And 7 more matches
Parsing microformats in JavaScript - Archive of obsolete content
ally retrieves a date from a microformat node. after getting the text, it is normalized into an iso 8601 date. normalizeddate = microformats.parser.datetimegetter(propnode, parentnode); parameters propnode the dom node to check. parentnode the property's parent node. if it is a subproperty, this is the parent property node. otherwise this is the microformat node. re
turn value a string containing the normalized date. defaultgetter() uses the microformat patterns to decide what the correct text for a given microformat property is. this includes looking at thing such as abbr, img and alt, area and alt, and value excerpting. propertyvalue = microformats.parser.defaultgetter(propnode, parentnode, datatype); parameters propnode the dom node to check...
....parser.defaultgetter(propnode, parentnode, datatype); parameters propnode the dom node to check. parentnode the property's parent node. if it is a subproperty, this is the parent property node. otherwise this is the microformat node. datatype "html" if the search should be done using innerhtml(), or "text" to use innertext(). the default is "text". re
turn value a string containing the property's value. emailgetter() specifically retrieves an email address from a microformat node. this removes the subject if one is specified, as well as the mailto: prefix. email = microformats.parser.emailgetter(propnode, parentnode); parameters propnode the dom node to check. parentnode the property's parent node. if it is a subproper...
...eves an email address from a microformat node. this removes the subject if one is specified, as well as the mailto: prefix. email = microformats.parser.emailgetter(propnode, parentnode); parameters propnode the dom node to check. parentnode the property's parent node. if it is a subproperty, this is the parent property node. otherwise this is the microformat node. ...
...And 7 more matches
Client-side storage - Learn web development
useful. the storage.setitem() method allows you to save a data item in storage — it takes two parameters: the name of the item, and its value. try typing this into your javascript console (change the value to your own name, if you wish!): localstorage.setitem('name','chris'); the storage.getitem() method takes one parameter — the name of a data item you want to retrieve — and re
turns the item's value. now type these lines into your javascript console: let myname = localstorage.getitem('name'); myname upon typing in the second line, you should see that the myname variable now contains the value of the name data item. the storage.removeitem() method takes one parameter — the name of a data item you want to remove — and removes that item out of web storage. type...
...d see that the myname variable now contains the value of the name data item. the storage.removeitem() method takes one parameter — the name of a data item you want to remove — and removes that item out of web storage. type the following lines into your javascript console: localstorage.removeitem('name'); let myname = localstorage.getitem('name'); myname the third line should now re
turn null — the name item no longer exists in the web storage. the data persists! one key feature of web storage is that the data persists between page loads (and even when the browser is shut down, in the case of localstorage). let's look at this in action. open our web storage blank template again, but this time in a different browser to the one you've got this tutorial open in! this wi...
...calstorage). let's look at this in action. open our web storage blank template again, but this time in a different browser to the one you've got this tutorial open in! this will make it easier to deal with. type these lines into the browser's javascript console: localstorage.setitem('name','chris'); let myname = localstorage.getitem('name'); myname you should see the name item re
turned. now close down the browser and open it up again. enter the following lines again: let myname = localstorage.getitem('name'); myname you should see that the value is still available, even though the browser has been closed and then opened again. separate storage for each domain there is a separate data store for each domain (each separate web address loaded in the browser...
...And 7 more matches
Third-party APIs - Learn web development
able). the api key, which has to be specified in the api-key url parameter (the value is taken from the key variable). the page number, which has to be specified in the page url parameter (the value is taken from the pagenumber variable). the search term, which has to be specified in the q url parameter (the value is taken from the value of the searchterm text <input>). the document type to re
turn results for, as specified in an expression passed in via the fq url parameter. in this case, we want to re
turn articles. next, we use a couple of if() statements to check whether the startdate and enddate <input>s have had values filled in on them. if they do, we append their values to the url, specified in begin_date and end_date url parameters respectively. so, a complete url would end up lo...
...rs (pattern="[0-9]{8}"). see form data validation for more details on how these work. requesting data from the api now we've constructed our url, let's make a request to it. we'll do this using the fetch api. add the following code block inside the fetchresults() function, just above the closing curly brace: // use fetch() to make the request to the api fetch(url).then(function(result) { re
turn result.json(); }).then(function(json) { displayresults(json); }); here we run the request by passing our url variable to fetch(), convert the response body to json using the json() function, then pass the resulting json to the displayresults() function so the data can be displayed in our ui. displaying the data ok, let's look at how we'll display the data. add the following function below yo...
...esults() function. ...
...And 7 more matches
Useful string methods - Learn web development
ed to know about most of these early on in your learning journey. but there are a few that you'll potentially use quite often that we'll look at here. let's enter some examples into the browser developer console. finding the length of a string this is easy — you simply use the length property. ...
... should re
turn the number 7, because "mozilla" is 7 characters long. this is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length. retrieving a specific string character on a related note, you can re
turn any character inside a string by using square bracket notation — this means you include square brackets ([]) on the end of your variable name. ...
...ow that a username they have entered into a form field is too long if it is over a certain length. retrieving a specific string character on a related note, you can re
turn any character inside a string by using square bracket notation — this means you include square brackets ([]) on the end of your variable name. inside the square brackets you include the number of the character you want to re
turn, so for example to retrieve the first letter you'd do this: browsertype[0]; remember: computers count from 0, not 1! you could use this to, for example, find the first letter of a series of strings and order them alphabetically. to retrieve the last character of any string, we could use the following line, combining this technique with the length property we looked at above: browsertype[brows...
...And 7 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
for editing the name of a task yet. we'll get to that in a moment. to start with, we can at least implement an edittask() function in app.js. it’ll be similar to deletetask() because it'll take an id to find its target object, but it'll also take a newname property containing the name to update the task to. ...
...rray.prototype.filter() because we want to re
turn a new array with some changes, instead of deleting something from the array. ...
......
...And 7 more matches
Introduction to automated testing - Learn web development
dule: use a task runner such as grunt or gulp, or npm scripts to run tests and clean up code during your build process. this is a great way to perform tasks like linting and minifying code, adding in css prefixes or transpiling nascent javascript features for maximum cross-browser reach, and so on. use a browser automation system like selenium to run specific tests on installed browsers and re
turn results, alerting you to failures in browsers as they crop up. commercial cross-browser testing apps like lambdatest, sauce labs, browserstack, and testingbot are based on selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system. we will look at how to set up your own selenium-based testing system in the next a...
... your own selenium-based testing system in the next article. in this article, we'll look at how to set up a task runner, and use the basic functionality of commercial systems like the ones mentioned above. note: the above two categories are not mutually exclusive. it is possible to set up a task runner to access a service like sauce labs, or lambdatest via an api, run cross browser tests, and re
turn results. we will look at this below as well. using a task runner to automate testing tools as we said above, you can drastically speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automatically at a certain point in your build process. for example, this could be every time you save a file, or at some other point. inside this sectio...
... site. (if you already have node and npm installed, jump to point 4) install it like you would any other program. note that node comes with node package manager (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects. once the install completes, test that node is installed by typing the following into the terminal, which re
turns the installed versions of node and npm: node -v npm -v if you've got node/npm already installed, you should update them to their latest versions. to update node, the most reliable way is to download and install an updated installer package from their website (see link above). to update npm, use the following command in your terminal: npm install npm@latest -g note: if the above comma...
...And 7 more matches
JNI.jsm
cdata getforthread(); cdata loadclass(cdata ajenv, string aclassfullyqualifiedname, [optional] object adeclares); cdata newstring(cdata ajenv, string astr); string readstring(cdata ajenv, cdata ajavastring); void unloadclasses(); methods getforthread() blah blah cdata getforthread(); parameters this function does not take any arguments. re
turn value blah blah loadclass() blah blah cdata loadclass( ajenv, afullyqualifiedname, [optional] object adeclares ); parameters ajenv the re
turn value of getforthread(). afullyqualifiedname a sig of a typed array or the name of the class that would be used in a signature, but without the surrounding l and ;. if it is the sig of a typed array such as '[i' then adeclares must not be...
.../gecko/geckoappshell" and for geckointerface we would use "org/mozilla/gecko/geckoappshell$geckointerface". adeclares optional if this is omitted, then afullyqualifiedname must be an array type. if this is provided, then afullyqualifiedname must be a class name. a required object that contains up to five fields of key names: constructors, fields, static_fields, methods, and static_methods. re
turn value blah blah newstring() blah blah cdata newstring( ajenv, astr ); parameters ajenv the re
turn value of getforthread(). astr a javascript string, use any encoding desired. re
turn value blah blah readstring() blah blah string readstring( ajenv, ajavastring ); parameters ajenv the re
turn value of getforthread(). ajavastring a cdata object that is a java string. re...
... value blah blah newstring() blah blah cdata newstring( ajenv, astr ); parameters ajenv the re
turn value of getforthread(). astr a javascript string, use any encoding desired. re
turn value blah blah readstring() blah blah string readstring( ajenv, ajavastring ); parameters ajenv the re
turn value of getforthread(). ajavastring a cdata object that is a java string. re
turn value a javascript string. unloadclasses() blah blah void unloadclasses(); parameters this function takes no arguments. re
turn value this function has no re
turn value, if you try to store the re
turn value in a variable, it will be undefined. working with arrays creating/preallocating a typed array methods cdata .get(number aindex); cdata .getelements(number astart...
...And 7 more matches
Hacking Tips
with their description. note that some functions have been moved under an 'os' object, and help(os) will give brief help on just the members of that "namespace". getting the bytecode of a function (from js shell) the shell has a small function named dis to dump the bytecode of a function with its source notes. without arguments, it will dump the bytecode of its caller. ...
...object, and help(os) will give brief help on just the members of that "namespace". getting the bytecode of a function (from js shell) the shell has a small function named dis to dump the bytecode of a function with its source notes. without arguments, it will dump the bytecode of its caller. js> function f () { re
turn 1; } js> dis(f); flags: loc op ----- -- main: 00000: one 00001: re
turn 00002: stop source notes: ofs line pc delta desc args ---- ---- ----- ------ -------- ------ 0: 1 0 [ 0] newline 1: 2 0 [ 0] colspan 2 3: 2 2 [ 2] colspan 9 getting the bytecode of a function (from gdb) in jsopcode.cpp, a function named js::disassembleatpc can print the bytecode of a script. some variants of this function such as js::dumpscript et...
...he ins->id() of the lir instruction can be added to select precisely the instruction you are looking for. once the breakpoint is on codegenerator function of the lir instruction, add a command to generate a static breakpoint in the generated code. $ gdb --args js […] (gdb) b js::ion::codegenerator::visitstart (gdb) command >call masm.breakpoint() >continue >end (gdb) r js> function f(a, b) { re
turn a + b; } js> for (var i = 0; i < 100000; i++) f(i, i + 1); breakpoint 1, js::ion::codegenerator::visitstart (this=0x101ed20, lir=0x10234e0) at /home/nicolas/mozilla/ionmonkey/js/src/ion/codegenerator.cpp:609 609 } program received signal sigtrap, trace/breakpoint trap. 0x00007ffff7fb165a in ?? () (gdb) once you hit the generated breakpoint, you can replace it by a gdb breakpoint to ...
...And 7 more matches
Introduction to the JavaScript shell
redirect stdout to file. js_stderr=file redirect stderr to file. built-in functions to make the javascript shell more useful, there are a number of built-in functions provided that you can use either from javascript programs or in interactive mode. note: this list is incomplete and overlaps with shell global objects. see js/src/shell/js.cpp (around shell_functions) for more. build() re
turns the date and time at which the javascript shell was built. note: clear() with no parameters really clears everything. this includes all these built-in functions. clone(function, [scope]) clones the specified function object. if scope isn't specified, the new object's parent is the same as the original object's. otherwise, the new object is placed in the scope of the object specified by scope.
...ed in spidermonkey 1.8 dump the graph of all existing objects (or a specific interesting subgraph) to a file. for more information, see the c/c++ version of this function, js_dumpheap. evalcx(string[, object]) evaluates the javascript code in string. if object is specified, the code is executed in that object, treating it as a sandbox. if string is empty and object is not specified, evalcx() re
turns a new object with eager standard classes. if string is "lazy" and object is not specified, evalcx() re
turns a new object with lazy standard classes. note: evalcx() is only useful for people doing deep internal work on the javascript engine, for testing evalinsandbox-like environments in the shell. gc() runs the garbage collector to free up memory. gcparam(name[, value]) added in spidermonk...
...runs the garbage collector to free up memory. gcparam(name[, value]) added in spidermonkey 1.8 read or configure garbage collector parameters. the name must be one of the parameter keys (such as 'maxbytes', 'maxmallocbytes' or 'gcnumber') defined by for_each_gc_param in https://searchfox.org/mozilla-central/source/js/src/builtin/testingfunctions.cpp#464. if value is not specified, gcparam() re
turns the current value associated with gc parameter named name. if value is specified, it must be convertable to a positive uint32; gcparam() sets gc parameter name to value. for more information, see the c/c++ functions js_getgcparameter and js_setgcparameter. gczeal(level) added in spidermonkey 1.8 debug only. set the level of gc zeal, a debugging feature. this can be 0 for normal periodic gar...
...And 7 more matches
JIT Optimization Strategies
riables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions. call a function using f.apply(obj, arguments) if the function contains any use of the arguments object that falls out of the cases defined above, this optimization will be suppressed. in particular, arguments cannot be re
turned from the function, or passed as an argument into calls (except for the apply case above). getprop_argumentscallee attempts to optimize an arguments.callee property access. this optimization only works if the arguments object is used in well-understood ways within the function. the function containing the arguments.callee is allowed to use the arguments object in the following ways without dis...
...riables, as long as those variables cannot be accessed by any nested function, and as long as there exists no eval anywhere within the function or nested function definitions. call a function using f.apply(obj, arguments) if the function contains any use of the arguments object that falls out of the cases defined above, this optimization will be suppressed. in particular, arguments cannot be re
turned from the function, or passed as an argument into calls (except for the apply example listed above). getprop_inferredconstant attempts to optimize an access to a property that seems to be a constant. it applies to property accesses on objects which are global-like in that there is only one instance of them per program. this includes global objects, object literals defined at the top-level of a...
...timization makes the assumption that a property that has not changed after it was first assigned, is likely a constant property. it then directly inlines the value of the property into hot code that accesses it. for example, in the following code: var constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) re
turn true; } re
turn false; } will have the loop compiled into the following when testarray gets hot. for (var i = 0; i < array.length; i++) { if (array[i] > 100) re
turn true; } when this optimization is successful, property access is eliminated entirely and replaced with an inline constant. getprop_constant attempts to optimize reading a property that contains a uniquely-typed (or "si...
...And 7 more matches
JS::CompileOptions
known); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. version jsversion javascript version used to compile the script. methods some methods of js::owningcompileoptions and js::compileoptions re
turn the instance itself to allow method chain. methods of js::readonlycompileoptions method description bool mutederrors() const determines if errors are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the us...
...) for juicy morsels of its contents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. ...
...cript errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. const char *filename() const re
turns filename of the source code. const char *introducerfilename() const re
turns filename of the file which introduces the file. const char16_t *sourcemapurl() const re
turns the url of the source map. methods of js::owningcompileoptions method description jsobject *element() const re
turns the dom element to which this source code belongs, if any, or null if it belongs to no dom element. source belongs to a dom element in the f...
...And 7 more matches
NS ConvertASCIItoUTF16 external
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
NS ConvertUTF8toUTF16 external
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
PromiseFlatString (External)
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
nsAutoString (External)
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
nsCStringContainer (External)
(*) rfind(const nsacstring&, print32, print32 (*) rfind(const char*, print32 (*) rfind(const char*, print32, print32 (*) findchar rfindchar appendint tointeger base classes nsacstring data members no public members. methods beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation. parameters char* begin char* end char beginreading() const - source endreading char endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ch...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char* begin char* end pruint32 newsize char beginwriting(pruint32) - source parameters pruint32 alen endwriting char endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...urce parameters char other equalsliteral prbool equalsliteral(const char*) const - source parameters char other find(const nsacstring&, print32 (*) print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
nsDependentString external
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
nsStringContainer (External)
operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger base classes nsastring data members no public members. methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation. parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
nsString external
parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - sourc...
...equalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 7 more matches
IAccessibleHyperlink
gested that implementations should not rely on the inheritance. method overview [propget] hresult anchor([in] long index, [out] variant anchor ); [propget] hresult anchortarget([in] long index, [out] variant anchortarget ); [propget] hresult endindex([out] long index ); [propget] hresult startindex([out] long index ); [propget] hresult valid([out] boolean valid ); methods anchor() re
turns an object that represents the link anchor, as appropriate for the link at the specified index. [propget] hresult anchor( [in] long index, [out] variant anchor ); parameters index a 0 based index identifies the anchor when, as in the case of an image map, there is more than one link represented by this object. the valid maximal index is indicated by iaccessibleaction.nactions(). anchor this...
...d index. [propget] hresult anchor( [in] long index, [out] variant anchor ); parameters index a 0 based index identifies the anchor when, as in the case of an image map, there is more than one link represented by this object. the valid maximal index is indicated by iaccessibleaction.nactions(). anchor this is an implementation dependent value. ...
...n, as in the case of an image map, there is more than one link represented by this object. the valid maximal index is indicated by iaccessibleaction.nactions(). anchor this is an implementation dependent value. for example, for a text link this method could re
turn the substring of the containing string where the substring is overridden with link behavior, and for an image link this method could re
turn an iunknown variant for iaccessibleimage. see the section about. re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to re
turn, [out] value is null. s_ok. anchortarget() re
turns an object representing the target of the link, as appropriate for the link at the specified index. [propget] hresult anchortarget( [in] long index, [out] variant anchortarge...
...And 7 more matches
nsIDOMWindowInternal
mstring btoa(in domstring abase64data) nsivariant showmodaldialog(in nsivariant aargs, [optional] in domstring aoptions) void postmessage(in domstring message, in domstring targetorigin) attributes attribute type description window nsidomwindowinternal readonly: the window object itself. ...
...nal] in domstring aoptions) void postmessage(in domstring message, in domstring targetorigin) attributes attribute type description window nsidomwindowinternal readonly: the window object itself. self nsidomwindowinternal readonly: re
turns an object reference to the window object. navigator nsidomnavigator readonly: re
turns a reference to the navigator object. ...
...rgetorigin) attributes attribute type description window nsidomwindowinternal readonly: the window object itself. self nsidomwindowinternal readonly: re
turns an object reference to the window object. navigator nsidomnavigator readonly: re
turns a reference to the navigator object. screen nsidomscreen readonly: re
turns a reference to the screen object associated with the window. history nsidomhistory readonly: re
turns a reference to the history object, which provides an interface for manipulating the browser session history. content nsidomwindow readonly: re
turns a window object for the primary content window. prompter nsiprompt readonly: menubar nsid...
...And 7 more matches
nsIEditorSpellCheck
nitspellchecker(); void updatecurrentdictionary(); methods addwordtodictionary() adds the specified word to the current personal dictionary. void addwordtodictionary( in wstring word ); parameters word the word to add to the current personal dictionary. canspellcheck() determines whether or not spell checking can be enabled. boolean canspellcheck(); parameters none. re
turn value re
turns true if spell checking can be enabled. if there are no available dictionaries, the re
turn value is false. checkcurrentdictionary() call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available. if the current dictionary is no longer available, pick another dictionary. void checkcurrentdictionary()...
...urrentdictionary() call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available. if the current dictionary is no longer available, pick another dictionary. void checkcurrentdictionary(); parameters none. checkcurrentword() checks a given word. in spite of the name, this function checks the word you give it, re
turning true if the word is misspelled. if the word is misspelled, it will compute the suggestions which you can get from getsuggestedword(). boolean checkcurrentword( in wstring suggestedword ); parameters suggestedword missing description re
turn value true if the specified word is misspelled; otherwise false. checkcurrentwordnosuggest() like checkcurrentword(), checks the word you give ...
...ue if the word is misspelled. if the word is misspelled, it will compute the suggestions which you can get from getsuggestedword(). boolean checkcurrentword( in wstring suggestedword ); parameters suggestedword missing description re
turn value true if the specified word is misspelled; otherwise false. checkcurrentwordnosuggest() like checkcurrentword(), checks the word you give it, re
turning true if it is misspelled. this is faster than checkcurrentword() because it does not compute any suggestions. ...
...And 7 more matches
nsIEffectiveTLDService
public suffixes, and the list of them is the public suffix list, or psl. see publicsuffix.org for more information. the methods below implement the public suffix algorithm in full, including the implicit "*" rule. therefore, if you call getpublicsuffix("a.b.c.nonexistent"), you will get back "nonexistent" - this "tld" is not in the public suffix list, but the implicit "*" rule means that it is re
turned. this is the right answer for e.g. cookie setting and domain highlighting, but you should check whether it's the right answer for your application. it is not recommended to use this interface for determining whether a given string "is a domain name". that question is unanswerable with 100% accuracy using the psl, because what is a domain name is a property of the dns, which is different for di...
... it's not dynamically updated data). ...
... exceptions thrown ns_error_invalid_arg this exception is thrown if the hostname in auri is empty. ...
...And 7 more matches
nsIHttpChannel
e referrer uri is rejected. exceptions thrown ns_error_in_progress if set after the channel has been opened. ns_error_failure if used for setting referrer during visitrequestheaders(). getting the value will not throw. requestmethod acstring set or get the http request method (default is "get"). setter is case insensitive; getter re
turns an uppercase string. this attribute may only be set before the channel is opened. note: the data for a "post" or "put" request can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request method explicitly. the documentation for nsiuploadchannel has further details. exceptions thrown ns_error_in_progres...
...the data for a "post" or "put" request can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request method explicitly. the documentation for nsiuploadchannel has further details. exceptions thrown ns_error_in_progress if set after the channel has been opened. requestsucceeded boolean re
turns true if the http response code indicates success. the value of nsirequest.status() will be ns_ok even when processing a 404 file not found response because such a response may include a message body that (in some cases) should be shown to the user. use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid re...
... onstartrequest()). responsestatus unsigned long get the http response code (for example 200). read only. exceptions thrown ns_error_not_available if called before the response has been received (before onstartrequest()). responsestatustext acstring get the http response status text (for example "ok"). note: this re
turns the raw (possibly 8-bit) text from the server. there are no assumptions made about the charset of the re
turned text. you have been warned! read only. exceptions thrown ns_error_not_available if called before the response has been received (before onstartrequest()). referrerpolicy read only unsigned long the referrer policy in use for this ...
...And 7 more matches
nsIIOService
when in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up). observers will be notified of changes to this attribute. methods allowport() checks if a port number is banned. this involv...
...'s decision to block the port. this gives the protocol handler ultimate control over its own security policy while ensuring reasonable, default protection. is similar to nsiprotocolhandler.allowport(). boolean allowport( in long aport, in string ascheme ); parameters aport the port to check ascheme the scheme for the protocol handler that could override the ioservice's decision. re
turn value true if the port is allowed, false otherwise. extractscheme() utility to extract the scheme from a url string, consistently and according to spec (see rfc 3986). note: most url parsing is done via nsiuri, and in fact the scheme can also be extracted from a url string via nsiuri. this method is provided purely as an optimization. acstring extractscheme( in autf8string urlstring ); ...
...o extract the scheme from a url string, consistently and according to spec (see rfc 3986). note: most url parsing is done via nsiuri, and in fact the scheme can also be extracted from a url string via nsiuri. this method is provided purely as an optimization. acstring extractscheme( in autf8string urlstring ); parameters urlstring the string for the url to extract the scheme from. ...
...And 7 more matches
nsIInputStream
tes available in the stream. in addition to the number of bytes available in the stream, this method also informs the caller of the current status of the stream. a stream that is closed will throw an exception when this method is called. that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-file, but not closed, then this method re
turns 0 bytes available. note: some nsiinputstream implementations automatically close() when end-of-file is reached; others do not. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the under...
...atically close() when end-of-file is reached; others do not. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. ...
... native code only!read this method copies data from the stream into a buffer. ...
...And 7 more matches
nsIMsgDBView
); parameters folder the nsimsgfolder to open. sorttype a nsmsgviewsorttypevalue designating the sort type used for the folder. defined in the interface: nsmsgviewsorttype. sortorder an nsmsgviewsortordervalue designating the sort order used for the folder. defined in the interface: nsmsgviewsortorder. viewflags other flags to be used. defined in the interface: nsmsgviewflagstype. re
turn values count upon re
turn, the count variable may contain the number of messages in the folder. note: this re
turn value does not appear to be implemented in the base implementation. openwithhdrs() opens the view with a set of specified headers. note: this is not implemented in the base implementation. void openwithhdrs(in nsisimpleenumerator aheaders, in nsmsgviewsortt...
...eaders to open, arranged in an nsisimpleenumerator. asorttype a nsmsgviewsorttypevalue designating the sort type used for the folder. defined in the interface: nsmsgviewsorttype. sortorder an nsmsgviewsortordervalue designating the sort order used for the folder. defined in the interface: nsmsgviewsortorder. viewflags other flags to be used. defined in the interface: nsmsgviewflagstype. re
turn values acount upon re
turn, the count variable may contain the number of messages loaded. close() close the current list of messages. void close(); init() initializes the database view for use. void init(in nsimessenger amessengerinstance, in nsimsgwindow amsgwindow, in nsimsgdbviewcommandupdater acommandupdater); parameters amessengerinstance amsgwindow ...
...tus of a particular command. used by the thunderbird ui to determine if the command is available. void getcommandstatus(in nsmsgviewcommandtypevalue command, out boolean selectable_p, out nsmsgviewcommandcheckstatevalue selected_p); parameters command the nsmsgviewcommandtypevalue to perform. defined in the interface: nsmsgviewcommandtype. re
turn values selectable_p the state of the command. true if it is enabled. false if it is disabled. selected_p the re
turned check state of the command. defined in the interface: nsmsgviewcommandcheckstate. this is not used for all commands and will re
turn the notused value most of the time. viewnavigate() change the view to show a particular message. this method will automatically expand the d...
...And 7 more matches
nsINavHistoryService
7 this transition type is set when the transition is a download. transition_framed_link 8 this transition type is set when the user followed a link that loaded a page in a frame. methods getpagetitle() this method retrieves the original title of the page. astring getpagetitle( in nsiuri auri ); parameters auri the page whose title needs to be retrieved. re
turn value re
turns the original title of the page. markpageasfollowedbookmark() this method is just like markpageastyped (in nsibrowserhistory, also implemented by the history service), but for bookmarks. it declares that the given uri is being opened as a result of following a bookmark. if this uri is loaded soon after this message has been received, that transition will be marked as following a b...
...ne whether it will be or not. you don't have to worry about calling this, addpagetosession/adduri will always check before actually adding the page. this function is public because some components may want to check if this page would go in the history (that is for annotations). boolean canadduri( in nsiuri auri ); parameters auri the uri that needs to be added to the history system. re
turn value re
turns true if this uri would be added to the history, otherwise re
turns 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 ...
...f transition: one of transition_* defined above. aisredirect true if the given visit redirects to somewhere else (that is you will create a visit out of here that is a redirect transition). this causes this page to be hidden in normal history views (unless it has been unhidden by visiting it with a non-redirect). asessionid the session id that this page belongs to. use "0" for no session. ...
...And 7 more matches
nsIWindowsRegKey
read only. key hkey this attribute exposes the native hkey and is available to provide c++ consumers with the flexibility of making other windows registry api calls that are not exposed via this interface. it is possible to initialize this object by setting an hkey on it. in that case, it is the responsibility of the consumer setting the hkey to ...
...ity of making other windows registry api calls that are not exposed via this interface. it is possible to initialize this object by setting an hkey on it. in that case, it is the responsibility of the consumer setting the hkey to ensure that it is a valid hkey. warning: setting the key does not close() the old key. native code only! valuecount unsigned long this attribute re
turns the number of values under this key. read only. constants root key constants the values for these keys correspond to the values from winreg.h in the ms platform sdk. the root_key_ prefix corresponds to the hkey_ prefix in the ms platform sdk. this interface is not restricted to using only these root keys. constant value description root_key_classes_root 0x8000000...
...e consulted for the exact meaning of these value types. this interface is somewhat restricted to using only these value types. there is no method that is directly equivalent to regqueryvalueex or regsetvalueex. in particular, this interface does not support the reg_multi_sz and reg_expand_sz value types. it is still possible to enumerate values that have other types (that is, getvaluetype() may re
turn a type not defined below). constant value description type_none 0 reg_none type_string 1 reg_sz type_binary 3 reg_binary type_int 4 reg_dword type_int64 11 reg_qword methods close() this method closes the key. if the key is already closed, then this method does nothing. void close(); parameters none. ...
...And 7 more matches
Working with data
tions that you can use to create new cdata objects of that type. there are several ways you can go about creating new cdata objects. creating uninitialized cdata objects there are three forms of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj = new type; var mycdataobj = new type(); var mycdataobj = type(); these all do the same thing: they re
turn a new cdata object of the specified type, whose data buffer has been populated entirely with zeroes. note: if type.size is undefined, creating a new object this way will throw a typeerror exception. creating initialized cdata objects similarly, you can initialize cdata objects with specific values at the type of creation by specifying them as a parameter when calling the ctype's constructor, l...
...llowing steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array. this is the same as new arraytype(type.elementtype, value). if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and re
turned. if the type is an array of 8-bit characters and value is a utf-16 string, the new cdata object is the result of converting the utf-16 string to utf-8, with a null terminator. if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdata objects and copied into the new array, which is ...
... the type is an array of 8-bit characters and value is a utf-16 string, the new cdata object is the result of converting the utf-16 string to utf-8, with a null terminator. if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdata objects and copied into the new array, which is then re
turned. if none of these conditions are met, a typeerror is thrown. if type is ctypes.void_t, a typeerror is thrown. example: creating an array let arraytype = ctypes.arraytype(ctypes.int32_t); let myarray = new arraytype(5); at this point, myarray.length is 5; there are 5 entries in the array. myarray.constructor.size is 20; the total size of the array's data buffer is 20 bytes (5 entries, 4 b...
...And 7 more matches
Using js-ctypes
l the ctypes.open() method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the re
turned object is a library object that you use to declare functions and data types for use with the loaded library. note: js-ctypes only works with c libraries; you can't use c++ methods directly. instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you. examples can be found here: bugzilla :: bug 505907 - support c++ calling from jsctypes libra...
...("user32.dll"); or even without the extension. var lib = ctypes.open("user32"); calling carbon routines on mac os x this example demonstrates how to use ctypes to call a carbon function on mac os x. ...
...on makestr(str) { re
turn string.fromcharcode(str.length) + str; } components.utils.import("resource://gre/modules/ctypes.jsm"); var carbon = ctypes.open("/system/library/frameworks/carbon.framework/carbon"); stdalert = carbon.declare("standardalert", /* function name */ ctypes.default_abi, /* abi type */ ctypes.int16_t, /* re
turn type */ ctypes.int16_t, /* alert type */ ctypes.char.ptr, /* primary text */ ctypes.char.ptr, /* secondary text */ ctypes.uint32_t, /* alert param */ ctypes.int16_t); /* item hit */ var hit = 0; var msgerr = makestr("carbon says..."); va...
...And 7 more matches
Using Fetch - Web APIs
e network. this kind of functionality was previously achieved using xmlhttprequest. fetch provides a better alternative that can be easily used by other technologies such as service workers. fetch also provides a single logical place to define other http-related concepts such as cors and extensions to http. the fetch specification differs from jquery.ajax() in three main ways: the promise re
turned from fetch() won’t reject on http error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites...
...1.0b13.) a basic fetch request is really simple to set up. have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console. the simplest use of fetch() takes one argument — the path to the resource you want to fetch — and re
turns a promise containing the response (a response object). this is just an http response, not the actual json. to extract the json body content from the response, we use the json() method (defined on the body mixin, which is implemented by both the request and response objects.) note: the body mixin also has similar methods to extract other types of body content; see the body section for more. ...
...n' // 'content-type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerpolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: json.stringify(data) // body data type must match "content-type" header }); re
turn response.json(); // parses json response into native javascript objects } postdata('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // json data parsed by `data.json()` call }); note that mode: "no-cors" only allows a limited set of headers in the request: accept accept-language content-language content-type with a value of application/x-www-form-u...
...And 7 more matches
Using the Payment Request API - Web APIs
s the total payment amount, tax, shipping cost, etc. options (optional) — an object containing addtional options related to the payment. ...
...the payment. ...
...ed inside the constructor simply re
turn the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: re
turn [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard'], supportedtypes: ['debit', 'credit'] } }]; } function buildshoppingcartdetails() { // hardcoded for demo purposes: re
turn { id: 'order-123', displayitems: [ { label: 'example item', amount: {currency: 'usd', value: '1.00'} } ], total: { label: 'total', amount: {currency: 'usd', value: '1.00'} } }; } starting the payment process once the paymentrequest object has been created, you call the paymentrequest.show() method on it to initiate the payment reques...
...And 7 more matches
Range - Web APIs
that can contain nodes and parts of text nodes. a range can be created by using the document.createrange() method. range objects can also be retrieved by using the getrangeat() method of the selection object or the caretrangefrompoint() method of the document object. there also is the range() constructor available. properties there are no inherited properties. range.collapsed read only re
turns a boolean indicating whether the range's start and end points are at the same position. range.commonancestorcontainer read only re
turns the deepest node that contains the startcontainer and endcontainer nodes. range.endcontainer read only re
turns the node within which the range ends. range.endoffset read only re
turns a number representing where in the endcontainer the range ends. range...
... methods there are no inherited methods. ...
... methods there are no inherited methods. range.setstart() sets the start position of a range. range.setend() sets the end position of a range. ...
...And 7 more matches
Using the Resource Timing API - Web APIs
t and requeststart, respectively), until the response has ended (responseend). this timing data provides a detailed profile of the resource loading phases and this data can be used to help identify performance bottlenecks. ...
...ormance support if (performance === undefined) { console.log("= calculate load times: performance not supported"); re
turn; } // get a list of "resource" performance entries var resources = performance.getentriesbytype("resource"); if (resources === undefined || resources.length <= 0) { console.log("= calculate load times: there are no `resource` performance records"); re
turn; } console.log("= calculate load times"); for (var i=0; i < resources.length; i++) { console.log("== resource[" + i + "] - " + resources[i].name); // redirect time var t = resources[i].redirectend - resources[i].redirectstart; console.log("... redirect time = " + t); // dns time t = resources[i].domainlookupend - resources[i].domainlookupstart; console.log("...
..... start until response end time = " + t); } } resource size measurements the size of an application's resources can affect an application's performance so getting accurate data on resource size can be important (especially for non-hosted resources). the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. ...
...And 7 more matches
Resource Timing API - Web APIs
ce page, using the resource timing api, and the references in the see also section. for a graphical representation of the resource timing processing model see the resource timing phases figure. the performanceresourcetiming interface extends the performanceentry for performance entries which have an entrytype of "resource". high-resolution timestamps several of the resource timing properties re
turn high-resolution timestamps. these timestamps have a domhighrestimestamp type and as its name implies, they represent a high-resolution point in time. this type is a double and its value is a discrete point in time or the difference in time between two discrete points in time. the unit of domhighrestimestamp is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser i...
... if the browser is unable to provide a time value accurate to 5 µs (because, for example, due to hardware or software constraints), the browser can represent a the value as a time in milliseconds accurate to a millisecond. resource loading timestamps an application can get timestamps for the various stages used to load a resource. the first property in the processing model is starttime which re
turns the timestamp immediately before the resource loading process begins. the fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup. the next stages are connectstart and connectend which are the timestamps immediately before and after connecting to the server, respectively. the last three timestamps are, in order: requeststart - the timestamp before the browse...
...ver; responsestart - the timestamp after the browser receives the first byte of the response from the server; and responseend - the timestamp after the browser receives the last byte of the resource. if the resource is loaded via a secure connection a secureconnectionstart timestamp will be available between the connection start and end events. ...
...And 7 more matches
SVGPathElement - Web APIs
parent, svggeometryelement. svgpathelement.pathlength an svganimatednumber corresponding to the pathlength attribute of the given <path> element. note: in svg 2 this property was moved to the svggeometryelement interface, from which this interface inherits it. methods this interface also inherits methods from its parent, svggeometryelement. ...
...metryelement. svgpathelement.gettotallength() re
turns a float representing the computed value for the total length of the path using the browser's distance-along-a-path algorithm, as a distance in the current user coordinate system. note: in svg 2 this method was moved to the svggeometryelement interface, from which this interface inherits it. svgpathelement.getpointatlength() re
turns an svgpoint representing the x and y coordinates in user space utilizing the browser's distance-along-a-path algorithm. note: in svg 2 this method was moved to the svggeometryelement interface, from which this interface inherits it. ...
...e svggeometryelement interface, from which this interface inherits it. svgpathelement.getpointatlength() re
turns an svgpoint representing the x and y coordinates in user space utilizing the browser's distance-along-a-path algorithm. note: in svg 2 this method was moved to the svggeometryelement interface, from which this interface inherits it. svgpathelement.getpathsegatlength() re
turns an unsigned long representing the index within the pathseglist utilizing the user agent's distance-along-a-path algorithm. svgpathelement.createsvgpathsegclosepath() re
turns a stand-alone, parentless svgpathsegclosepath object. ...
...And 7 more matches
Matrix math for the web - Web APIs
the 2nd column, then add together let resulty = (x * c1r0) + (y * c1r1) + (z * c1r2) + (w * c1r3); // multiply the point against each part of the 3rd column, then add together let resultz = (x * c2r0) + (y * c2r1) + (z * c2r2) + (w * c2r3); // multiply the point against each part of the 4th column, then add together let resultw = (x * c3r0) + (y * c3r1) + (z * c3r2) + (w * c3r3); re
turn [resultx, resulty, resultz, resultw]; } now using the function above we can multiply a point by the matrix. using the identity matrix it should re
turn a matrix identical to the original, since a matrix multiplied by the identity matrix is always equal to itself: // sets identityresult to [4,3,2,1] let identityresult = multiplymatrixandpoint(identitymatrix, [4, 3, 2, 1]); re
turning the same p...
...7]]; let row2 = [matrixb[ 8], matrixb[ 9], matrixb[10], matrixb[11]]; let row3 = [matrixb[12], matrixb[13], matrixb[14], matrixb[15]]; // multiply each row by matrixa let result0 = multiplymatrixandpoint(matrixa, row0); let result1 = multiplymatrixandpoint(matrixa, row1); let result2 = multiplymatrixandpoint(matrixa, row2); let result3 = multiplymatrixandpoint(matrixa, row3); //
turn the result rows back into a single matrix re
turn [ result0[0], result0[1], result0[2], result0[3], result1[0], result1[1], result1[2], result1[3], result2[0], result2[1], result2[2], result2[3], result3[0], result3[1], result3[2], result3[3] ]; } let's look at this function in action: let somematrix = [ 4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 4, 8, 4, 1 ] let identitym...
...these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection. in real production code it would be best to use...
...And 7 more matches
WritableStream.WritableStream() - Web APIs
ining 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 re
turn 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 to the underlying sink.
... 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 to the underlying sink. it can re
turn a promise to signal success or failure of the write operation. the controller parameter passed to this method is a writablestreamdefaultcontroller that can be used by the developer to control the stream as more chunks are submitted for writing. this method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). close(controller) opt...
...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 re
turn 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 wishes to abruptly clos...
...And 7 more matches
Private class fields - JavaScript
class properties are public by default and can be examined or modified outside the class. there is however an experimental proposal to allow defining private class fields using a hash # prefix is added. ...
...static_field } examples private static fields private fields are accessible on the class constructor from inside the class declaration itself. the limitation of static variables being called by only static methods still holds. class classwithprivatestaticfield { static #private_static_field static publicstaticmethod() { classwithprivatestaticfield.#private_static_field = 42 re
turn classwithprivatestaticfield.#private_static_field } } console.assert(classwithprivatestaticfield.publicstaticmethod() === 42) private static fields are added to the class constructor at class evaluation time. there is a provenance restriction on private static fields. only the class which defines the private static field can access the field. this can lead to unexpected behaviour when using...
...dded to the class constructor at class evaluation time. there is a provenance restriction on private static fields. only the class which defines the private static field can access the field. this can lead to unexpected behaviour when using this. class baseclasswithprivatestaticfield { static #private_static_field static basepublicstaticmethod() { this.#private_static_field = 42 re
turn this.#private_static_field } } class subclass extends baseclasswithprivatestaticfield { } let error = null try { subclass.basepublicstaticmethod() } catch(e) { error = e} console.assert(error instanceof typeerror) private instance fields private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. the # is a part of the name itself...
...And 7 more matches
Function.prototype.bind() - JavaScript
a function (supplied as a callback) inside a settimeout, any primitive value passed as thisarg is converted to object. if no arguments are provided to bind , or if the thisarg is null or undefined, the this of the executing scope is treated as the thisarg for the new function. arg1, arg2, ...argn optional arguments to prepend to arguments provided to the bound function when invoking func. re
turn value a copy of the given function with the specified this value, and initial arguments (if provided). description the bind() function creates a new bound function, which is an exotic function object (a term from ecmascript 2015) that wraps the original function object. calling the bound function generally results in the execution of its wrapped function. a bound function has the following in...
... // yes, it does work with `new (funca.bind(thisarg, args)...
... // yes, it does work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var arrayprototypeslice = array.p...
...And 7 more matches
JSON.stringify() - JavaScript
it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). values less than 1 indicate that no space should be used. if this is a string, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. if this parameter is not provided (or is null), no white space is used. re
turn value a json string representing the given value. exceptions throws a typeerror ("cyclic object value") exception when a circular reference is found. throws a typeerror ("bigint value can't be serialized in json") when trying to stringify a bigint value. description json.stringify() converts a value to json notation representing it: if the value has a tojson() method, it's responsible...
... boolean, number, and string objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics. undefined, functions, and symbols are not valid json values. if any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). json.stringify() can re
turn undefined when passing in "pure" values like json.stringify(function(){}) or json.stringify(undefined). all symbol-keyed properties will be completely ignored, even when using the replacer function. the instances of date implement the tojson() function by re
turning a string (the same as date.toisostring()). thus, they are treated as strings. the numbers infinity and nan, as well as the value n...
...on.stringify([new int8array([1]), new int16array([1]), new int32array([1])]); // '[{"0":1},{"0":1},{"0":1}]' json.stringify([new uint8array([1]), new uint8clampedarray([1]), new uint16array([1]), new uint32array([1])]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' json.stringify([new float32array([1]), new float64array([1])]); // '[{"0":1},{"0":1}]' // tojson() json.stringify({ x: 5, y: 6, tojson(){ re
turn this.x + this.y; } }); // '11' // symbols: json.stringify({ x: undefined, y: object, z: symbol('') }); // '{}' json.stringify({ [symbol('foo')]: 'foo' }); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, [symbol.for('foo')]); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { re
turn 'a symbol'; } }); // undefined // non-enumerable ...
...And 7 more matches
Math - JavaScript
of 10; approximately 2.303. math.log2e base-2 logarithm of e; approximately 1.443. math.log10e base-10 logarithm of e; approximately 0.434. math.pi ratio of the a circle's circumference to its diameter; approximately 3.14159. math.sqrt1_2 square root of ½ (or equivalently, 1/√2); approximately 0.707. math.sqrt2 square root of 2; approximately 1.414. ...
...logarithm of e; approximately 1.443. math.log10e base-10 logarithm of e; approximately 0.434. math.pi ratio of the a circle's circumference to its diameter; approximately 3.14159. math.sqrt1_2 square root of ½ (or equivalently, 1/√2); approximately 0.707. math.sqrt2 square root of 2; approximately 1.414. static methods math.abs(x) re
turns the absolute value of x. math.acos(x) re
turns the arccosine of x. math.acosh(x) re
turns the hyperbolic arccosine of x. math.asin(x) re
turns the arcsine of x. math.asinh(x) re
turns the hyperbolic arcsine of a number. math.atan(x) re
turns the arctangent of x. math.atanh(x) re
turns the hyperbolic arctangent of x. math.atan2(y, x) re
turns the arctangent of the quotient of its arguments. math.cbrt(x) re
turns the cube root of x. ma...
...e of x. math.acosh(x) re
turns the hyperbolic arccosine of x. math.asin(x) re
turns the arcsine of x. math.asinh(x) re
turns the hyperbolic arcsine of a number. math.atan(x) re
turns the arctangent of x. math.atanh(x) re
turns the hyperbolic arctangent of x. math.atan2(y, x) re
turns the arctangent of the quotient of its arguments. math.cbrt(x) re
turns the cube root of x. math.ceil(x) re
turns the smallest integer greater than or equal to x. math.clz32(x) re
turns the number of leading zeroes of the 32-bit integer x. math.cos(x) re
turns the cosine of x. math.cosh(x) re
turns the hyperbolic cosine of x. math.exp(x) re
turns ex, where x is the argument, and e is euler's constant (2.718…, the base of the natural logarithm). math.expm1(x) re
turns subtracting 1 from exp(x). math.
...And 7 more matches
Object.prototype.propertyIsEnumerable() - JavaScript
description every object has a propertyisenumerable method. ...
...er the specified property is enumerable and is the object's own property. 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 obj.propertyisenumerable(prop) parameters prop the name of the property to test. re
turn value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property...
...n indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property, this method re
turns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // re
turns true a.propertyisenumerable(0); // re
turns true user-defined vs. built-in objects the following example demonstrates the enumerab...
...And 7 more matches
String.prototype.indexOf() - JavaScript
the indexof() method re
turns the index within the calling string object of the first occurrence of the specified value, starting the search at fromindex. re
turns -1 if the value is not found. 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. note: for the array method, see array.prototype.indexof(). syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. ...
.../mdn/interactive-examples and send us a pull request. note: for the array method, see array.prototype.indexof(). syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. so, for example: 'undefined'.indexof() will re
turn 0, as undefined is found at position 0 in the string undefined. 'undefine'.indexof() however will re
turn -1, as undefined is not found in the string undefine. fromindex optional an integer representing the index at which to start the search. defaults to 0. for fromindex values lower than 0, or greater than str.length, the search starts at index 0 and str.length, respectively. for exampl...
...n the string undefined. 'undefine'.indexof() however will re
turn -1, as undefined is not found in the string undefine. fromindex optional an integer representing the index at which to start the search. defaults to 0. for fromindex values lower than 0, or greater than str.length, the search starts at index 0 and str.length, respectively. for example, 'hello world'.indexof('o', -5) will re
turn 4, as it starts at position 0, and o is found at position 4. on the other hand, 'hello world'.indexof('o', 11) (and with any fromindex value greater than 11) will re
turn -1, as the search is started at position 11, a position after the end of the string. re
turn value the index of the first occurrence of searchvalue, or -1 if not found. an empty string searchvalue produces strange results. w...
...And 7 more matches
delete operator - JavaScript
ribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax delete expression where expression should evaluate to a property reference, e.g.: delete object.property delete object['property'] parameters object the name of an object, or an expression evaluating to an object. property the property to delete. re
turn value true for all cases except when the property is an own non-configurable property, in which case, false is re
turned in non-strict mode. exceptions throws typeerror in strict mode if the property is an own non-configurable property. description unlike what common belief suggests (perhaps due to other programming languages like delete in c++), the delete operator has nothing to do with dir...
... property. description unlike what common belief suggests (perhaps due to other programming languages like delete in c++), the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references. see the memory management page for more details. the delete operator removes a given property from an object. on successful deletion, it will re
turn true, else false will be re
turned. however, it is important to consider the following scenarios: if the property which you are trying to delete does not exist, delete will not have any effect and will re
turn true. if a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete onl...
...ich they were defined. non-configurable properties cannot be removed. this includes properties of built-in objects like math, array, object and properties that are created as non-configurable with methods like object.defineproperty(). the following snippet gives a simple example: var employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete employee.name); // re
turns true console.log(delete employee.age); // re
turns true // when trying to delete a property that does // not exist, true is re
turned console.log(delete employee.salary); // re
turns true non-configurable properties when a property is marked as non-configurable, delete won't have any effect, and will re
turn false. in strict mode this will raise a typeerror. var employee = {}; object.definep...
...And 7 more matches
instanceof - JavaScript
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 object instanceof constructor parameters object the object to test. constructor function to test against description the instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...bject.setprototypeof. it is also possible using the non-standard __proto__ property. instanceof and multiple context (e.g. frames or windows) different scopes have different execution environments. this means that they have different built-ins (different global object, different constructors, etc.). this may result in unexpected results. for instance, [] instanceof window.frames[0].array will re
turn false, because array.prototype !== window.frames[0].array and arrays inherit from the former. this may not make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. for instance, you can securely check if a given object is, in fact, an array using array.isarray(myobj) for ex...
...ect is, in fact, an array using array.isarray(myobj) for example, checking if a nodes is a svgelement in a different context, you can use mynode instanceof mynode.ownerdocument.defaultview.svgelement. note for mozilla developers: in code using xpcom, instanceof has special effect: obj instanceof xpcominterface (e.g. components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and re
turns true if queryinterface succeeded. a side effect of such call is that you can use xpcominterface's properties on obj after a successful instanceof test. unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope. examples demonstrating that string and date are of type object and exceptional cases the following code uses...
...And 7 more matches
Caching compiled WebAssembly modules - WebAssembly
ng library because indexeddb is a somewhat old-fashioned api, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern apis. in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and re
turns a promise resolving to the finished wasm instance. additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again. note: the entire site's wasm cache (not just the given url) is versioned by the specified dbversion passed i...
...ing some necessary constants: function instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it re
turns a promise resolving to the new database. function opendatabase() { re
turn new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if...
...n ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looking up the given url in the object store we created above. it resolves with the stored compiled module, or rejects with an error. ...
...And 7 more matches
Private Properties - Archive of obsolete content
h an underscore. consider the following example: function point(x, y) { this._x = x; this._y = y; } the properties _x and _y are intended to be private, and should only be accessed by member functions. to make a private property readable/writable from any function, it's common to define getter/setter functions for the property, respectively: point.prototype.getx = function () { re
turn this._x; }; point.prototype.setx = function (x) { this._x = x; }; point.prototype.gety = function () { re
turn this._y; }; point.prototype.sety = function (y) { this._y = y; }; the above technique is simple and clearly expresses intent. however, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from ...
...refix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is supposed to be private. using closures another common technique, is to define private properties as variables and their getter and setter functions as a closure over these variables: function point(_x, _y) { this.getx = function () { re
turn _x; }; this.setx = function (x) { _x = x; }; this.gety = function () { re
turn _y; }; this.sety = function (y) { _y = y; }; } note that this technique requires member functions that need access to private properties to be defined on the object itself, instead of its prototype. this is slightly less efficient than using the underscore convent...
...duced to javascript in ecmascript 2015 and have recently been implemented in spidermonkey. ...
...And 6 more matches
tabs/utils - Archive of obsolete content
functions for working with xul tabs and the xul tabbrowser object. globals functions activatetab(tab, window) set the specified tab as the active, or selected, tab. parameters tab : tab a xul tab element to activate. window : window a browser window. gettabbrowser(window) get the tabbrowser element for the given browser window. parameters window : window a browser window. re
turns tabbrowser : gettabcontainer(window) get the tabbrowser's tabcontainer property. parameters window : window a browser window. re
turns tabcontainer : gettabs(window) re
turns the tabs for the specified window. if you omit window, this function will re
turn tabs across all the browser's windows. however, if your add-on has not opted into private browsing, then the function will exclude all tab...
... tabs across all the browser's windows. however, if your add-on has not opted into private browsing, then the function will exclude all tabs that are hosted by private browser windows. to learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. parameters window : nsiwindow optional. re
turns array : an array of tab elements. getactivetab(window) given a browser window, get the active, or selected, tab. parameters window : window a browser window. re
turns tab : the currently selected tab. getownerwindow(tab) get the browser window that owns the specified tab. parameters tab : tab a browser tab. re
turns window : a browser window. opentab(window, url, options) open a n...
...b. url : string url for the document to load. options : object optional options: name type inbackground boolean if true, open the new tab, but keep the currently selected tab selected. if false, make the new tab the selected tab. optional, defaults to false. pinned boolean pin this tab. optional, defaults to false. re
turns tab : the new tab. istabopen(tab) test whether the specified tab is open. parameters tab : tab a xul tab element. re
turns boolean : true if the tab is open, otherwise false. closetab(tab) close the specified tab. parameters tab : tab a xul tab element. geturi(tab) get the specified tab's uri. parameters tab : tab a xul tab element. re
turns string : the current uri. gettabbro...
...And 6 more matches
Miscellaneous - Archive of obsolete content
this page contains small, self-explanatory code snippets. system info operating system detection // re
turns "winnt" on windows vista, xp, 2000, and nt systems; // "linux" on gnu/linux; and "darwin" on mac os x. ...
... this page contains small, self-explanatory code snippets. system info operating system detection // re
turns "winnt" on windows vista, xp, 2000, and nt systems; // "linux" on gnu/linux; and "darwin" on mac os x. ...
...f-explanatory code snippets. system info operating system detection // re
turns "winnt" on windows vista, xp, 2000, and nt systems; // "linux" on gnu/linux; and "darwin" on mac os x. ...
...And 6 more matches
Tabbed browser - Archive of obsolete content
pageload(event) { if (event.originaltarget instanceof components.interfaces.nsidomhtmldocument) { var win = event.originaltarget.defaultview; if (win.frameelement) { // frame within a tab was loaded. win should be the top window of // the frameset. if you don't want do anything when frames/iframes // are loaded in this web page, uncomment the following line: // re
turn; // find the root document: win = win.top; } } } // do not try to add a callback until the browser window has // been initialised. we add a callback to the tabbed browser // when the browser's window gets loaded. window.addeventlistener("load", function () { // add a callback to be run every time a document loads. // note that this includes frames/iframes within the documen...
...cument from windows or dialogs not opened by the browser window, you can use nsiwindowmediator to get the document displayed in the selected tab of the most recently used browser window. var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var recentwindow = wm.getmostrecentwindow("navigator:browser"); re
turn recentwindow ? recentwindow.content.document.location : null; see also working with windows in chrome code. enumerating browsers to go through all browser in a tabbrowser, first get a reference to a browser's window. if your code is executed from a firefox browser.xul overlay (for example, it is a toolbar button or menu click handler), you can access the current window with the window pre-def...
...urrent reference pages on browser and tabbrowser. getting the browser that fires the http-on-modify-request notification see the observer notifications page for information on http-on-* notifications. note that some http requests aren't associated with a tab; for example, rss feed updates, extension manager requests, xhr requests from xpcom components, etc. in those cases, the following code re
turns null. warning: this code should be updated to use nsiloadcontext instead of getinterface(components.interfaces.nsidomwindow). updated example is in section below this observe: function (subject, topic, data) { if (topic == "http-on-modify-request") { subject.queryinterface(components.interfaces.nsihttpchannel); var url = subject.uri.spec; /* url being requested. you might want this f...
...And 6 more matches
Sorting and filtering a custom tree view - Archive of obsolete content
operty for (var i in element) { if (prepareforcomparison(element[i]).indexof(filtertext) != -1) { table.push(element); break; } } }); } sort(); //restore scroll position if (topvisiblerow) { settopvisiblerow(topvisiblerow); } } //generic custom tree view stuff function treeview(table) { this.rowcount = table.length; this.getcelltext = function(row, col) { re
turn table[row][col.id]; }; this.getcellvalue = function(row, col) { re
turn table[row][col.id]; }; this.settree = function(treebox) { this.treebox = treebox; }; this.iseditable = function(row, col) { re
turn col.editable; }; this.iscontainer = function(row){ re
turn false; }; this.isseparator = function(row){ re
turn false; }; this.issorted = function(){ re
turn false; }; this.getlevel = ...
...1 : -1; //if the column is...
...re
turn table[row][col.id]; }; this.settree = function(treebox) { this.treebox = treebox; }; this.iseditable = function(row, col) { re
turn col.editable; }; this.iscontainer = function(row){ re
turn false; }; this.isseparator = function(row){ re
turn false; }; this.issorted = function(){ re
turn false; }; this.getlevel = function(row){ re
turn 0; }; this.getimagesrc = function(row,col){ re
turn null; }; this.getrowproperties = function(row,props){}; this.getcellproperties = function(row,col,props){}; this.getcolumnproperties = function(colid,col,props){}; this.cycleheader = function(col, elem) {}; } function sort(column) { var columnname; var order = tree.getattribute("sortdirection") == "ascending" ? 1 : -1; //if the column is passed and it's already sorted by that column, reve...
...And 6 more matches
Template and Tree Listeners - Archive of obsolete content
above makes use of the getresourceatindex and getindexofresource methods. these two methods are available for tree builders and will convert between an index in the tree and the associated member resource for the item at the index. naturally, we can't store the index as the item may have moved its position. ...
...finally, you can remove a listener using the builder's removelistener method. listening for tree changes the second type of listener is used to handle particular actions related to trees. ...
...agging onto a folder type of row. in other situations, you may wish to allow items to be dragged between (before or after) rows. this would be the situation if you were dragging items from that tree around, for instance dragging a bookmark from one location to another. the tree widget will draw a small line between the rows while dragging. ...
...And 6 more matches
Box Objects - Archive of obsolete content
e the position and size of the xul element as displayed, and second, you can determine the order of the elements in the box as displayed, instead of their order as they are stored in the dom. retrieving position and size the box object provides six read only properties, x, y, screenx, screeny, width and height, for determining the currently displayed position and size of an element. all values re
turned are in pixels. x, y the x and y coordinates are referenced from the top left corner of the document in the window (that portion which excludes the window border and title bar) and refer to the top left corner of the element, including css padding. css margins and borders* are excluded. the top left corner of the document is that which is obtained from screen.mozinnerscreenx, screen.mozinnersc...
...ich is obtained from screen.mozinnerscreenx, screen.mozinnerscreeny screenx, screeny the screenx and screeny coordinates are referenced from the absolute top left corner of the screen (screen.top,screen.left) and refer to the top left corner of the element, including css padding and borders. css margins are excluded. width, height the width and height properties are also measured in pixels and re
turn the width and height of the element, including css padding and borders. css margins are excluded. *note that x, y refers to the portion of the element that is just inside any borders, which is inconsistent with the other four boxobject position and size references, which include borders as part of the element. the values are always the position and sizes as currently displayed, so the values ...
...xible element will change in size and the box object dimensions will update accordingly. the following example shows this. example 1 : source view <button label="click me" oncommand="alert('the width is ' + this.boxobject.width);"/> you can use the width and height attributes of the element to specify the element's width and height, respectively. ...
...And 6 more matches
prefwindow - Archive of obsolete content
over this hides separator between titlebar and window contents. this affects only on mac os x. lastselected type: string set this to the id of the last selected pane. it will be opened by default the next time the preferences dialog is opened. onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called. re
turning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog method is called. if the handler re
turns true, the dialog will indeed go away, but if it re
turns false it will not. ondialogcancel type: script code the ...
... ondialogdisclosure type: script code the code in this attribute is called when the "disclosure" button is pressed. ...
... ondialogdisclosure type: script code the code in this attribute is called when the "disclosure" button is pressed. ondialoghelp type: script code the code in this attribute is called when the "help" button is pressed. ...
...And 6 more matches
textbox - Archive of obsolete content
ire if the user presses the enter key. the timed type is deprecated in gecko 1.9.1 and the search textbox may be used instead. value type: string the default value entered in a textbox. the attribute only holds the default value and is never modified when the user enters text. to get the updated value, use the value property. for number boxes, the default is 0 or the minimum value re
turned by the min property, whichever is higher. wrap type: string set this attribute to the value off to disable word wrapping in the textbox. if this attribute is not specified, word wrapping is enabled. wraparound type: boolean if true, the value of the number box will wrap around when the maximum or minimum value is exceeded. the minimum and maximum values must both not be infin...
... type: integer gets and sets the value of the increment attribute. inputfield type: textbox element in mozilla, the xul textbox is implemented as a wrapper around an html input element. this read only property holds a reference to this inner input element. label type: string sets the label attribute. gets the label attribute if it is present and not empty. otherwise it re
turns the value of the associated label element, if applicable. otherwise it re
turns the placeholder or emptytext property. the getter is mostly useful for screen readers. note: prior to firefox 3, and always in thunderbird and seamonkey, the label property of an autocomplete textbox re
turns its value, for compatibility with the menulist element. max type: integer gets an...
... caret (cursor) within the textbox. selectionstart type: integer get or set the beginning of the selected portion of the field's text. use in conjuction with the selectionend property. the value specifies the index of the first selected character. size type: integer gets and sets the value of the size attribute. spinbuttons type: element the read-only property re
turns a reference to the spinbuttons element used by the number box. tabindex type: integer gets and sets the value of the tabindex attribute. textlength type: integer holds the length of the text entered in the textbox. this property is read-only. timeout type: integer gets and sets the value of the timeout attribute. type type: string gets an...
...And 6 more matches
NPN_GetValue - Archive of obsolete content
rowser for information. syntax #include <npapi.h> nperror npn_getvalue(npp instance, npnvariable variable, void *value); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable information the call gets. ...
...pn_getvalue(npp instance, npnvariable variable, void *value); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable information the call gets. ...
...ers: instance pointer to the current plug-in instance. variable information the call gets. ...
...And 6 more matches
Implementing controls using the Gamepad API - Game development
es) and avoid the "bad" food (beer, burgers, pizza.) a countdown changes the type of food the fridge wants to eat every few seconds, so you have to be careful and act quickly. the second, hidden "change" implementation is the ability to transform the static fridge into a full-blown moving, shooting and eating machine. when you connect the controller, the game significantly changes (hungry fridge
turns into the super turbo hungry fridge) and you're able to control the armored fridge using the gamepad api. you have to shoot down the food, but once again you also have to find the type of food the fridge wants to eat at each point, or else you'll lose energy. the game encapsulates two totally different types of "change" — good food vs. bad food, and mobile vs. desktop. demo the full version ...
...ble on github where you can dive deep into the code and study exactly how it works. the code explained below is from the full version of the hungry fridge game, but it's almost identical to the one from the demo — the only difference is that the full version uses the turbo variable to decide whether or not the game will be launched using super turbo mode. ...
... implementation there are two important events to use along with the gamepad api — gamepadconnected and gamepaddisconnected. ...
...And 6 more matches
Introduction to the server side - Learn web development
a status line indicating whether or not the request succeeded (e.g. "http/1.1 200 ok" for success). the body of a successful response to a request would contain the requested resource (e.g. a new html page, or an image, etc...), which could then be displayed by the web browser. static sites the diagram below shows a basic web server architecture for a static site (a static site is one that re
turns the same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and re
turns an http response containing the document and a success status (usually 200 ok). if the file cannot be retrieved for some reason, ...
... content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and re
turns an http response containing the document and a success status (usually 200 ok). if the file cannot be retrieved for some reason, an error status is re
turned (see client error responses and server error responses). dynamic sites a dynamic website is one where some of the response content is generated dynamically, only when needed. on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of content than using static websit...
...es and server error responses). dynamic sites a dynamic website is one where some of the response content is generated dynamically, only when needed. on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of content than using static websites). a dynamic site can re
turn different data for a url based on information provided by the user or stored preferences and can perform other operations as part of re
turning a response (e.g. sending notifications). most of the code to support a dynamic website must run on the server. creating this code is known as "server-side programming" (or sometimes "back-end scripting"). the diagram below shows a simple architecture for...
...And 6 more matches
Handling common JavaScript problems - Learn web development
se 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 re
turned before trying to use the values they re
turn. for example, this ajax example checks to make sure the request is complete and the response has been re
turned 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 mistakes javascript developer...
...vailable. to install it: install atom (if you haven't got an up-to-date version already installed) — download it from the atom page linked above. go to atom's preferences... dialog (e.g. by choosing atom > preferences... on mac, or file > preferences... on windows/linux) and choose the install option in the left-hand menu. in the search packages text field, type "jslint" and press enter/re
turn to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-jshint plugin. after the packages have finished installing, try loading up a javascript file: you'll see any issues highlighted with green (for warnings) and red (for errors) circle...
...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 re
turned 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 = function() { let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); }...
...And 6 more matches
HTML parser threading
data from document.write(). it also has another lazily initialized tokenizer/tree builder for speculatively scanning the tail of document.write() data when the parser blocks without parsing the document.write() data to completion. nshtml5streamparser has one tokenizer/tree builder pair for parsing data from the network. additionally, each nshtml5parser has an associated nshtml5treeopexecutor that
turns the output (tree operations; discussed later) of the portable parser core into actions performed on the gecko dom. initialization an nshtml5parser is constructed without an nshtml5streamparser due to legacy code structure around parser creation. if the parser is not script-created, nshtml5parser::markasnotscriptcreated() is called to create an nshtml5streamparser for the nshtml5parser. due to le...
...lling using html in an iframe e.g. for a chat app.) some tree ops hold char or prunichar arrays. those arrays are allocated when creating the tree op and delete[]d by the destructor of nshtml5treeoperation. hence, data gets copied to and from these arrays. executing tree ops when the executor flushing runnable fires on the main thread, it calls nshtml5treeopexecutor::runflushloop(). this method re
turns immediately if another invocation of it is already on the call stack (nested event loop case). the method then enters a loop that has a bunch of re
turn conditions (including parser termination). the loop first flushes speculative loads (creation discussed later). if the executor is reading from a stage (i.e. the ops are coming from the parser thread), the executor moves the tree ops from the sta...
...f having to synchronize thread on a per-tree op basis.) if the executor isn't reading from a stage, it calls nshtml5parser::parseuntilblocked() to parse potential document.write()-generated data into tree ops. the outer loop then has an inner loop that iterates over the tree ops in the executor's queue and calls perform on each one. ...
...And 6 more matches
Introduction to NSPR
ently from other threads in the same process. a thread has a limited number of resources that it truly owns. these resources include the thread stack and the cpu register set (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, independent execution entity until it re
turns from its root function or the process abnormally terminates. (prthread and functions for creating and manipulating threads are described in detail in threads.) nspr threads are lightweight in the sense that they are cheaper than full-blown processes, but they are not free. they achieve the cost reduction by relying on their containing process to manage most of the resources that they access. th...
...ve threads. global threads are scheduled by the host os--not by nspr--either within a process or across processes on the entire host. global threads correspond to native threads on the host os. nspr threads can also be either user threads or system threads. nspr provides a function, pr_cleanup, that synchronizes process termination. pr_cleanup waits for the last user thread to exit before re
turning, whereas it ignores system threads when determining when a process should exit. this arrangement implies that a system thread should not have volatile data that needs to be safely stored away. priorities for nspr threads are based loosely on hints provided by the client and sometimes constrained by the underlying operating system. therefore, priorities are not rigidly defined. for more inform...
...hese systems can support local level thread abstractions that can be made preemptable, but run the risk of library corruption (libc). still other operating systems have a native notion of threads, and their libraries are thread-aware and support locking. however, if local threads are also present, and they are preemptable, they are subject to deadlock. at this time, the only safe solutions are to
turn off preemption (a runtime decision) or to preempt global threads only. interrupting threads nspr threads are interruptable, with some constraints and inconsistencies. to interrupt a thread, the caller of pr_interrupt must have the nspr reference to the target thread (prthread*). when the target is interrupted, it is rescheduled from the point at which it was blocked, with a status error indica...
...And 6 more matches
NSS_3.12_release_notes.html
camellia_128_cbc_sha tls_dh_dss_with_camellia_256_cbc_sha tls_dh_rsa_with_camellia_256_cbc_sha tls_dh_anon_with_camellia_256_cbc_sha tls_ecdh_anon_with_null_sha tls_ecdh_anon_with_rc4_128_sha tls_ecdh_anon_with_3des_ede_cbc_sha tls_ecdh_anon_with_aes_128_cbc_sha tls_ecdh_anon_with_aes_256_cbc_sha bugs fixed the following bugs have been fixed in nss 3.12. bug 354403: nsslist_createiterator re
turns pointer to a freed memory if the function fails to allocate a lock bug 399236: pkix wrapper must print debug output into stderr bug 399300: pkix error results not freed after use. bug 414985: crash in pkix_pl_ocsprequest_destroy bug 421870: strsclnt crashed in pkix tests. bug 429388: vfychain.main leaks memory bug 396044: warning: usage of uninitialized variable in ckfw/object.c(174) bug 396045:...
...bug 391291: shared database integrity checks not yet implemented. bug 391292: s...
...522: integrity hashes must be updated when passwords are changed. ...
...And 6 more matches
JS::CallArgs
signed argc, js::value *vp); name type description args unsigned number of argument. (2nd argument of jsnative) vp js::value * a pointer to the argument value array. (3nd argument of jsnative) methods methods of js::callargs method description bool requireatleast(jscontext *cx, const char *fnname, unsigned required) re
turns true if there are at least required arguments passed in. if false, it reports an error message on the context. methods inherited from js::callargsbase method description unsigned length() const re
turns the number of arguments.. js::mutablehandlevalue operator[](unsigned i) const re
turns the i-th zero-indexed argument. js::handlevalue get(unsig...
...e at least required arguments passed in. if false, it reports an error message on the context. methods inherited from js::callargsbase method description unsigned length() const re
turns the number of arguments.. js::mutablehandlevalue operator[](unsigned i) const re
turns the i-th zero-indexed argument. js::handlevalue get(unsigned i) const re
turns the i-th zero-indexed argument, or undefined if there's no such argument. bool hasdefined(unsigned i) const re
turns true if the i-th zero-indexed argument is present and is not undefined. methods inherited from js::detail::callreceiverbase method description jsobject &callee() const re
turns the function being called, as an object. must not be called af...
...this method must not be called when the function is being called as a constructor via new. ...
...And 6 more matches
NS ConvertUTF16toUTF8 external
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
NS LossyConvertUTF16toASCII external
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
PromiseFlatCString (External)
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsACString (External)
uals operator< operator<= operator== operator>= operator> operator!= equalsliteral find rfind findchar rfindchar appendint tointeger data members no public members. methods beginreading pruint32 beginreading(const char**, const char**) const - source re
turns the length, beginning, and end of a string in one operation. parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsCAutoString (External)
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsCString external
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsDependentCString external
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsDependentCSubstring external
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsDependentSubstring external
parameters prunichar* begin prunichar* end prunichar beginreading() const - source endreading prunichar endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos ...
... pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar* begin prunichar* end pruint32 newsize prunichar beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar endwriting() - source setlength prbool setlength(pruint32) - source ...
...ol lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char aasciistring find(const nsastring&, print32 (*) print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsLiteralCString (External)
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
nsLiteralString (External)
parameters char** begin char** end char* beginreading() const - source endreading char* endreading() const - source charat char charat(pruint32) const - source parameters pruint32 apos operator[] ...
...meters pruint32 apos first char first() const - source beginwriting pruint32 beginwriting(char**, char**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters ...
...tor!=(const char*) const - source parameters char* other equalsliteral prbool equalsliteral(const char*) const - source parameters char* other find print32 find(const nsacstring&, print32 (*)(const char*, const char*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 6 more matches
IAccessibleTableCell
[propget] hresult...
...sibles, [out] long nrowheadercells ); [propget] hresult rowindex([out] long rowindex ); [propget] hresult table([out] iunknown table ); methods columnextent() re
turns the number of columns occupied by this cell accessible. the result is greater than 1 if the specified cell spans multiple columns. [propget] hresult columnextent( [out] long ncolumnsspanned ); parameters ncolumnsspanned re
turns the 1 based column extent of the specified cell. re
turn value s_ok. columnheadercells() re
turns the column headers as an array of cell accessibles. [propget] hresult columnheadercells( [out, size_is(, ncolumnheadercells,)] iunknown cellaccessibles, [out] long ncolumnheadercells ); parameters cellaccessibles pointer to an array of references to cell accessibles. the array is allocated by t...
...ls() re
turns the column headers as an array of cell accessibles. [propget] hresult columnheadercells( [out, size_is(, ncolumnheadercells,)] iunknown cellaccessibles, [out] long ncolumnheadercells ); parameters cellaccessibles pointer to an array of references to cell accessibles. the array is allocated by the server. free it with cotaskmemfree. ncolumnheadercells the number of accessibles re
turned; the size of the re
turned array. re
turn value s_false if there is no header, [out] values are null and 0 respectively. s_ok. columnindex() translates this cell accessible into the corresponding column index. ...
...And 6 more matches
nsIJSON
decodetojsval() note: this met...
... decodetojsval() note: this method may only be used from native code, and provides a way to decode a json string to a jsval for use in your native code. don't forget to gcroot the result before using it. ...
...json string. decodetojsval() note: this method may only be used from native code, and provides a way to decode a json string to a jsval for use in your native code. don't forget to gcroot the result before using it. jsval decodetojsval( in astring str, in jscontext cx ); parameters str the json string to decode. cx the javascript runtime context to use to decode the string. re
turn value the original javascript object, reconstructed from the json string. don't forget to gcroot the jsval before using it. decodefromstream() decodes a json string read from an input stream, re
turning the javascript object it represents. jsobject decodefromstream( in nsiinputstream stream, in long contentlength ); parameters stream the nsiinputstream from which to read the json...
...And 6 more matches
nsILoginManager
s provided for use only by the formfillcontroller, which calls it directly. it should not be used for any other purpose. nsiautocompleteresult autocompletesearch( in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement ); parameters asearchstring missing description apreviousresult missing description aelement missing description re
turn value missing description countlogins() re
turns the number of logins matching the specified criteria. called when only the number of logins is needed, and not the actual logins (which avoids prompting the user for a master password, as the logins don't need to be decrypted). unsigned long countlogins( in astring ahostname, in astring aactionurl, in astring ahttprealm ); parameters ...
...atch any form logins (for example when interested in protocol logins only), specify null. ahttprealm for protocol logins, specify the http realm for which the login applies; this is obtained from the www-authenticate header (see rfc 2617). to match any protocol login, specify "" (empty string). to not match any protocol logins (for example when interested in form logins only), specify null. ...
... findlogins() searches for logins matching the specified criteria. called when looking for logins that might be applicable to a given form or authentication request. ...
...And 6 more matches
nsIMsgMessageService
msgwindow, out nsiuri aurl); parameters asrcuri the string url of the message to copy. acopylistener an nsistreamlistener to be notified of copy events. amovemessage set to true if you want the message to be moved. false leaves it as just a copy. aurllistener a nsiurllistener to be notified of url events. amsgwindow nsimsgwindow for progress and status feedback re
turn values aurl the new nsiuri of the message. copymessages() copy multiple messages at a time. see copymessage [noscript] void copymessages(in nsmsgkeyarrayptr keys, in nsimsgfolder srcfolder, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener a...
...ndow amsgwindow, out nsiuri aurl); parameters keys an array of message keys to be copied. srcfolder acopylistener an nsistreamlistener to be notified of copy events. amovemessage set to true if you want the message to be moved. false leaves it as just a copy. aurllistener an nsiurllistener amsgwindow nsimsgwindow for progress and status feedback re
turn values aurl the new nsiuri of the message. (?) displaymessage() when you want a message displayed.... void displaymessage(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, in string acharsetoverride, out nsiuri aurl); ...
... in string acharsetoverride, out nsiuri aurl); parameters amessageuri a uri representing the message to display. adisplayconsumer is (for now) an nsidocshell which the message is loaded into. amsgwindow nsimsgwindow for progress and status feedback aurllistener an nsiurllistener acharsetoverride (optional) character set over ride to force the message to use. re
turn values aurl the new nsiuri of the message. openattachment() downloads and opens an attachment. void openattachment(in string acontenttype, in string afilename, in string aurl, in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in n...
...And 6 more matches
Component; nsIPrefBranch
erenced by this branch. getboolpref() called to get the state of an individual boolean preference. boolean getboolpref( in string aprefname, [optional] in boolean adefaultvalue ); parameters aprefname the boolean preference to get the state of. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing an exception). re
turn value the value of the requested boolean preference. getcharpref() called to get the state of an individual string preference. string getcharpref( in string aprefname, [optional] in string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing a...
...of the requested boolean preference. getcharpref() called to get the state of an individual string preference. string getcharpref( in string aprefname, [optional] in string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing an exception). re
turn value re
turns string - the value of the requested string preference. getstringpref() requires gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55) called to get the state of an individual utf-8 string preference. utf8string getstringpref( in string aprefname, [optional] in utf8string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultval...
...ko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55) called to get the state of an individual utf-8 string preference. utf8string getstringpref( in string aprefname, [optional] in utf8string adefaultvalue ); parameters aprefname the string preference to retrieve. adefaultvalue optional - a default value to use if the preference does not exist (instead of throwing an exception). re
turn value re
turns utf8tring - the value of the requested string preference. getchildlist() re
turns an array of strings representing the child preferences of the root of this branch. note: this method can be called on either a default or user branch but, in effect, always operates on both. (to call from javascript use children = nsiprefbranch.getchildlist("",obj), which will fill in obj.value wit...
...And 6 more matches
nsIPrincipal
string capability, inout voidptr annotation); native code only! void setcanenablecapability(in string capability, in short canenable); native code only! boolean subsumes(in nsiprincipal other); attributes attribute type description certificate nsisupports the certificate associated with this principal, if any. if there isn't one, this will re
turn null. getting this attribute never throws. read only. certificateid string the fingerprint id of this principal's certificate. throws if there is no certificate associated with this principal. read only. obsolete since gecko 1.8 commonname string the common name for the certificate. this pertains to the certificate authority organization. throws if there is no certi...
...t.domain, and may be null. setting this has no effect on the uri. native code only! fingerprint autf8string the fingerprint id of this principal's certificate. throws if there is no certificate associated with this principal. read only. hascertificate boolean whether this principal is associated with a certificate. read only. hashvalue unsigned long re
turns a hash value for the principal. read only. native code only! origin string the origin of this principal's codebase uri. an origin is defined as: scheme + host + port. read only. prettyname autf8string the pretty name for the certificate. this sort of (but not really) identifies the subject of the certificate (the entity that stands behind the certificate). note...
...on a set of capabilities, the minimum is computed. constant value description enable_denied 1 enable_unknown 2 enable_with_user_permission 3 enable_granted 4 methods native code only!canenablecapability short canenablecapability( in string capability ); parameters capability missing description re
turn value missing description exceptions thrown missing exception missing description checkmayload() checks whether this principal is allowed to load the network resource located at the given uri under the same-origin policy. this means that codebase principals are only allowed to load resources from the same domain, the system principal is allowed to load anything, and null principals are ...
...And 6 more matches
nsISupportsArray
deleteelementat() void deleteelementat( in unsigned long aindex ); parameters aindex deletelastelement() void deletelastelement( in nsisupports aelement ); parameters aelement violates the xpcom interface guidelines elementat() nsisupports elementat( in unsigned...
...elementat(in nsisupports aelement, in unsigned long aindex); violates the xpcom interface guidelines boolean sizeto(in long asize); violates the xpcom interface guidelines methods violates the xpcom interface guidelines appendelements() boolean appendelements( in nsisupportsarray aelements ); parameters aelements re
turn value clone() nsisupportsarray clone(); parameters none. re
turn value compact() void compact(); parameters none. ...
...; parameters none. re
turn value compact() void compact(); parameters none. ...
...And 6 more matches
nsITransactionListener
ansactionmanager amanager, in nsitransaction atransaction); boolean willundo(in nsitransactionmanager amanager, in nsitransaction atransaction); methods didbeginbatch() called after a nsitransactionmanager begins a batch. void didbeginbatch( in nsitransactionmanager amanager, in nsresult aresult ); parameters amanager the nsitransactionmanager that began a batch. ...
...
turned after beginning a batch. diddo() called after a nsitransactionmanager calls the nsitransaction.dotransaction() method of a transaction. void diddo( in nsitransactionmanager amanager, in nsitransaction atransaction, in nsresult adoresult ); parameters amanager the nsitransactionmanager that did the transaction. atransaction the transaction that was executed. adoresult the nsresult re
turned after executing the transaction. didendbatch() called after a nsitransactionmanager ends a batch. void didendbatch( in nsitransactionmanager amanager, in nsresult aresult ); parameters amanager the nsitransactionmanager ending a batch. aresult the nsresult re
turned after ending a batch. didmerge() called after a nsitransactionmanager tries to merge a transaction, that was just executed,...
...ger amanager, in nsitransaction atoptransaction, in nsitransaction atransactiontomerge, in boolean adidmerge, in nsresult amergeresult ); parameters amanager the nsitransactionmanager ending a batch. atoptransaction the transaction at the top of the undo stack. atransactiontomerge the transaction to merge. adidmerge true if transaction was merged, else false. ...
...And 6 more matches
nsIWindowWatcher
users must keep this attribute current, including after the topmost window is closed. this attribute will be null if the active window is not an nsidomwindow; for example, if the active window is an alert. methods getchromeforwindow() retrieve the chrome window mapped to the given dom window. nsiwindowwatcher keeps a list of all top-level dom windows currently open, alon...
... dom window. nsiwindowwatcher keeps a list of all top-level dom windows currently open, along with their corresponding chrome interfaces. since dom windows lack a (public) means of retrieving their corresponding chrome, this method will do that. nsiwebbrowserchrome getchromeforwindow( in nsidomwindow awindow ); parameters awindow the nsidomwindow whose chrome window the caller needs. ...
...r corresponding chrome interfaces. since dom windows lack a (public) means of retrieving their corresponding chrome, this method will do that. nsiwebbrowserchrome getchromeforwindow( in nsidomwindow awindow ); parameters awindow the nsidomwindow whose chrome window the caller needs. re
turn value an nsiwebbrowserchrome object for the corresponding chrome window getnewauthprompter() re
turn a newly created nsiauthprompt implementation. nsiauthprompt getnewauthprompter( in nsidomwindow aparent ); parameters aparent the parent window used for posing alerts. can be null. re
turn value a new nsiauthprompt object. getnewprompter() re
turn a newly created nsiprompt implementation. nsiprompt getnewprompter( in nsidomwindow aparent ); parameters aparent the parent nsido...
...And 6 more matches
nsIXULTemplateQueryProcessor
in astring aexpr ); parameters arulenode rule to add the binding to. avar variable that will be bound. aref variable that holds reference value. aexpr expression used to compute the value to assign. exceptions thrown ns_error_unexpected if generateresults() has already been called. compareresults() compare two results to determine their order, used when sorting results. this method should re
turn -1 when the left result is less than the right, 0 if both are equivalent, and 1 if the left is greater than the right. the comparison should only consider the values for the specified variable. if the comparison variable is null, the results may be sorted in a natural order, for instance, based on the order the data in stored in the datasource. this method must only be called with results that we...
...ethod must only be called with results that were created by this query processor. print32 compareresults( in nsixultemplateresult aleft, in nsixultemplateresult aright, in nsiatom avar, in unsigned long asorthints ); parameters aleft the left result to compare. aright the right result to compare. avar variable to compare. asorthints the sort hints are the flags in nsixulsortservice. re
turn value -1 if aleft < aright 0 if aleft == aright 1 if aleft > aright compilequery() compile a query from a node. the result of this function will later be passed to generateresults() for result generation. if null is re
turned, the query will be ignored. the template builder will call this method once for each query within the template, before any results can be generated using generateresults(),...
... may use the member variable as a hint to indicate what variable is expected to contain the results. nsisupports compilequery( in nsixultemplatebuilder abuilder, in nsidomnode aquery, in nsiatom arefvariable, in nsiatom amembervariable ); parameters abuilder the template builder. aquery <query> node to compile. arefvariable the reference variable. amembervariable the member variable. re
turn value a compiled query object. done() called when the template builder is being destroyed so that the query processor can clean up any state. the query processor should remove as much state as possible, such as results or references to the builder. this method will also be called when the template is going to be rebuilt. void done(); parameters none. generateresults() generate the results of a q...
...And 6 more matches
nsIZipReader
y must be stored in the zip in either uncompressed or deflate-compressed format for the extraction to be successful. if the entry is a directory, the directory will be extracted non-recursively. void extract( in autf8string zipentry, in nsifile outfile ); parameters zipentry the zip entry to extract. outfile the local file destination used to extract the zip entry. findentries() re
turns a string enumerator containing the matching entry names. nsiutf8stringenumerator findentries( in autf8string apattern ); parameters apattern a regular expression used to find matching entries in the zip file. set this parameter to null (javascript) or emptycstring() (c++) to get all entries; otherwise, use the following syntax: * matches anything. ? matches one character. $ matc...
...cified for '[^az]' will happen.) [a-z] matches any character between a and z. the characters a and z must either both be letters or both be numbers, with the character represented by 'a' having a lower ascii value than the character represented by 'z'. [^az] matches any character except a or z. if ] is to appear inside the brackets as a character to not match, it must be escaped. pat~pat2 re
turns matches to the pattern 'pat' which do not also match the pattern 'pat2'. this may be used to perform filtering upon the results of one pattern to remove all matches which also match another pattern. for example, because '*' matches any string and '*z*' matches any string containing a 'z', '*~*z*' will match all strings except those containing a 'z'. note that a pattern may not use '~' multiple t...
.... (foo|bar) will match either the pattern foo or the pattern bar. neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above. \ will escape a special character. escaping is required for all special characters unless otherwise specified. all other characters match case-sensitively. an apattern not conforming to this syntax has undefined behavior. re
turn value the nsiutf8stringenumerator containing the matching entry names. exceptions thrown ns_error_illegal_value on many but not all invalid apattern values. getcertificateprincipal() re
turns an object describing the entity which signed an entry. parsemanifest must be called first. if aentryname is an entry in the jar, getinputstream() must be called after parsemanifest. if aentryname is ...
...And 6 more matches
XPIDL
munging by the msvc++ compiler, an attribute with the name `iid' is forbidden. in addition, any attribute whose name matches the regex /^[a-z]{2,3}i[a-z][a-z]/ is emitted with a warning, as its name looks like an nsiinterface or a moziinterface declaration. also like methods, if the first character of an attribute is lowercase in idl, it is made uppercase in native code only. methods define a re
turn type and a series of in and out parameters. when called from a javascript context, they invocation looks as it is declared for the most part; some parameter properties can adjust what the code looks like. the calls are more mangled in native contexts. an important attribute for methods and attributes is scriptability. a method or attribute is scriptable if it is declared in a scriptable interfac...
... what the code looks like. the calls are more mangled in native contexts. an important attribute for methods and attributes is scriptability. a method or attribute is scriptable if it is declared in a scriptable interface and it lacks a noscript or notxpcom property. any method that is not scriptable can only be accessed by native code. however, scriptable methods must contain parameters and a re
turn type that can be translated to script: any native type, save those declared with an nsid, utf8string, cstring, astring, or jsval property, may not be used in a scriptable method or attribute. an exception to the above rule is if the parameter has the iid_is property (a special case for some queryinterface-like operations). in general, this means that the only usable native types are those declare...
...d in a scriptable method or attribute. an exception to the above rule is if the parameter has the iid_is property (a special case for some queryinterface-like operations). in general, this means that the only usable native types are those declared in nsrootidl.idl (see above). methods and attributes are mangled on conversion to native code. if a method is declared notxpcom, the mangling of the re
turn type is prevented, so it is called mostly as it looks. otherwise, the re
turn type of the native method is nsresult, and the re
turn type acts as a final outparameter if it is not void. the name is translated so that the first character is unconditionally uppercase; subsequent characters are unaffected. however, the presence of the binaryname property allows the user to select another name to use i...
...And 6 more matches
Using COM from js-ctypes
$ cl ole32.lib test.cpp vtable needs vtable description here. the order of the vtable is very critical. when used from c or js-ctypes, the order of the vtable methods should match the order of the c++ vtable. __stdcall and __cdecl needs __stdcall and __cdecl (callback_abi) descr...
... $ cl ole32.lib test.c c code with pseudo struct needs pseudo struct description here. #include <sapi.h> struct myispvoicevtbl; struct myispvoice { struct myispvoicevtbl* lpvtbl; }; struct myispvoicevtbl { /* start inherit from iunknown */ void* queryinterface; void* addref; ulong (__...
...it could be converted into js-ctypes in almost straightforward way. clsid and iid needs clsid and iid of spvoice and ispvoice description here. com types and functions needs com types (guid) and functions (coinitialize etc) description here. converted js-ctypes code here's converted code. this example uses busy loo...
...And 6 more matches
Element.closest() - Web APIs
it may be null. exceptions syntaxerror is thrown if the selectors is not a valid selector list string. ...
...it may be null. exceptions syntaxerror is thrown if the selectors is not a valid selector list string. ...
...it may be null. exceptions syntaxerror is thrown if the selectors is not a valid selector list string. ...
...And 6 more matches
SubtleCrypto.encrypt() - Web APIs
syntax const result = crypto.subtle.encrypt(algorithm, key, data); parameters algorithm is an object specifying the algorithm to be used and any extra parameters if required: to use rsa-oaep, pass an rsaoaepparams object. ...
... any extra parameters if required: to use rsa-oaep, pass an rsaoaepparams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for encryption. data is a buffersource containing the data to be encrypted (also known as the plaintext). re
turn value result is a promise that fulfills with an arraybuffer containing the "ciphertext". exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the o...
...attacker. examples note: you can try the working examples out on github. rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep. see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".rsa-oaep #message"); let message = messagebox.value; let enc = new textencoder(); re
turn enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); re
turn window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode. see the complete code on github. function getmessageencoding() { c...
...And 6 more matches
SubtleCrypto.importKey() - Web APIs
be used to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. derivebits: the key may be used in deriving bits. wrapkey: the key may be used to wrap a key. unwrapkey: the key may be used to unwrap a key. re
turn value result is a promise that fulfills with the imported key as a cryptokey object. exceptions the promise is rejected when one of the following exceptions is encountered: syntaxerror raised when keyusages is empty but the unwrapped key is of type secret or private. typeerror raised when trying to use an invalid format or if the keydata is not suited for that format. supported form...
...av-ysew" }; examples note: you can try the working examples on github. raw import this example imports an aes key from an arraybuffer containing the bytes to use. see the complete code on github. const rawkey = window.crypto.getrandomvalues(new uint8array(16)); /* import an aes secret key from an arraybuffer containing the raw bytes. takes an arraybuffer string containing the bytes, and re
turns a promise that will resolve to a cryptokey representing the secret key. */ function importsecretkey(rawkey) { re
turn window.crypto.subtle.importkey( "raw", rawkey, "aes-gcm", true, ["encrypt", "decrypt"] ); } pkcs #8 import this example imports an rsa private signing key from a pem-encoded pkcs #8 object. see the complete code on github. /* convert a string into an arr...
...kcs #8 object. see the complete code on github. ...
...And 6 more matches
SubtleCrypto - Web APIs
security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. properties this interface doesn't inherit any properties, as it has no parent interface. methods this interface doesn't inherit any methods, as it has no parent interface. ...
...ou probably shouldn't be using this api. properties this interface doesn't inherit any properties, as it has no parent interface. methods this interface doesn't inherit any methods, as it has no parent interface. subtlecrypto.encrypt() re
turns a promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. subtlecrypto.decrypt() re
turns a promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. ...
...erface doesn't inherit any methods, as it has no parent interface. subtlecrypto.encrypt() re
turns a promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. subtlecrypto.decrypt() re
turns a promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. subtlecrypto.sign() re
turns a promise that fulfills with the signature corresponding to the text, algorithm, and key given as parameters. ...
...And 6 more matches
TextRange - Web APIs
when you hold down the mouse to select the content on the page, you create a typical textrange. it is implemented in ie, then a textrange object can be created by element.createtextrange() or document.selection.createrange(). note that this interface is not supported in non ie browsers. alternative selection and range interfaces can be used. ...
...plemented in ie, then a textrange object can be created by element.createtextrange() or document.selection.createrange(). note that this interface is not supported in non ie browsers. alternative selection and range interfaces can be used. properties textrange.boundingheightread only re
turns the height of the rectangle bound to the textrange object. ...
...ative selection and range interfaces can be used. properties textrange.boundingheightread only re
turns the height of the rectangle bound to the textrange object. textrange.boundingleftread only re
turns the distance between the left edge of the rectangle that binds the textrange object and the left edge that completely contains the textrange object. textrange.boundingtopread only re
turns the distance between the top edge of the rectangle that binds the textrange object and the top edge that completely contains the textrange object. textrange.boundingwidthread only re
turns the width of the rectangle bound to the textrange object. textrange.htmltext gets or sets the html content within the textrange. textrange.text gets or sets the plaintext content within the textrange...
...And 6 more matches
WebGL2RenderingContext - Web APIs
renderingcontext interface. some methods of the webgl 1 context can accept additional values when used in a webgl 2 context. you will find this info noted on the webgl 1 reference pages. the webgl tutorial has more information, examples, and resources on how to get started with webgl. constants see the webgl constants page. state information webgl2renderingcontext.getindexedparameter() re
turns the indexed value for the given target. buffers webgl2renderingcontext.bufferdata() initializes and creates the buffer object's data store. webgl2renderingcontext.buffersubdata() updates a subset of a buffer object's data store. webgl2renderingcontext.copybuffersubdata() copies part of the data of a buffer to another buffer. webgl2renderingcontext.getbuffersubdata() reads data from a...
...amebuffer. webgl2renderingcontext.invalidateframebuffer() invalidates the contents of attachments in a framebuffer. webgl2renderingcontext.invalidatesubframebuffer() invalidates portions of the contents of attachments in a framebuffer webgl2renderingcontext.readbuffer() selects a color buffer as the source for pixels. renderbuffers webgl2renderingcontext.getinternalformatparameter() re
turns information about implementation-dependent support for internal formats. webgl2renderingcontext.renderbufferstoragemultisample() creates and initializes a renderbuffer object's data store and allows specifying the number of samples to be used. textures webgl2renderingcontext.texstorage2d() specifies all levels of two-dimensional texture storage. webgl2renderingcontext.texstorage3d() sp...
...om the current webglframebuffer into an existing 3d texture sub-image. webgl2renderingcontext.compressedteximage3d() specifies a three-dimensional texture image in a compressed format. webgl2renderingcontext.compressedtexsubimage3d() specifies a three-dimensional sub-rectangle for a texture image in a compressed format. programs and shaders webgl2renderingcontext.getfragdatalocation() re
turns the binding of color numbers to user-defined varying out variables. uniforms and attributes webgl2renderingcontext.uniform[1234][uif][v]() methods specifying values of uniform variables. webgl2renderingcontext.uniformmatrix[234]x[234]fv() methods specifying matrix values for uniform variables. webgl2renderingcontext.vertexattribi4[u]i[v]() methods specifying integer values for generic ...
...And 6 more matches
Signaling and video calling - Web APIs
n the two. here's the expected sequence of events: we'll see this detailed more over the course of this article. ice candidate exchange process when each peer's ice layer begins to send candidates, it enters into an exchange among the various points in the chain that looks like this: each side sends candidates to the other as it receives them from their local ice layer; there is no taking
turns or batching of candidates. as soon as the two peers agree upon one candidate that they can both use to exchange the media, media begins to flow. each peer continues to send candidates until it runs out of options, even after the media has already begun to flow. this is done in hopes of identifying even better options than the one initially selected. if conditions change—for example the networ...
...o: true, // we want an audio track video: true // ...and we want a video track }; function invite(evt) { if (mypeerconnection) { alert("you can't start a call because you already have one open!"); } else { var clickedusername = evt.target.textcontent; if (clickedusername === myusername) { alert("i'm afraid i can't let you talk to yourself. ...
...he variable targetusername and call createpeerconnection(), a function which will create and do basic configuration of the rtcpeerconnection. once the rtcpeerconnection has been created, we request access to the user's camera and microphone by calling mediadevices.getusermedia(), which is exposed to us through the navigator.mediadevices.getusermedia property. when this succeeds, fulfilling the re
turned promise, our then handler is executed. it receives, as input, a mediastream object representing the stream with audio from the user's microphone and video from their webcam. note: we could restrict the set of permitted media inputs to a specific device or set of devices by calling navigator.mediadevices.enumeratedevices() to get a list of devices, filtering the resulting list based on our des...
...And 6 more matches
Web Authentication API - Web APIs
ser in or as a form of second-factor authentication. please note: both create() and get() require a secure context (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context. in their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they re
turn the challenge signed by the private key back to the server. this proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network. in order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser: s...
... in the publickeycredentialcreationoptions dictionary. likewise, the full set of response fields can be found in the publickeycredential interface (where publickeycredential.response is the authenticatorattestationresponse interface). note most javascript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently re
turns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means. figure 1 - a diagram showing the sequence of actions for a web authentication registration and the essential data associated with each action. the registration steps are: application requests registration - the application makes the...
...t specified and is outside of the scope of the web authentication api. typically, server communications would be rest over https (probably using xmlhttprequest or fetch), but they could also be soap, rfc 2549 or nearly any other protocol provided that the protocol is secure. the parameters received from the server will be passed to the create() call, typically with little or no modification and re
turns a promise that will resolve to a publickeycredential containing an authenticatorattestationresponse. note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it must be generated on the server in order to ensure the security of the registration process. browser calls authenticatormakecredential() on authenticator - internally, the browser ...
...And 6 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
ee reasons for delays longer than specified below. arg1, ..., argn optional additional arguments which are passed through to the function specified by function. note: passing additional parameters to the function in the first syntax does not work in internet explorer 9 and below. if you want to enable this functionality on that browser, you must use a polyfill (see the polyfill section). re
turn value the re
turned timeoutid is a positive integer value which identifies the timer created by the call to settimeout(); this value can be passed to cleartimeout() to cancel the timeout. it may be helpful to be aware that settimeout() and setinterval() share the same pool of ids, and that cleartimeout() and clearinterval() can technically be used interchangeably. for clarity, however, you shoul...
...function() { vcallback.apply(null, aargs); } : vcallback, ndelay); }; }, 0, 'test'); var interval = setinter...
...= window.setinterval(code, delay); |*| \*/ (function() { settimeout(function(arg1) { if (arg1 === 'test') { // feature test is passed, no need for polyfill re
turn; } var __nativest__ = window.settimeout; window.settimeout = function(vcallback, ndelay /*, argumenttopass1, argumenttopass2, etc. ...
...And 6 more matches
XMLHttpRequest - Web APIs
etter choice. constructor xmlhttprequest() the constructor initializes an xmlhttprequest. it must be called before any other method calls. properties this interface also inherits properties of xmlhttprequesteventtarget and of eventtarget. xmlhttprequest.onreadystatechange an eventhandler that is called whenever the readystate attribute changes. ...
...est. it must be called before any other method calls. properties this interface also inherits properties of xmlhttprequesteventtarget and of eventtarget. xmlhttprequest.onreadystatechange an eventhandler that is called whenever the readystate attribute changes. xmlhttprequest.readystate read only re
turns an unsigned short, the state of the request. xmlhttprequest.response read only re
turns an arraybuffer, blob, document, javascript object, or a domstring, depending on the value of xmlhttprequest.responsetype, that contains the response entity body. xmlhttprequest.responsetext read only re
turns a domstring that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent. xmlhttprequest.responsetype is an enumerated value that ...
...depending on the value of xmlhttprequest.responsetype, that contains the response entity body. xmlhttprequest.responsetext read only re
turns a domstring that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent. xmlhttprequest.responsetype is an enumerated value that defines the response type. xmlhttprequest.responseurl read only re
turns the serialized url of the response or the empty string if the url is null. ...
...And 6 more matches
<input type="file"> - HTML: Hypertext Markup Language
attribute, as shown above, specifies that multiple files can be chosen at once. the user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down shift or control, and then clicking). if you only want the user to choose a single file per <input>, omit the multiple attribute. getting information on selected files the selected files' are re
turned by the element's htmlinputelement.files property, which is a filelist object containing a list of file objects. the filelist behaves like an array, so you can check its length property to get the number of selected files. each file object contains the following information: name the file's name. lastmodified a number specifying the date and time at which the file was last modified, in mi...
...loop through each one, printing information about it into the preview <div>. things to note here: we use the custom validfiletype() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute). if it is, we: print out its name and file size into a list item inside the previous <div> (obtained from file.name and file.size). the custom re
turnfilesize() function re
turns a nicely-formatted version of the size in bytes/kb/mb (by default the browser reports the size in absolute bytes). generate a thumbnail preview of the image by calling url.createobjecturl(curfiles[i]). then, insert the image into the list item too by creating a new <img> and setting its src to the thumbnail. if the file type is invalid, we display a message ins...
...update your selection.`; listitem.appendchild(para); } list.appendchild(listitem); } ...
...And 6 more matches
Meta programming - JavaScript
s (e.g. property lookup, assignment, enumeration, function invocation, etc). with the help of these two objects you are able to program at the meta level of javascript. proxies introduced in ecmascript 6, proxy objects allow you to intercept certain operations and to implement custom behaviors. for example, getting a property on an object: let handler = { get: function(target, name) { re
turn name in target? target[name] : 42 } } let p = new proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 the proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. here, an object that is proxied will not re
turn undefined when getting undefined properties, but will instead re
turn the number 42. additional examples are available on t...
...e following table summarizes the available traps available to proxy objects. see the reference pages for detailed explanations and examples. handler / trap interceptions invariants handler.getprototypeof() object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof getprototypeof method must re
turn an object or null. if target is not extensible, object.getprototypeof(proxy) method must re
turn the same value as object.getprototypeof(target). handler.setprototypeof() object.setprototypeof() reflect.setprototypeof() if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). handler.isextensible() ob...
...ethod must re
turn the same value as object.getprototypeof(target). handler.setprototypeof() object.setprototypeof() reflect.setprototypeof() if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). handler.isextensible() object.isextensible() reflect.isextensible() object.isextensible(proxy) must re
turn the same value as object.isextensible(target). handler.preventextensions() object.preventextensions() reflect.preventextensions() object.preventextensions(proxy) only re
turns true if object.isextensible(proxy) is false. handler.getownpropertydescriptor() object.getownpropertydescriptor() reflect.getownpropertydescriptor() getownpropertydescriptor m...
...And 6 more matches
Array.prototype.findIndex() - JavaScript
the findindex() method re
turns the index of the first element in the array that satisfies the provided testing function. otherwise, it re
turns -1, indicating that no element passed the test. 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. see also the find() method, which re
turns the value of an array element, instead of its index. syntax arr.findindex(callback( element[, index[, array]] )[, thisarg]) parameters callback a function to execute on each value in the array until the function re
turns true, indicating that the satisfying element was found. it takes three arguments: element the current e...
... until the function re
turns true, indicating that the satisfying element was found. it takes three arguments: element the current element being processed in the array. index optional the index of the current element being processed in the array. array optional the array findindex() was called upon. thisarg optional optional object to use as this when executing callback. re
turn value the index of the first element in the array that passes the test. otherwise, -1. description the findindex() method executes the callback function once for every index in the array until it finds the one where callback re
turns a truthy value. if such an element is found, findindex() immediately re
turns the element's index. ...
... edge case alert: unlike other array methods such as array.some(), callback is run even for indexes with unassigned values. ...
...And 6 more matches
Array.prototype.some() - JavaScript
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 arr.some(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. ...
...(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array some() was called upon. thisargoptional a value to use as this when executing callback. ...
...ameters callback a function to test for each element, taking three arguments: element the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array some() was called upon. thisargoptional a value to use as this when executing callback. re
turn value true if the callback function re
turns a truthy value for at least one element in the array. otherwise, false. description the some() method executes the callback function once for each element present in the array until it finds the one where callback re
turns a truthy value (a value that becomes true when converted to a boolean). if such an element is found, some() immediately re
turns true. otherwise, some() re
turns false. callbac...
...And 6 more matches
JSON.parse() - JavaScript
the json.parse() method parses a json string, constructing the javascript value or object described by the string. an optional reviver function can be provided to perform a transformation on the resulting object before it is re
turned. 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 json.parse(text[, reviver]) parameters text the string to parse as json. ...
...contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax json.parse(text[, reviver]) parameters text the string to parse as json. see the json object for a description of json syntax. reviver optional if a function, this prescribes how the value originally produced by parsing is transformed, before being re
turned. re
turn value the object, array, string, number, boolean, or null value corresponding to the given json text. exceptions throws a syntaxerror exception if the string to parse is not valid json. polyfill // from https://github.com/douglascrockford/json-js/blob/master/json2.js if (typeof json.parse !== "function") { var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(?:["\\\/bfnrt]|u[0-...
... var j; function walk(holder, key) { // the walk method is used to recursively walk the resulting structure so // that modifications can be made. var k; var v; var value = holder[key]; if (value && typeof value === "object") { ...
...And 6 more matches
Math.clz32() - JavaScript
the math.clz32() function re
turns the number of leading zero bits in the 32-bit binary representation of a number. 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 math.clz32(x) parameters x a number. re
turn value the number of leading zero bits in the 32-bit binary representation of the given number. description "clz32" is short for countleadingzeroes32. if x is not a number, then it will be converted to a number first, then converted to a 32-bit unsigned integer. if the converted 32-bit unsigned integer is 0, then re
turn 32, because all bits are 0. this function is particularly useful for syste...
...the ctrz function below fills in all the high bits with the lowest filled bit, then negates the bits to erase all higher set bits so that clz can then be used. var clz = math.clz32; function ctrz(integer){ // count trailing zeros // 1. fill...
...s to erase all higher set bits so that clz can then be used. var clz = math.clz32; function ctrz(integer){ // count trailing zeros // 1. fill in all the higher bits after the first one integer |= integer << 16; integer |= integer << 8; integer |= integer << 4; integer |= integer << 2; integer |= integer << 1; // 2. now, inversing the bits reveals the lowest bits re
turn 32 - clz(~integer) |0; // `|0` ensures integer coercion } function ctron(integer){ // count trailing ones // no shift-filling-in-with-ones operator is available in // javascript, so the below code is the fastest re
turn ctrz(~integer); /* alternate implementation for demonstrational purposes: // 1. erase all the higher bits after the first zero integer &= (integer << ...
...And 6 more matches
Promise.all() - JavaScript
the promise.all() method takes an iterable of promises as an input, and re
turns a single promise that resolves to an array of the results of the input promises. this re
turned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. it rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error. 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. ...
...ses throwing an error, and will reject with this first rejection message / error. 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. ...
...te 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. re
turn 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 re
turns an already resolved promise in this case. a pending promise in all other cases. ...
...And 6 more matches
String.prototype.charCodeAt() - JavaScript
if you want the entire code point value, use codepointat(). ...
...o contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the utf-16 code unit matches the unicode code point for code points which can be represented in a single utf-16 code unit. ...
... a single utf-16 code unit (because its value is greater than 0xffff) then the code unit re
turned will be the first part of a surrogate pair for the code point. if you want the entire code point value, use codepointat(). syntax str.charcodeat(index) parameters index an integer greater than or equal to 0 and less than the length of the string. if index is not a number, it defaults to 0. re
turn value a number representing the utf-16 code unit value of the character at the given index. if index is out of range, charcodeat() re
turns nan. description unicode code points range from 0 to 1114111 (0x10ffff). the first 128 unicode code points are a direct match of the ascii character encoding. ...
...And 6 more matches
String.prototype.match() - JavaScript
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.match(regexp) parameters regexp a regular expression object. if regexp is a non-regexp object, it is implicitly converted to a regexp by using new regexp(regexp). if you don't give any parameter and use the match() method directly, you will get an array with an empty string: [""]. ...
...plicitly converted to a regexp by using new regexp(regexp). if you don't give any parameter and use the match() method directly, you will get an array with an empty string: [""]. re
turn value an array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found. if the g flag is used, all results matching the complete regular expression will be re
turned, but capturing groups will not. if the g flag is not used, only the first complete match and its related capturing groups are re
turned. in this case, the re
turned item will have additional properties as described below. additional properties as explained above, some results contain additional properties as described below. groups an object of named capturing groups whose keys are the na...
...w. groups an object of named capturing groups whose keys are the names and values are the capturing groups or undefined if no named capturing groups were defined. see groups and ranges for more information. index the index of the search at which the result was found. input a copy of the search string. description if the regular expression does not include the g flag, str.match() will re
turn the same result as regexp.exec(). other methods if you need to know if a string matches a regular expression regexp, use regexp.test(). if you only want the first match found, you might want to use regexp.exec() instead. if you want to obtain capture groups and the global flag is set, you need to use regexp.exec() or string.prototype.matchall() instead. examples using match() in the fol...
...And 6 more matches
parseFloat() - JavaScript
the parsefloat() function parses an argument (converting it to a string first if needed) and re
turns a floating point number. 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 parsefloat(string) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. re
turn value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. description parsefloat is a top-level function and not a method of any object...
... re
turn value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. description parsefloat is a top-level function and not a method of any object. if parsefloat encounters a character other than a plus sign (+), minus sign (- u+002d hyphen-minus), numeral (0–9), decimal point (.), or exponent (e or e), it re
turns the value up to that character, ignoring the invalid character and characters following it. a second decimal point also stops parsing (characters up to that point will still be parsed). leading and trailing spaces in the argument are ignored. if the argument’s first character can’t be converted to a number (it’s not any of the above characters), parsefloat re
turns nan. parsefloat can a...
...o that character, ignoring the invalid character and characters following it. a second decimal point also stops parsing (characters up to that point will still be parsed). leading and trailing spaces in the argument are ignored. if the argument’s first character can’t be converted to a number (it’s not any of the above characters), parsefloat re
turns nan. parsefloat can also parse and re
turn infinity. ...
...And 6 more matches
Logical OR (||) - JavaScript
the logical or (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. it is typically used with boolean (logical) values. when it is, it re
turns a boolean value. however, the || operator actually re
turns the value of one of the specified operands, so if this operator is used with non-boolean values, it will re
turn a non-boolean value. 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 expr1 || expr2 description if expr1 can be converted to true, re
turns expr1; else, re
turns expr2. if a value can be converted to true, the value is so-called truth...
...a value can be converted to true, the value is so-called truthy. if a value can be converted to false, the value is so-called falsy. examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined. even though the || operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its re
turn value can always be converted to a boolean primitive. to explicitly convert its re
turn value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. short-circuit evaluation the logical or expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule: (some truthy expression)...
...ort-circuit evaluated to the truthy expression. short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). this happens because the value of the operator is already determined after the evaluation of the first operand. see example: function a(){ console.log('called a'); re
turn false; } function b(){ console.log('called b'); re
turn true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && fals...
...And 6 more matches
Modules - Archive of obsolete content
o; // => 5 // a.js: foo = 3; // b.js: foo = 5; in the above example, the value of foo depends on the order in which the subscripts are loaded: there is no way to access the property foo defined by "a.js", since it is overwritten by "b.js". ...
...each script to be loaded in the scope of their own global object, and then re
turn the global object as its result. in effect, any properties defined by the script being loaded on its global object are exported to the loading script. the script loader we obtained from components allows us to do just that: function loadscript(url) { let global = {}; loader.loadsubscript(url, global); re
turn global; } if present, the loadsubscript function evaluates the script to be loaded in the scope of the second argument. using this new version of loadscript, we can now rewrite our earlier example as follows: // index.js: let a = loadscript("www.foo.com/a.js"); let b = loadscript("www.foo.com/b.js"); a.foo // => 3 b.foo; // => 5 // a.js: foo = 3; // b.js: foo = 5; importing names in additi...
...=> 3 b.foo; // => 5 // a.js: foo = 3; // b.js: foo = 5; importing names in addition to exporting properties from the script being loaded to the loading script, we can also import properties from the loading script to the script being loaded: function loadscript(url, imports) { let global = { imports: imports, exports: {} }; loader.loadsubscript(url, global); re
turn global.exports; } among other things, this allows us to import loadscript to scripts being loaded, allowing them to load further scripts: // index.js: loadscript("www.foo.com/a.js", { loadscript: loadscript }).foo; => 5 // a.js: exports.foo = imports.loadscript("www.foo.com/b.js").bar; // b.js: exports.bar = 5; sandboxes and compartments the loadscript function as defined in the previou...
...And 5 more matches
util/array - Archive of obsolete content
helper functions for working with arrays. globals functions has(array, element) re
turns true if the given array contains the element or false otherwise. a simplified version of array.indexof(element) >= 0. let { has } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; has(a, 'rock'); // true has(a, 'rush'); // false has(a, 100); // true parameters array : array the array to search. element : * the element to search for in the array. re
turns boolean : a boolean indicating whether or not the element was found in the array. hasany(array, elements) re
turns true if the given array contains any of the elements in the elements array, or false otherwise. let { hasany } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; hasany(a, ['rock', 'bright', 'light']); // tr...
...urns true if the given array contains any of the elements in the elements array, or false otherwise. let { hasany } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; hasany(a, ['rock', 'bright', 'light']); // true hasany(a, ['rush', 'coil', 'jet']); // false parameters array : array the array to search for elements. elements : array an array of elements to search for in array. re
turns boolean : a boolean indicating whether or not any of the elements were found in the array. add(array, element) if the given array does not already contain the given element, this function adds the element to the array and re
turns true. otherwise, this function does not add the element and re
turns false. let { add } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; add(a, 'dave...
...he array and re
turns true. otherwise, this function does not add the element and re
turns false. let { add } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; add(a, 'dave'); // true add(a, 'dave'); // false add(a, 'alice'); // false console.log(a); // ['alice', 'bob', 'carol', 'dave'] parameters array : array the array to add the element to. element : * the element to add re
turns boolean : a boolean indicating whether or not the element was added to the array. remove(array, element) if the given array contains the given element, this function removes the element from the array and re
turns true. otherwise, this function does not alter the array and re
turns false. let { remove } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; remove(a, 'dave'); // fals...
...And 5 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
. note: if you're using html5's postmessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received. document.addeventlistener("message", function(e) { yourfunction(e); }, false, true); sending data from chrome to unprivileged document to "answer" the web page (e.g., re
turn code), your extension can set an attribute or attach child elements on the event target element (<myextensiondataelement/> in this example). you can optionally clean up the created element, or create it once when the web page loads then re-use it each time. another option is to send a re
turn event from the extension to the web page. this can be done using the same principle as the above example...
... { var response = json.parse(request.nodevalue); callback(response); } }, false); document.head.appendchild(request); var event = document.createevent("htmlevents"); event.initevent("something-query", true, false); request.dispatchevent(event); }, callback: function(response) { re
turn alert("response: " + (response ? response.tosource() : response)); } } </script> </head> <body> <button onclick="re
turn something.send_request({foo: 1}, something.callback)">send {foo: 1} with callback</button> <button onclick="re
turn something.send_request({baz: 3}, something.callback)">send {baz: 3} with callback</button> <button onclick="re
turn something.send_...
...</script> </head> <body> <button onclick="re
turn something.send_request({foo: 1}, something.callback)">send {foo: 1} with callback</button> <button onclick="re
turn something.send_request({baz: 3}, something.callback)">send {baz: 3} with callback</button> <button onclick="re
turn something.send_request({mozilla: 3})">send {mozilla: 3} without callback</button> <button onclick="re
turn something.send_request({firefox: 4}, something.callback)">send {firefox: 4} with callback</button> </body> </html> overlay on browser.xul in your extension: var something = { listen_request: function(callback) { // analogue of chrome.extension.onrequest.addlistener document.addeventlistener("something-query", function(event) { var node = event.target; if (!node || node.node...
...And 5 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
lockpref("mail.identity.id1.useremail", mai...
...ned above, i now get the following error message while stating thunderbird with autoconfig (autoconf.js having pref('general.config.filename','thunderbird.cfg'); ) and thunderbird.cfg calling getldap* functions to retrieve cn and mail address of the current user. netscape.cfg/autoconfig failed. please contact your system administrator. error: getldapattibutes failed: [exception... "component re
turned failure code: 0xc1f30001 (ns_error_not_initialized) [nsildapurl.spec]" nsresult: "0xc1f30001 (ns_error_not_initialized)" location: "js frame :: file:////usr/lib/thunderbird-3.0b2/defaults/autoconfig/prefcalls.js :: getldapattributes :: line 174" data: no] bug 295329 had been re-opened . autoconfig option and ldap support in thunderbird 1.5.x fortunately, autoconfig is now part of thund...
... var env_mozdebug= getenv("mozilla_debug"); if (env_mozdebug) {displayerror("no error , ...
...And 5 more matches
Supporting private browsing mode - Archive of obsolete content
-window private browsing for details. firefox 3.5 introduced private browsing mode, in which potentially private information is not recorded. this includes cookies, history information, download information, and so forth. when private browsing mode is enabled, temporary, databases are created to be used for cookies and local storage; these databases are thrown away when private browsing mode is
turned off, and the regular databases are re-activated. the temporary cookie and local storage databases start out empty. extensions that may record potentially private information may wish to hook into the private browsing service so that they can avoid saving personal information when private browsing mode is enabled. doing this is quite easy, using the nsiprivatebrowsingservice interface. detectin...
...ate browsing mode isn't active. let docroot = document.documentelement; if (docroot.hasattribute("privatebrowsingmode")) { // private browsing mode is enabled } if (docroot.getattribute("privatebrowsingmode") == "temporary") { // private browsing mode is temporary } if (docroot.getattribute("privatebrowsingmode") == "permanent") { // private browsing mode is permanent for this session }
turning private browsing on and off extensions can
turn private browsing mode on and off by manipulating the value of the privatebrowsingenabled attribute. var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var oldprivatemode = pbs.privatebrowsingmode; pbs.privatebrowsingenabled = true; /* this is all priva...
... from that point until we restore the original value of the private browsing mode setting, things are done privately. this allows us to, for example, work with the places database without affecting its contents. private browsing notifications there are notifications available that allow you to easily watch for changes to the status of the private...
...And 5 more matches
Reading from Files - Archive of obsolete content
reams. var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile(). in this case, the file 'sample.txt' within the user's home directory is retrieved. next, nsiscriptableio.newinputstream() is called to create a new input stream for reading from the file. this method will open the file and re
turn a stream. naturally, if the file does not exist, an error will occur. you may wish to use nsifile.exists() to check if the file exists before opening it. in fact, it is a good idea to enclose file reading and writing operations within a try-catch block to capture any errors that might occur during the process. see file errors for a list of errors that might occur. the newinputstream method takes ...
...further read from the file will read additional characters after the first 20. the readstring takes one argument, the number of characters to read from the file. note that this is distinct from the number of bytes to read. depending on the character encoding, it is possible that more than 20 bytes will be read from the file in order to retrieve 20 characters from the file. the readstring method re
turns the string read from the stream. usually this string have a length equal to the number of characters that were requested. however, it may not do, for instance if the end of the file was reached. this doesn't trigger an error, and the string will just be re
turned containing as many characters as are available. you can use the available method to check if data is available for reading: var file = ...
...g as many characters as are available. you can use the available method to check if data is available for reading: var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); var str = stream.readstring(stream.available()); stream.close(); in this example, the available method is called to determine the number of available bytes for reading. note that this method re
turns the number of bytes available, not the number of characters available, because the file hasn't been read and parsed yet, so the actual number of characters isn't known yet. fortunately as a character is always at least one byte long in the default utf-8 encoding, the number of characters will always be equal to or smaller than the number of bytes available. for normal file streams, the available...
...And 5 more matches
How to implement a custom XUL query processor component - Archive of obsolete content
math.random(100000).tostring(); } templateresult.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsixultemplateresult]), // private storage _data: null, // right now our results are flat lists, so no containing/recursion take place iscontainer: false, isempty: true, mayprocesschildren: false, resource: null, type: "simple-item", get id() { re
turn this._id; }, // re
turn the value of that bound variable such as ?name getbindingfor: function(avar) { // strip off the ? from the beginning of the name var name = avar.tostring().slice(1); re
turn this._data[name]; }, // re
turn an object instead of a string for convenient comparison purposes // or null to say just use string value getbindingobjectfor: function(avar) { ...
...._id; }, // re
turn the value of that bound variable such as ?name getbindingfor: function(avar) { // strip off the ? from the beginning of the name var name = avar.tostring().slice(1); re
turn this._data[name]; }, // re
turn an object instead of a string for convenient comparison purposes // or null to say just use string value getbindingobjectfor: function(avar) { re
turn null; }, // called when a rule matches this item. rulematched: function(aquery, arulenode) { }, // the output for a result has been removed and the result is no longer being used by the builder hasbeenremoved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.pro...
...s been removed and the result is no longer being used by the builder hasbeenremoved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsisimpleenumerator]), hasmoreelements: function() { re
turn this._index < this._array.length; }, getnext: function() { re
turn new templateresult(this._array[this._index++]); } }; // the query processor class - implements nsixultemplatequeryprocessor function templatequeryprocessor() { // our basic list of data this._data = [ {name: "mark", age: 36, hair: "brown", eye: "brown"}, {name: "bill", age: 25, hair:...
...And 5 more matches
XBL Example - Archive of obsolete content
getting this custom property, it will need to retrieve the value of the selectedindex attribute of the deck, which holds the number of the currently displayed page. similarly, when setting this property, it will need to change the selectedindex attribute of the deck. in addition, the text widget will need to be updated to display which page is the current one. <property name="page" onget="re
turn parseint(document.getanonymousnodes(this)[0].childnodes[0].getattribute('selectedindex'));" onset="re
turn this.setpage(val);"/> the page property gets its value by looking at the first element of the anonymous array. this re
turns the vertical box, so to get the deck, we need to get the first child node of the box. the anonymous array isn't used as the deck is not anonymous from the box. fin...
... <xul:button xbl:inherits="label=previoustext" oncommand="parentnode.parentnode.parentnode.page--;"/> <xul:description flex="1"/> <xul:button xbl:inherits="label=nexttext" oncommand="parentnode.parentnode.parentnode.page++;"/> because the 'page' property is only on the outer xul element, we need to to use the parentnode property to get to it. the first parentnode re
turns the parent of the button which is the horizontal box, the second its parent, the vertical box, and finally, its parent which is the outer box. the 'page' property is incremented or decremented. this will call the onget script to get the value, increment or decrement the value by one, and then call the onset handler to set the value. setpage method now let's define the 'setpage' method. it will...
...ter, the page number to set the page to. it will need to make sure the page is not out of range and then modify the deck's selectedindex attribute and the text widget's label attribute. <method name="setpage"> <parameter name="newidx"/> <body> <![cdata[ var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; var totalpages=this.childnodes.length; if (newidx<0) re
turn 0; if (newidx>=totalpages) re
turn totalpages; thedeck.setattribute("selectedindex",newidx); document.getanonymousnodes(this)[0].childnodes[1].childnodes[1] .setattribute("value",(newidx+1)+" of "+totalpages); re
turn newidx; ]]> </body> </method> this function is called setpage and takes one parameter newidx. the body of the method has been enclosed in...
...And 5 more matches
browser - Archive of obsolete content
ultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addprogresslistener( listener ) re
turn type: no re
turn value add a progress listener to the browser which will monitor loaded documents. the progress listener should implement the nsiwebprogresslistener interface. goback() re
turn type: no re
turn value go back one page in the history. goforward() re
turn type: no re
turn value go forward one page in the history. gohome() re
turn type: no re
turn value load the user's...
...use a positive number to go forward and a negative number to go back. ...
...use a positive number to go forward and a negative number to go back. note: this is the xul method on <browser> / <tabbrowser>, not the global function in chrome://browser/content/browser.js. ...
...And 5 more matches
panel - Archive of obsolete content
/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. re
turning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attribute determines where the popup appears relative to the element the user clicked to invoke the popup. this allows you to...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, ...
... if both x and y have the value -1 the call will realign the popup with its anchor node. openpopup( anchor , position , x , y , iscontextmenu, attributesoverride, triggerevent ) ...
...And 5 more matches
Choosing the right approach - Learn web development
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 operation repeating operation multiple sequential operations multiple simultaneous operations no yes (recursive callbacks) yes (nested callbacks) no code example an example that loads a resource ...
... 7 full support 6.1prefixed prefixed implemented with the vendor prefix: webkitsamsung internet android full support 1.5 full support 1.5 full support 1.0prefixed prefixed implemented with the vendor prefix: webkitre
turn valuechrome full support 23edge full support 12firefox full support 11ie full support 10opera full support 15safari full support ...
... and added to local db."); }).catch(function (err) { if (err.name == 'conflict') { localdb.get(element.doc._id).then(function (resp) { localdb.remove(resp._id, resp._rev).then(function (resp) { // et cetera... ...
...And 5 more matches
Introducing asynchronous JavaScript - Learn web development
ases 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 learning area modules is synchronous — you run some code, and the result is re
turned as soon as the browser can do so. let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are execut...
...ul for demonstrating a synchronous blocking operation, is terrible for use in real world applications. asynchronous javascript for reasons illustrated earlier (e.g. related to blocking), many web api features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and re
turning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to work using synchronous code? let's look at a quick example. when you fetch an image from a server, you can't re
turn the result immediately. that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob();...
...k: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to wait until the response is re
turned before it tries to do anything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code. in the below sections we'll review each of these in
turn. async callbacks async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background.
...And 5 more matches
Functions — reusable blocks of code - Learn web development
browser functions we've made use of functions built in to the browser a lot in this course. ...
... the javascrip...
...love', 'chocolate', 'frogs']; let madeastring = myarray.join(' '); console.log(madeastring); // the join() function takes an array, joins // all the array items together into a single // string, and re
turns this new string or every time we generated a random number: let mynumber = math.random(); // the random() function generates a random number between // 0 and up to but not including 1, and re
turns that number ...we were using a function! note: feel free to enter these lines into your browser's javascript console to re-familiarize yourself with their functionality, if needed. the javascript language has many built-in functions to allow you to do useful things without having to write all that code yourself. in fact, some of the code you are calling when you invoke (a fancy word for run...
...And 5 more matches
Arrays - Learn web development
and printing out the total price at the bottom. if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. this would be much longer to write out, less efficient, and more error-prone. if we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? we'll re
turn to this example later on in the article. as in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console. creating arrays arrays consist of square brackets and elements that are separated by commas. suppose we want to store a shopping list in an array. paste the following code into the console: let shopping = ['bread', 'milk',...
...another only strings. for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; let random = ['tree', 795, [0, 1, 2]]; before proceeding, create a few example arrays. accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string. enter the following into your console: shopping[0]; // re
turns "bread" you can also modify an item in an array by simply giving a single array item a new value. try this: shopping[0] = 'tahini'; shopping; // shopping will now re
turn [ "tahini", "milk", "cheese", "hummus", "noodles" ] note: we've said it before, but just as a reminder — computers start counting from 0! note that an array inside an array is called a multidimensional array. you ca...
...; try making some more modifications to your array examples before moving on. play around a bit, and see what works and what doesn't. finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. try the following: shopping.length; // should re
turn 5 this has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. so for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; for (let i = 0; i < sequence.length; i++) { console.log(sequence[i]); } you'll learn about loops properly later on (in our looping code article), but briefly, this code is saying: start looping at ite...
...And 5 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
re often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error. okay, so it's not quite that simple — there are some other differentiators as you drill down deeper. but the above classifications will do at this early stage in your career. we'll look at both of these types going forward. an erroneous example to get started, let's re
turn to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced. go to github and make yourself a local copy of number-game-errors.html (see it running live here). to get started, open the local copy inside your favorite text editor, and your browser. try playing the game — you'll notice that when you press the "submit guess" button, ...
...ector. looking further up our file, we can find the paragraph in question: <p class="loworhi"></p> so we need a class selector here, which begins with a dot (.), but the selector being passed into the queryselector() method in line 48 has no dot. this could be the problem! try changing loworhi to .loworhi in line 48. try saving and refreshing again, and your console.log() statement should re
turn the <p> element we want. phew! another error fixed! you can delete your console.log() line now, or keep it to reference later on — your choice. note: see our typeerror: "x" is (not) "y" reference page for more details about this error. syntax errors round three now if you try playing the game through again, you should get more success — the game should play through absolutely fine, un...
...just need to change addeventlistener to .addeventlistener. do this now. a logic error at this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the "random" number you've got to guess is always 1. definitely not quite how we want the game to play out! there's definitely a problem in the game logic somewhere — the game is not re
turning an error; it just isn't playing right. search for the randomnumber variable, and the lines where the random number is first set. the instance that stores the random number that we want to guess at the start of the game should be around line number 44: let randomnumber = math.floor(math.random()) + 1; and the one that generates the random number before each subsequent game is around lin...
...And 5 more matches
Routing in Ember - Learn web development
e", "completed", or "index"), will render the <todolist /> component. the location in the page where <todolist /> is rendered is determined by the {{ outlet }} inside the parent route, which in this case is application.hbs. so we have our routes in place. great! but now we need a way to differentiate between each of these routes, so that they show what they are supposed to show. ...
...ation in the page where <todolist /> is rendered is determined by the {{ outlet }} inside the parent route, which in this case is application.hbs. so we have our routes in place. great! but now we need a way to differentiate between each of these routes, so that they show what they are supposed to show. first of all, re
turn once more to our todo-data.js file. it already contains a getter that re
turns all todos, and a getter that re
turns incomplete todos. the getter we are missing is one to re
turn just the completed todos. add the following below the existing getters: get completed() { re
turn this.todos.filter(todo => todo.iscompleted); } models now we need to add models to our route javascript files to allow us to easily re
turn specific data sets to display in those models. model is a d...
... deeper. we also provide access to the service, like we did for the components. the index route model first of all, update todomvc/app/routes/index.js so it looks as follows: import route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class indexroute extends route { @service('todo-data') todos; model() { let todos = this.todos; re
turn { get alltodos() { re
turn todos.all; } } } } we can now update the todomvc/app/templates/index.hbs file so that when it includes the <todolist /> component, it does so explicitly with the available model, calling its alltodos() getter to make sure all of the todos are shown. in this file, change <todolist /> to <todolist @todos={{ @model.alltodos }}/> the completed...
...And 5 more matches
TypeScript support in Svelte - Learn web development
not a number it will complain about it: the application template has a validate script configured that runs svelte-check against your code. this package allows you to detect errors and warnings normally displayed by a code editor from the command line, which makes it pretty useful for running it in a continuous integration (ci) pipeline. just run npm run validate to check for unused css, and re
turn a11y hints and typescript compile errors. in this case, if you run npm run validate (either in the vs code console or terminal) you will get the following error: even better, if you run it from the vs code integrated terminal (you can open it with the ctrl + ` keyboard shortcut), cmd/ctrl + clicking on the file name will take you to the line containing the error. you can also run the validat...
... only the attributes of the todo that have been updated. that means it's not a complete todo — it only has a subset of a todo's properties. for these kinds of cases, typescript provides several utility types to make it easier to apply these common transformations. what we need right now is the partial<t> utility, which allows us to represent all subsets of a given type. the partial utility re
turns a new type based on the type t, where every property of t is optional. we'll use it in the update() function — update yours like so: function update(updatedtodo: partial<todotype>) { todo = { ...todo, ...updatedtodo } // applies modifications to todo dispatch('update', todo) // emit update event } with this we are telling typescript that the updatedtodo variable wi...
...remember that imports in typescript don't include the file extension. in each case it should end up like this: import { selectonfocus } from '../actions' migrating the...
...And 5 more matches
Working with Svelte stores - Learn web development
will update accordingly. then we call the method alert.subscribe(), passing it a callback function as a parameter. whenever the value of the store changes, the callback function will be called with the new value as its parameter. in the callback function we just assign the value we receive to the local variable, which will trigger the update of the component's dom. the subscribe() method also re
turns a clean-up function, which takes care of releasing the subscription. so we subscribe when the component is being initialized, and use ondestroy to unsubscribe when the component is unmounted. finally we use the alertcontent variable in our markup, and if the user clicks on the alert we clean it. at the end we include a few css lines to style our alert component. this setup allows us to work ...
...ment a store contract: the theory you can create your own stores without relying on svelte/store by implementing the store contract. its features must work like so: a store must contain a subscribe() method, which must accept as its argument a subscription function. all of a store's active subscription functions must be called whenever the store's value changes. the subscribe() method must re
turn an unsubscribe() function, which when called must stop its subscription. a store may optionally contain a set() method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. a store with a set() method is called a writable store. first of all, let's add the following console.log() statements to our app.svelt...
...itable = (initial_value = 0) => { let value = initial_value // content of the store let subs = [] // subscriber's handlers const subscribe = (handler) => { subs = [...subs, handler] // add handler to the array of subscribers handler(value) // call handler with current value re
turn () => subs = subs.filter(sub => sub !== handler) // re
turn unsubscribe function } const set = (new_value) => { if (value === new_value) re
turn // same value, exit value = new_value // update value subs.foreach(sub => sub(value)) // update subscribers } const update = (update_fn) => set(update_fn(value)) // update function re
turn {...
...And 5 more matches
gettext
for string which are supposed to support plurals. for instance, in php the default keyword for regular messages is gettext() and _(). for messages with plural support, the default keyword is ngettext(). a definition of a string with plurals takes three arguments: the singular form of the english string, the plural form of the english string, and the number basing on which the function will re
turn the correct (singular or plural) form of the string. consider the following code snippet: <?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string. notice that you need to pass the $num variable twice. first i...
...?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string. notice that you need to pass the $num variable twice. first in the ngettext() call, where it will be used to determine which form of the string will be re
turned. in the above example, $num equals 1, so the string re
turned (for english) will be %d user likes this. the second time the $num variable is passed in the printf() call, which at this point of interpretation looks something like printf("%d user likes this.", $num);. the %d in the first argument (which is the string re
turned by gettext) will be replaced with the value of $num. for english, the ab...
...ll produce the following output: 1 user likes this. the string definition in the messages.po file will look like this: #: file.php:3 #, php-format msgid "%d user likes this." msgid_plural "%d users like this." msgstr[0] "" msgstr[1] "" depending on the localizer's target language and its rules for creating plural forms, there might be another field for translation, e.g. msgstr[2]. gettext will re
turn one of the msgstrs, depending on the number passed to the gettext function in the code ($num in the above example). to determine which form to re
turn, gettext uses a plural rule, which should be declared in the po file header. for example, for english, the plural rule is of the following form: plural-forms: nplurals=2; plural=n != 1; the first part defines the number of different plural forms (2...
...And 5 more matches
GC Rooting Guide
js::mutablehandle<jsstring*> js::mutablehandlestring js::mutablehandle<jsscript*> js::mutablehandlescript js::mutablehandle<jsid> js::mutablehandleid js::mutablehandle<t> should be used for all out-parameters, for example instead of: bool maybegetvalue(jscontext *cx, js::value* valueout) { // ... ...
...context *cx, js::value* valueout) { // ... if (!waserror) *valueout = resultvalue; re
turn waserror; } void otherfunction(jscontext *cx) { js::value value; bool success = maybegetvalue(cx, &value); // ... } you should write: bool maybegetvalue(jscontext *cx, js::mutablehandlevalue valueout) { // ... if (!waserror) valueout.set(resultvalue); re
turn waserror; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ... ...
...text *cx) { js::value value; bool success = maybegetvalue(cx, &value); // ... } you should write: bool maybegetvalue(jscontext *cx, js::mutablehandlevalue valueout) { // ... if (!waserror) valueout.set(resultvalue); re
turn waserror; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ... } re
turn values it's ok to re
turn raw pointers! these do not need to be wrapped in any of rooting classes, but they should be immediately used to initialize a js::rooted<t> if there is any code that could gc before the end of the containing function; a raw pointer must never be stored on the stack during a gc. one rare but especially tricky case to watch out for is where an raii destructor could gc in ...
...And 5 more matches
JSAutoByteString
the caller must be in a request on this jscontext. str jsstring * a pointer to jsstring to get initial content by calling js_encodestring(cx, str). methods method description void initbytes(char *bytes) take ownership of the given byte array. char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the re
turned string, and re
turn the string. char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take o...
...urn the string. char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. ...
... char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the re
turned string, and re
turn the string. void clear() free the owned string. you should call this before calling encode* methods or initbytes method if a string is already owned, otherwise the string will never be freed. char *ptr() const re
turn a pointer to the owned string. this could be null if no string is owned. bool operator!() const re
turn true if no string is owned. size_t...
...And 5 more matches
Accessing the Windows Registry Using XPCOM
g values, enumerating keys, and receiving notifications access_write — for setting values and creating sub keys access_all — access for all operations in addition to open() and create(), there are the openchild() and createchild() methods. you can call these methods on an already-opened registry key to open a child key. both methods take a relative path and access mode as parameters and re
turn a new object implementing nsiwindowsregkey. here's the simple example again, but using openchild(): var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft", wrk.access_read); var subkey = wrk.openchild("windows\\currentversion", wrk...
... to make use of it. reading registry values probably the most common action associated with the windows registry is reading values. the simple example above shows how to read an existing string value. however, windows registry values can have several data types, so you need to ensure that you read the correct type. you can check the type of a value using the method getvaluetype(). this method re
turns an integer indicating the data type of the value. the data types supported by this interface are defined as named constants on the interface as follows: type_none — probably not useful type_string — a unicode string value type_binary — binary data type_int — a 32 bit integer type_int64 — a 64 bit integer each of these types (except type_none) has a corresponding method to read...
... the value data: readstringvalue() readbinaryvalue() readintvalue() readint64value() since javascript is a dynamically-typed language, you may wish to use the following code to handle all types of data. in this function, wrk is expected to be an already opened nsiwindowsregkey. function readregistryvalue(wrk, value) { switch (wrk.getvaluetype(value)) { case wrk.type_string: re
turn wrk.readstringvalue(value); case wrk.type_binary: re
turn wrk.readbinaryvalue(value); case wrk.type_int: re
turn wrk.readintvalue(value); case wrk.type_int64: re
turn wrk.readint64value(value); } // unknown type re
turn null; } writing registry values writing registry values is quite similar to reading. for each supported data type, there is a write*value() meth...
...And 5 more matches
nsAString (External)
uncate stripchars stripwhitespace trim defaultcomparator compare equals operator< operator<= operator== operator>= operator> operator!= equalsliteral lowercaseequalsliteral find rfind findchar rfindchar appendint tointeger data members no public members. methods beginreading pruint32 beginreading(const prunichar**, const prunichar**) const - source re
turns the length, beginning, and end of a string in one operation. parameters prunichar** begin prunichar** end prunichar* beginreading() const - source endreading prunichar* endreading() const - source charat prunichar charat(pruint32) const - source parameters pruint32 apos operator[] prunichar operator[](pruint32) const - source parameters pruint32 apos first prunichar ...
...unichar operator[](pruint32) const - source parameters pruint32 apos first prunichar first() const - source beginwriting pruint32 beginwriting(prunichar**, prunichar**, pruint32) - source get the length, begin writing, and optionally set the length of a string all in one operation. @param newsize size the string to this length. pass pr_uint32_max to leave the length unchanged. @re
turn the new length of the string, or 0 if resizing failed. parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty...
...onst - source parameters char* aasciistring lowercaseequalsliteral prbool lowercaseequalsliteral(const char*) const - source case-insensitive match this string to a lowercase ascii string. parameters char* aasciistring find print32 find(const nsastring&, print32 (*)(const prunichar*, const prunichar*, pruint32)) const - source find the first occurrence of astr in this string. ...
...And 5 more matches
mozIStorageConnection
rom the last sql insert operation. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. schemaversion long the schema version of the database. this should not be used until the database is ready. the version will be reported as 0 if it is not set. transactioninprogress boolean re
turns true if there is a transaction in progress on the database. otherwise re
turns false. read only. constants transaction execution time constants. constant value description transaction_deferred 0 no database lock is obtained until the first statement is run. transaction_immediate 1 a reserved lock is obtained on the database. transacti...
..., you will get a read-only clone. note: due to a bug in sqlite, if you use the shared cache (by calling mozistorageservice.opendatabase()), the cloned connection's access privileges will be the same as the original connection, regardless of the value you specify for the areadonly parameter. mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if true, the re
turned database connection is in read only mode. this is false by default. re
turn value a new mozistorageconnection object representing the cloned connection. exceptions thrown ns_error_unexpected the connection is to a memory database. close() closes a database connection. before closing the connection, you need to finalize all statements created for the connection. note: you must not cal...
...read and cannot be used to take any synchronous actions on the database. the expression may use "?#" to indicate sequentially numbered parameters (?1, ?2, etc) or ":name" to indicate named parameters. javascript callers should use named parameters. mozistorageasyncstatement createasyncstatement( in autf8string asqlstatement ); parameters asqlstatement the sql statement to execute. re
turn value re
turns a new mozistorageasyncstatement to be used to execute the specified statement. createfunction() creates a new function that can be used in sql. see mozistoragefunction for sample code and more details. if you use your connection on multiple threads, your function needs to be threadsafe, or it should only be called on one thread. void createfunction( in autf8string afunction...
...And 5 more matches
nsIContentViewer
void stop(); void unload(); obsolete since gecko 1.8 attributes attribute type description container nsisupports domdocument nsidomdocument enablerendering boolean obsolete since gecko 2.0 historyentry nsishentry get the history entry that this viewer will save itself into when destroyed. can re
turn null. read only. istabmodalpromptallowed boolean read only. prescontext nsprescontextptr read only. native code only! note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. presshell nsipresshellptr read only. native code only! note: prior to gecko...
...hide() will be called, and no further destruction will happen. destroy() void destroy(); parameters none. findcontainerview() finds the view to use as the container view for makewindow. note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. [noscript,notxpcom,nostdcall] nsiviewptr findcontainerview(); parameters none. re
turn value the container view, or null if this content viewer is the root of a view manager hierarchy. note: if this container is the root of a view manager hierarchy (that is, this method re
turns null), and mparentwidget is also null, then this document should not even be displayed. native code only!getbounds void getbounds( in nsintrectref abounds ); parameters abounds missing descript...
...hide() void hide(); parameters none. ...
...And 5 more matches
nsIDBFolderInfo
rtorder nsmsgviewsortordervalue sorttype nsmsgviewsorttypevalue version unsigned long viewflags nsmsgviewflagstypevalue viewtype nsmsgviewtypevalue methods andflags() long andflags( in long flags ); parameters flags missing description re
turn value missing description exceptions thrown missing exception missing description changeexpungedbytes() void changeexpungedbytes( in long delta ); parameters delta missing description exceptions thrown missing exception missing description changenummessages() void changenummessages( in long delta ); parameters delta missing desc...
...messages() void changenumunreadmessages( in long delta ); parameters delta missing description exceptions thrown missing exception missing description getbooleanproperty() boolean getbooleanproperty( in string propertyname, in boolean defaultvalue ); parameters propertyname missing description defaultvalue missing description re
turn value missing description exceptions thrown missing exception missing description getcharacterset() void getcharacterset( out acstring charset, out boolean overriden ); parameters charset missing description overriden missing description exceptions thrown missing exception missing description getcharactersetoverride() ...
...charactersetoverride() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void getcharactersetoverride( out boolean charactersetoverride ); parameters charactersetoverride missing description exceptions thrown missing exception missing description getcharptrcharacterset() string getcharptrcharacterset(); parameters none. ...
...And 5 more matches
nsIDOMNSHTMLDocument
read only. designmode domstring set to "on" or "off" to enable or disable editing for the entire document at once. roughly equivalent to body.contenteditable domain domstring initially the host name of the document's url, but may be changed t...
... initially the host name of the document's url, but may be changed to the parent (but not top-level) domain in order to facilitate data exchange between documents from different sites in the same domain. embeds nsidomhtmlcollection equivalent to getelementsbytagname("embed") read only. fgcolor domstring same as body.text head nsidomhtmlheadelement re
turns the first child element of the html element that is a head element, or null if there is no html or head element. read only. height long the height of the body element. read only. obsolete since gecko 6.0 linkcolor domstring same as body.link plugins nsidomhtmlcollection same as embeds for compatibility with netscape 4.x read only. vlinkcolor...
...) boolean execcommand( in domstring commandid, in boolean doshowui, in domstring value ); parameters commandid the name of the command to execute. see rich-text editing in mozilla for a list of supported commands. doshowui this is not implemented in gecko. value some commands require an argument. you can pass null for those commands that do not need an argument. re
turn value true if the command was recognized, false otherwise. execcommandshowhelp() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) this method never did anything but throw an exception, and was removed entirely in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11). boolean execcommandshowhelp( in domstring commandid ); parameters ...
...And 5 more matches
nsIFaviconService
rown ns_error_not_available thrown when we have never heard of this favicon url. getfavicondataasdataurl() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.getfavicondataforpage() instead. this method retrieves the given favicon data, re
turning it as a data url throws an exception if we don't have data. if there is no data but we have an entry for this favicon, re
turns null. astring getfavicondataasdataurl( in nsiuri afaviconuri ); parameters afaviconuri uri of the favicon whose data is being read. re
turn value a data url containing the data for the favicon. this is null if there is no data but there is an entry for the ...
...e since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.getfaviconurlforpage() instead. this method retrieves the uri of the favicon for the given page. nsiuri getfaviconforpage( in nsiuri apageuri ); parameters apageuri uri of the page whose favicon is desired. re
turn value re
turns the uri of the favicon associated with that page. re
turning a uri here does not mean that we have data for this favicon, only that we know what the favicon should be. exceptions thrown ns_error_not_available when the page is not found or it has no favicon. getfaviconimageforpage() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19)...
...ou should use the new async api moziasyncfavicons.getfaviconurlforpage() and getfaviconlinkforicon() instead. this method is very similar to that of getfaviconlinkforicon() method. for a given page will give you a uri that, when displayed in chrome, will result in the given page's favicon. unlike the other get functions, we needn't have heard of the page or its favicon: the default one will be re
turned in this case. when compared to getfaviconlinkforicon() method, this method only adds the extra level of indirection, looking up the favicon based on the page uri and using the default if not found. nsiuri getfaviconimageforpage( in nsiuri apageuri ); parameters apageuri uri of the page whose favicon is desired. re
turn value re
turns a uri that will give you the icon image. this is n...
...And 5 more matches
nsIHttpServer
(not supported) * @param function callback optional callback */ listen: function(port, opt, callback) { if (arguments.length == 2 && "function" == typeof opt) { ...
...(not supported) * @param function callback optional callback */ listen: function(port, opt, callback) { if (arguments.length == 2 && "function" == typeof opt) { callback = opt; ...
... this.registerprefixhandler("/", callback); } let host = "localhost"; if (typeof port === "string" && port.indexof(':') != -1){ [host, port] = port.split(':'); port = parseint(port); server.identity.add('http', host, port); } server.wrappedjsobject._start(port, host); re
turn true; }, registerfile: function(path, filepath) { var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(filepath); re
turn server.registerfile(path, file); }, registerdirectory : function(path, directorypath) { var...
...And 5 more matches
nsIOutputStream
the stream. forces the output stream to flush() any buffered data. note: this method may be called more than once, but subsequent calls are ignored. void close(); parameters none. exceptions thrown ns_base_stream_would_block indicates that closing the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() re
turns true. flush() this method may be called to instruct the output stream to write out the contents of any internal buffers to a low-level data sink, such as a file on disk. however, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); parameters none. exceptions thrown ns_base_stream_would_block indicates that flushing the output str...
... a low-level data sink, such as a file on disk. however, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); parameters none. exceptions thrown ns_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() re
turns 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(); para...
...ocking() 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. re
turn 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 immediately available. write() this method copies data from a buffer into the stream. note: though this method is scriptable, javascript code must only pass an ascii character string as the abuf parameter. c++ code...
...And 5 more matches
nsIPropertyBag2
note: acc...
...ng prop, in nsiidref iid, [iid_is(iid), retval] out nsqiresult result); pruint32 getpropertyasuint32(in astring prop); pruint64 getpropertyasuint64(in astring prop); prbool haskey(in astring prop); methods get() this method re
turns null if the value does not exist, or exists but is null. nsivariant get( in astring prop ); parameters prop property to re
turn the value of. re
turn value the property value as an nsivariant. getpropertyasacstring() acstring getpropertyasacstring( in astring prop ); parameters prop property to re
turn the value of. re
turn value the property value as an acstring. note: accessing a property of a different type may attempt conversion to this type. getpropertyasastring() astring getpropertyasastring( in astring...
...s an nsivariant. getpropertyasacstring() acstring getpropertyasacstring( in astring prop ); parameters prop property to re
turn the value of. re
turn value the property value as an acstring. note: accessing a property of a different type may attempt conversion to this type. getpropertyasastring() astring getpropertyasastring( in astring prop ); parameters prop property to re
turn the value of. re
turn value the property value as a string. note: accessing a property of a different type may attempt conversion to this type. getpropertyasautf8string() autf8string getpropertyasautf8string( in astring prop ); parameters prop property to re
turn the value of. re
turn value the property value as an autf8string. note: accessing a property of a different type may attempt...
...And 5 more matches
nsISelectionPrivate
ring formattype, in unsigned long flags, in print32 wrapcolumn); attributes attribute type description cancacheframeoffset boolean frame offset cache can be used just during calling nseditor::endplaceholdertransaction. endplaceholdertransaction will give rise to reflow/refreshing view/scroll, and call times of nstextframe::getpointfromoffset whose re
turn value is to be cached. see bug 35296 and bug 199412 native code only! interlineposition boolean type short re
turns the type of the selection (see nsiselectioncontroller for available constants). read only. constants constant value description endofprecedingline 0 startofnextline 1 tableselection...
...bleselection_table 4 tableselection_allcells 5 methods addselectionlistener() void addselectionlistener( in nsiselectionlistener newlistener ); parameters newlistener endbatchchanges() will resume user interface updates after a previous call to startbatchchanges(). void endbatchchanges(); parameters none. ...
...vious call to startbatchchanges(). void endbatchchanges(); parameters none. native code only!getcachedframeoffset re
turns cached value for nstextframe::getpointfromoffset. void getcachedframeoffset( in nsiframe aframe, in print32 inoffset, in nspointref apoint ); parameters aframe inoffset apoint getenumerator() nsienumerator getenumerator(); parameters none. re
turn value native code only!getframeselection nsframeselection getframeselection(); parameters none. re
turn value a reference to the frame selection associated with this selection. getrangesforinterval() re
turn array of ranges intersecting with the given dom interval. void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 end...
...And 5 more matches
nsITransferable
ce the destination directory for a file drag is known. methods adddataflavor() adds a new data flavor, indicating that this transferable can receive the type of data represented by the specified flavor string. void adddataflavor( in string adataflavor ); parameters adataflavor a string defining a new data flavor that the transferable supports. ...
...dataflavor( in string adataflavor ); parameters adataflavor a string defining a new data flavor that the transferable supports. flavorstransferablecanexport() re
turns a list of flavors (mime types as nsisupportscstring) that the transferable can export, either through intrinsic knowledge or output data converters. nsisupportsarray flavorstransferablecanexport(); parameters none. re
turn value missing description flavorstransferablecanimport() computes a list of flavors (mime types as nsisupportscstring) that the transferable can accept into it, either through intrinsic knowledge or input data converters. ...
...output data converters. nsisupportsarray flavorstransferablecanexport(); parameters none. re
turn value missing description flavorstransferablecanimport() computes a list of flavors (mime types as nsisupportscstring) that the transferable can accept into it, either through intrinsic knowledge or input data converters. nsisupportsarray flavorstransferablecanimport(); parameters none. re
turn value missing description getanytransferdata() re
turns the best flavor in the transferable, given those that have been added to it with adddataflavor(). ...
...And 5 more matches
nsIURL
or something to be a definitely be a file. but you can get just the leading directory portion for sure. some characters may be escaped. filebasename autf8string file basename portion of a filename in a url. some characters may be escaped. fileextension autf8string file extension portion of a filename in a url. if a file extension does not exist, the empty string is re
turned. some characters may be escaped. filename autf8string file name portion of a url. if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the complete /foo/bar/ portion, and the filename is the empty string. note that this is purely based on searching for the last trailing slash. and hence don't rely on this...
... ; in the url. some characters may be escaped. obsolete since gecko 9.0 note: this was removed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) because the semicolon is not actually valid for this purpose and should not have been specially handled. query autf8string query portion (the part after the "?") of the url. if there isn't one, an empty string is re
turned. some characters may be escaped. ref autf8string reference portion (the part after the "#") of the url. if there isn't one, an empty string is re
turned. some characters may be escaped. methods getcommonbasespec() this method takes a uri and compares the two. the common uri portion is re
turned as a string. the minimum common uri portion is the protocol, and any of these if p...
...for file uris, it is expected that the common spec would be at least "file:///" since '/' is a shared common root. ...
...And 5 more matches
nsIAbCard/Thunderbird3
ismaillist boolean if ismaillist is true then maillisturi will contain the uri of the associated mail list. this will be removed from the interface at a later date. maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mail list. this will be removed from the interface at a later date. methods getproperty() re
turns a property for the given name. nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); parameters name the case-sensitive name of the property to get. defaultvalue the value to re
turn if the property does not exist. re
turn value the value of the attribute asked for. exceptions thrown ns_error_not_available<tt> if the named property does not exist. <tt>ns_er...
...ta if the property cannot be converted to the desired type. getpropertyasastring() getpropertyasautf8string() getpropertyasuint32() getpropertyasbool() [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscript] pruint32 getpropertyasuint32(in string name); [noscript] boolean getpropertyasbool(in string name); re
turns a property for the given name. these functions convert values in the same manner as the default implementation of nsivariant. of particular note is that boolean variables are converted to integers as in c/c++ (true is a non-zero value), so that false will be converted to a string of 0 and not false<code>. these functions are marked <code>[noscript] since xpcconnect performs automatic type conv...
...ean variables are converted to integers as in c/c++ (true is a non-zero value), so that false will be converted to a string of 0 and not false<code>. these functions are marked <code>[noscript] since xpcconnect performs automatic type conversion on nsivariant such that they are not needed for scripts, only for c++ callers. parameters name the case-sensitive name of the property to get. re
turn value the value of the attribute asked for. exceptions thrown ns_error_not_available<tt> if the named property does not exist. <tt>ns_error_cannot_convert_data if the property cannot be converted to the desired type. [noscript] astring getpropertyasastring(in string name); [noscript] autf8string getpropertyasautf8string(in string name); [noscript] pruint32 getpropertyasuint32(in s...
...And 5 more matches
Address Book examples
"] .getservice(components.interfaces.nsiabmanager); let oneaddressbook = abmanager.getdirectory(addressbookuri); how do i search for a particular contact property (name, email)? once you have an object that implements nsiabcollection (see above), you can search for cards with particular properties within that collection using getcardfromproperty. ...
... let collection = ... let card = collection.cardforemailaddress("foo@bar.invalid.com"); note: both of these functions may raise an ns_error_not_implemented exception if the collection has not implemented that function. this is currently true in the case of ldap, but may be true in other cases as well. ...
...database specific information, that is used on edits. editing contacts once you have obtained a card from an nsiabdirectory (see above), you can edit it in a two step process, firstly, change the properties that you to edit: card.setproperty("firstname", "jane"); card.setproperty("lastname", "doe"); seco...
...And 5 more matches
Declaring and Using Callbacks
. warning: callbacks must be invoked on the same thread with which they were registered. there is no concurrency logic in js-ctypes, so invoking callbacks on other threads will cause things to crash. prerequiste understanding abi functiontype declaring callbacks a callback is declared by using ctypes.functiontype. the first argument is the calling convention, the second argument is the re
turn type, and the third is an array of arguments the callback expects. the re
turn type of the javascript callback must match the re
turn type declared, otherwise js-ctypes will throw an error saying "unexpected re
turn type". examples example 1 this callback that re
turns bool and has two arguments. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes...
...k expects. the re
turn type of the javascript callback must match the re
turn type declared, otherwise js-ctypes will throw an error saying "unexpected re
turn type". examples example 1 this callback that re
turns bool and has two arguments. var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { re
turn true; // as the re
turn of the functiontype was ctypes.bool we must make our javascript callback re
turn bool otherwise js-ctypes will throw error saying unexpected type re
turn } var myccallback = myfunctypedeclaration.ptr(myjscallback); example 2 this callback that re
turns void and no arguments. ...
...[ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { re
turn true; // as the re
turn of the functiontype was ctypes.bool we must make our javascript callback re
turn bool otherwise js-ctypes will throw error saying unexpected type re
turn } var myccallback = myfunctypedeclaration.ptr(myjscallback); example 2 this callback that re
turns void and no arguments. when void is the re
turn type, the javascript callback must not re
turn, or it should re
turn undefined. ...
...And 5 more matches
Standard OS Libraries
ows apis can be found at the msdn api index. winapi this is the one that is most commonly used by js-ctypes. this comes shipped by default with all installations of windows operating systems since win98. it's also known as winapi32 or just winapi. a list of all the functions available through this api can be found at the msdn winapi index. for finding out the values and types of arguments and re
turns of the functions you want to use from this api, you must visit the functions page on this linked msdn site; it will give you all that information. example: getcursorpos i wanted to get the mouse cursor position without using a mousemove listener, as this is a high overhead event listener. so i went to the msdn winapi index page and then went to the "cursors" category and came across getcursorp...
.../ types var gint = ctypes.int; var gdkdevice = ctypes.structtype('gdkdevice'); var gdkmodifiertype = ctypes.int; var gdkwindow = ctypes.structtype('gdkwindow'); var void = ctypes.void_t; // https://developer.gnome.org/gdk3/stable/gdk3-windows.html#gdk-get-default-root-window var gdk_get_default_root_window = gdk.declare('gdk_get_default_root_window', ctypes.default_abi, gdkwindow.ptr // re
turn - the root window, which is top most parent of all windows ); // in gdk2 we have to use gdk_window_get_pointer, but in gdk3 it was deprecated and have to use gdk_window_get_device_position https://developer.gnome.org/gdk3/stable/gdk3-windows.html#gdk-window-get-pointer var gdk_window_get_pointer = gdk.declare('gdk_window_get_pointer', ctypes.default_abi, gdkwindow.ptr, // re
turn - the...
...devicemanager = ctypes.structtype('gdkdevicemanager'); var gdkdisplay = ctypes.structtype('gdkdisplay'); var gdkmodifiertype = ctypes.int; var gdkwindow = ctypes.structtype('gdkwindow'); // https://developer.gnome.org/gdk3/stable/gdk3-windows.html#gdk-get-default-root-window var gdk_get_default_root_window = gdk.declare('gdk_get_default_root_window', ctypes.default_abi, gdkwindow.ptr // re
turn - the root window, which is top most parent of all windows ); // in gdk2 we have to use gdk_window_get_pointer, but in gdk3 it was deprecated and have to use gdk_window_get_device_position // https://developer.gnome.org/gdk3/stable/gdk3-windows.html#gdk-window-get-device-position var gdk_window_get_device_position = gdk3.declare('gdk_window_get_device_position', ctypes.default_abi, gdkwindow...
...And 5 more matches
CData
n constructor ctype the data type of the cdata object, as a ctype. read only. note: this is never ctypes.void_t or an array type with an unspecified length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. ...
...eerror exception if the value can't be converted. methods available on all cdata objects address() re
turns a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object. this provides a way to get a pointer to the actual data of the c value represented by the cdata object. cdata address() parameters none. re
turn value a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object. ...
...pe(dataobject.constructor) whose value points to the c object referred to by the object. this provides a way to get a pointer to the actual data of the c value represented by the cdata object. cdata address() parameters none. re
turn value a cdata object of the pointer type ctypes.pointertype(dataobject.constructor) whose value points to the c object referred to by the object. tosource() re
turns the string "t(arg)", where t and arg are implementation-defined javascript expressions intended to represent the type of the cdata object and its value, respectively. string tosource() parameters none. re
turn value a string that, ideally, should be able to be evaluated to produce a new cdata object containing a copy of the original object. however, this only works if the object's type happ...
...And 5 more matches
All keyboard shortcuts - Firefox Developer Tools
ve to first node in the tree. home home home move to last node in the tree. end end end expand currently selected node right arrow right arrow right arrow collapse currently selected node left arrow left arrow left arrow (when a node is selected) move inside the node so you can start stepping through attributes. ...
...eft arrow (when a node is selected) move inside the node so you can start stepping through attributes. ...
...ributes of a node shift + tab shift + tab shift + tab (when an attribute is selected) start editing the attribute enter re
turn enter hide/show the selected node h h h focus on the search box in the html pane ctrl + f cmd + f ctrl + f edit as html f2 f2 f2 stop editing html f2 / ctrl +enter f2 / cmd + re
turn f2 / ctrl + enter copy the selected node's outer html ctrl + c cmd + c ctrl + c scroll the selected node into view s s s find the next match in the markup, when searching is active enter re
turn enter find the previous match in the markup, when searching is active shift + enter shift + re
turn shift + enter breadcrumb...
...And 5 more matches
Attr - Web APIs
the attr interface represents one of a dom element's attributes as an object. in most dom methods, you will directly retrieve the attribute as a string (e.g., element.getattribute()), but certain functions (e.g., element.getattributenode()) or means of iterating re
turn attr types. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco...
...read only a domstring representing the namespace prefix of the attribute, or null if no prefix is specified. ownerelement read only the element holding the attribute. note: dom level 4 removed this property. the assumption was that since you get an attr object from an element, you should already know the associated element. ...
... value the attribute's value. note: dom level 3 defined namespaceuri, localname and prefix on the node interface. ...
...And 5 more matches
CSS Typed Object Model API - Web APIs
of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. cssstylevalue.parse(property, csstext) the parse() method of the cssstylevalue interface allows a cssnumericvalue to be constructed from a css string. it sets a specific css property to the specified values and re
turns the first value as a cssstylevalue object. cssstylevalue.parseall() the parseall() method of the cssstylevalue interface sets all occurences of a specific css property to the specified valueand re
turns an array of cssstylevalue objects, each containing one of the supplied values. stylepropertymap the stylepropertymap interface of the the css typed object model api provides a representation...
...arsedvalue the cssunparsedvalue interface of the css typed object model api represents property values that reference custom properties. it consists of a list of string fragments and variable references. cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties. ...
... csskeywordvalue serialization the csskeywordvalue interface of the the css typed object model api creates an object to represent css keywords and other identifiers. ...
...And 5 more matches
DOMMatrix - Web APIs
the dommatrix interface represents 4×4 matrices, suitable for 2d and 3d operations including rotation and translation. it is a mutable version of the dommatrixreadonly interface. this interface should be available inside web workers, though some implementations don't allow it yet. constructor dommatrix() creates and re
turns a new dommatrix object. properties this interface inherits properties from dommatrixreadonly, though some of these properties are altered to be mutable. is2d read only a boolean flag whose value is true if the matrix was initialized as a 2d matrix. if false, the matrix is 3d. isidentity read only a boolean whose value is true if the matrix is the identity matrix. the identity matrix is one in which every value is 0 except those on the main diagonal from t...
... a m11 b m12 c m21 d m22 e m41 f m42 methods this interface includes the following methods, as well as the methods it inherits from dommatrixreadonly. dommatrix.invertself() modifies the matrix by inverting it. if the matrix can't be inverted, its components are all set to nan, and is2d re
turns false. dommatrix.multiplyself() modifies the matrix by post-multiplying it with the specified dommatrix. this is equivalent to the dot product a⋅b, where matrix a is the source matrix and b is the matrix given as an input to the method. re
turns itself. dommatrix.premultiplyself() modifies the matrix by pre-multiplying it with the specified dommatrix. this is equivalent to the dot product b...
... dommatrix. this is equivalent to the dot product a⋅b, where matrix a is the source matrix and b is the matrix given as an input to the method. re
turns itself. dommatrix.premultiplyself() modifies the matrix by pre-multiplying it with the specified dommatrix. this is equivalent to the dot product b⋅a, where matrix a is the source matrix and b is the matrix given as an input to the method. re
turns itself. dommatrix.translateself() modifies the matrix by applying the specified vector. the default vector is [0, 0, 0]. re
turns itself. dommatrix.scalenonuniformself() modifies the matrix by applying the specified scaling on the x, y, and z axes, centered at the given origin. by default, the y and z axes' scaling factors are both 1, but the scaling factor for x must be specified. the defa...
...And 5 more matches
Headers - Web APIs
rs.entries()). note: you can find more out about the available headers by reading our http headers reference. constructor headers() creates a new headers object. methods headers.append() appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist. headers.delete() deletes a header from a headers object. ...
...headers.append() appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist. headers.delete() deletes a header from a headers object. headers.entries() re
turns an iterator allowing to go through all key/value pairs contained in this object. headers.foreach() executes a provided function once for each array element. headers.get() re
turns a bytestring sequence of all the values of a header within a headers object with a given name. headers.has() re
turns a boolean stating whether a headers object contains a certain header. headers.keys() re
turns an iterator allowing you to go through all keys of the key/value pairs contained in this object. headers.set() sets a new value for an existing header inside a headers object, or add...
...eaders object with a given name. headers.has() re
turns a boolean stating whether a headers object contains a certain header. headers.keys() re
turns an iterator allowing you to go through all keys of the key/value pairs contained in this object. headers.set() sets a new value for an existing header inside a headers object, or adds the header if it does not already exist. headers.values() re
turns an iterator allowing you to go through all values of the key/value pairs contained in this object. note: to be clear, the difference between headers.set() and headers.append() is that if the specified header does already exist and does accept multiple values, headers.set() will overwrite the existing value with the new one, whereas headers.append() will append the new value onto the end of th...
...And 5 more matches
IDBIndex - Web APIs
x can point to only one record in its referenced object store, but several indexes can reference the same object store. when the object store changes, all indexes that refers to the object store are automatically updated. you can grab a set of keys within a range. to learn more, see idbkeyrange. note: this feature is available in web workers. properties idbindex.isautolocale read only re
turns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) idbindex.locale read only re
turns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) idbindex.name the name of this index. idbindex.objectstore read only the...
...nly affects how the index behaves when the result of evaluating the index's key path yields an array. if true, there is one record in the index for each item in an array of keys. if false, then there is one record for each key that is an array. idbindex.unique read only if true, this index does not allow duplicate values for a key. ...
...valuating the index's key path yields an array. if true, there is one record in the index for each item in an array of keys. if false, then there is one record for each key that is an array. idbindex.unique read only if true, this index does not allow duplicate values for a key. methods inherits from: eventtarget idbindex.count() re
turns an idbrequest object, and in a separate thread, re
turns the number of records within a key range. ...
...And 5 more matches
IDBObjectStore - Web APIs
ect store. if this attribute is null, the application must provide a key for each modification operation. idbobjectstore.name the name of this object store. idbobjectstore.transaction read only the idbtransaction object to which this object store belongs. idbobjectstore.autoincrement read only the value of the auto increment flag for this object store. methods idbobjectstore.add() re
turns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. idbobjectstore.clear() creates and immediately re
turns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectsto...
...t object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. idbobjectstore.clear() creates and immediately re
turns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectstore.count() re
turns an idbrequest object, and, in a separate thread, re
turns the total number of records that match the provided key or idbkeyrange. ...
... store. idbobjectstore.clear() creates and immediately re
turns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectstore.count() re
turns an idbrequest object, and, in a separate thread, re
turns the total number of records that match the provided key or idbkeyrange. if no arguments are provided, it re
turns the total number of records in the store. idbobjectstore.createindex() creates a new index during a version upgrade, re
turning a new idbindex object in the connected database. idbobjectstore.delete() re
turns an idbrequest object, and, in a separate thread, deletes the store object selected by the specified key. this is for deleting individual records out of an object store. idbobjectstore.d...
...And 5 more matches
Recording a media element - Web APIs
in this article, we'll look at an example that does just that. html content <p>click the "start" button to begin video recording for a few seconds. you can stop the video by clicking the creatively-named "stop" button. ...
...); this specifies the length of the videos we'll record. utility functions next, we create some utility functions that will get used later. function log(msg) { logelement.innerhtml += msg + "\n"; } the log() function is used to output text strings to a <div> so we can share information with the user. not very pretty but it gets the job done for our purposes. function wait(delayinms) { re
turn new promise(resolve => settimeout(resolve, delayinms)); } the wait() function re
turns a new promise which resolves once the specified number of milliseconds have elapsed. it works by using an arrow function which calls window.settimeout(), specifying the promise's resolution handler as the timeout handler function. that lets us use promise syntax when using timeouts, which can be very handy whe...
...we always record no more than the specified number of milliseconds of media, although if the media stops before that time is reached, mediarecorder automatically stops recording as well. line 2 ...
...And 5 more matches
TreeWalker - Web APIs
the treewalker object represents the nodes of a document subtree and a position within them. a treewalker can be created using the document.createtreewalker() method. properties this interface doesn't inherit any property. treewalker.root read only re
turns a node representing the root node as specified when the treewalker was created. treewalker.whattoshow read only re
turns an unsigned long being a bitmask made of constants describing the types of node that must be presented. non-matching nodes are skipped, but their children may be included, if relevant. the possible values are: constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. nodefilter.show_a...
...ase, it means that the notation node will appear in the first position of the traversal. since entities are not part of the document tree, they do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. treewalker.filter read only re
turns a nodefilter used to select the relevant nodes. treewalker.expandentityreferences read only is a boolean indicating, when discarding an entityreference its whole sub-tree must be discarded at the same time. treewalker.currentnode is the node on which the treewalker is currently pointing at. methods this interface doesn't inherit any method. note: in the context of a treewalker, a node...
...ointing at. methods this interface doesn't inherit any method. note: in the context of a treewalker, a node is visible if it exists in the logical view determined by the whattoshow and filter parameter arguments. (whether or not the node is visible on the screen is irrelevant.) treewalker.parentnode() moves the current node to the first visible ancestor node in the document order, and re
turns the found node. it also moves the current node to this one. if no such node exists, or if it is before that the root node defined at the object construction, re
turns null and the current node is not changed. treewalker.firstchild() moves the current node to the first visible child of the current node, and re
turns the found child. it also moves the current node to this child. if no such child e...
...And 5 more matches
A basic 2D WebGL animation example - Web APIs
en the final position is computed by multiplying the rotated position by the scaling vector provided by the javascript code in uscalingfactor. the values of z and w are fixed at 0.0 and 1.0, respectively, since we're drawing in 2d. the standard webgl global gl_position is then set to the transformed and rotated vertex's position. fragment shader next comes the fragment shader. its role is to re
turn the color of each pixel in the shape being rendered. since we're drawing a solid, untextured object with no lighting applied, this is exceptionally simple: <script id="fragment-shader" type="x-shader/x-fragment"> #ifdef gl_es precision highp float; #endif uniform vec4 uglobalcolor; void main() { gl_fragcolor = uglobalcolor; } </script> this starts by specifying the precision...
...ed to let us add multiple shaders to our program quite easily. the array shaderset contains a list of objects, each describing one shader function to be compiled into the program. each function has a type (one of gl.vertex_shader or gl.fragment_shader) and an id (the id of the <script> element containing the shader's code). the shader set is passed into the function buildshaderprogram(), which re
turns the compiled and linked shader program. we'll look at how this works next. once the shader program is built, we compute the aspect ratio of our context by dividing its width by its height. then we set the current rotation vector for the animation to [0, 1], and the scaling vector to [1.0, aspectratio]. the scaling vector, as we saw in the vertex shader, is used to scale the coordinates to fit ...
...typically 60 fps) is set to 6. finally, animatescene() is called to render the first frame and schedule the rendering of the next frame of the animation. compiling and linking the shader program constructing and linking the program the buildshaderprogram() function accepts as input an array of objects describing a set of shader functions to be compiled and linked into the shader program and re
turns the shader program after it's been built and linked. function buildshaderprogram(shaderinfo) { let program = gl.createprogram(); shaderinfo.foreach(function(desc) { let shader = compileshader(desc.id, desc.type); if (shader) { gl.attachshader(program, shader); } }); gl.linkprogram(program) if (!gl.getprogramparameter(program, gl.link_status)) { console.log("e...
...And 5 more matches
Adding 2D content to a WebGL context - Web APIs
o transform the input vertex from its original coordinate system into the clip space coordinate system used by webgl, in which each axis has a range from -1.0 to 1.0, regardless of aspect ratio, actual size, or any other factors. the vertex shader must perform the needed transforms on the vertex's position, make any other adjustments or calculations it needs to make on a per-vertex basis, then re
turn the transformed vertex by saving it in a special variable provided by glsl, called gl_position. the vertex shader can, as needed, also do things like determine the coordinates within the face's texture of the texel to apply to the vertex, apply the normals to determine the lighting factor to apply to the vertex, and so on. this information can then be stored in varyings or attributes as appropri...
...the fragment shader is called once for every pixel on each shape to be drawn, after the shape's vertices have been processed by the vertex shader. its job is to determine the color of that pixel by figuring out which texel (that is, the pixel from within the shape's texture) to apply to the pixel, getting that texel's color, then applying the appropriate lighting to the color. the color is then re
turned to the webgl layer by storing it in the special variable gl_fragcolor. that color is then drawn to the screen in the correct position for the shape's corresponding pixel. in this case, we're simply re
turning white every time, since we're just drawing a white square, with no lighting in use. const fssource = ` void main() { gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0); } `; init...
...// function loadshader(gl, type, source) { const shader = gl.createshader(type); // send the source to the shader object gl.shadersource(shader, source); // compile the shader program gl.compileshader(shader); // see if it compiled successfully if (!gl.getshad...
...And 5 more matches
WebGL best practices - Web APIs
page tackles recommendations across the spectrum of expertise, and not only highlights dos and don'ts, but also details why. you can rely on this document to guide your choice of approach, and ensure you're on the right track no matter what browser or hardware your users run. general topics address and eliminate webgl errors your application should run without generating any webgl errors (as re
turned by geterror). every webgl error is reported in the web console as a javascript warning with a descriptive message. after too many errors (32 in firefox), webgl stops generating descriptive messages, which really hinders debugging. the only errors a well-formed page generates are out_of_memory and context_lost. know your limits (and extensions) the availability of most webgl extensions depend...
... in the rendered output. however, lod meshes is usually the answer to this problem, rarely moving work from the vertex to the fragment shader. compile shaders and link programs in parallel it's tempting to compile shaders and link programs serially, but many browsers can compile and link in parallel on background threads. ...
...ams) { compileonce(gl, vs); compileonce(gl, fs); gl.linkprogram(prog); if (!gl.getprogramparameter(prog, gl.link_status)) { console.error('link failed: ' + gl.getprograminfolog(prog)); console.error('vs info-log: ' + gl.getshaderinfolog(vs)); console.error('fs info-log: ' + gl.getshaderinfolog(fs)); } } consider: function compileonce(gl, shader) { if (shader.compiled) re
turn; gl.compileshader(shader); shader.compiled = true; } for (const [vs, fs, prog] of programs) { compileonce(gl, vs); compileonce(gl, fs); } for (const [vs, fs, prog] of programs) { gl.linkprogram(prog); } for (const [vs, fs, prog] of programs) { if (!gl.getprogramparameter(prog, gl.link_status)) { console.error('link failed: ' + gl.getprograminfolog(prog)); console.error('vs inf...
...And 5 more matches
WebGL model view projection - Web APIs
bute vec3 position; void main() { // the gl_position is the final position in clip space after the vertex shader modifies it gl_position = vec4(position, 1.0); } next, to actually rasterize the data into pixels, the fragment shader evaluates everything on a per pixel basis, setting a single color. the gpu calls the shader function for each pixel it needs to render; the shader's job is to re
turn the color to use for that pixel. precision mediump float; uniform vec4 color; void main() { gl_fragcolor = color; } with those settings included, it's time to directly draw to the screen using clip space coordinates. var box = new webglbox(); first draw a red box in the middle. box.draw({ top : 0.5, // x bottom : -0.5, // x left : -0.5, // y ...
...ribute to the shader. this is a three dimensional point, but the gl_position variable that ends up getting passed down through the pipeline is actually 4 dimensional — instead of (x, y, z) it is (x, y, z, w). there is no letter after z, so by convention this fourth dimension is labeled w. in the above example the w coordinate is set to 1.0. the obvious question is "why the extra dimension?" it
turns out that this addition allows for lots of nice techniques for manipulating 3d data. this added dimension introduces the notion of perspective into the coordinate system; with it in place, we can map 3d coordinates into 2d space—thereby allowing two parallel lines to intersect as they recede into the distance. the value of w is used as a divisor for the other components of the coordinate, so th...
...nsional point is defined in a typical cartesian coordinate system. the added fourth dimension changes this point into a homogeneous coordinate. it still represents a point in 3d space and it can easily be demonstrated how to construct this type of coordinate through a pair of simple functions. function cartesiantohomogeneous(point) let x = point[0]; let y = point[1]; let z = point[2]; re
turn [x, y, z, 1]; } function homogeneoustocartesian(point) { let x = point[0]; let y = point[1]; let z = point[2]; let w = point[3]; re
turn [x/w, y/w, z/w]; } as previously mentioned and shown in the functions above, the w component divides the x, y, and z components. when the w component is a non-zero real number then homogeneous coordinate easily translates back into a normal point in...
...And 5 more matches
Window.getComputedStyle() - Web APIs
the window.getcomputedstyle() method re
turns an object containing the values of all css properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. individual css property values are accessed through apis provided by the object, or by indexing with css property names. syntax var style = window.getcomputedstyle(element [, pseudoelt]); element the element for which to get the computed style. pseudoeltoptional a string specifying the pseudo-element to match. omitted (or null) for real elements. the re
turned style is a live cssstyledeclaration object, which updates automatically when the element's styles are changed. throws typeerror if the passed object is not an element or the pseudoelt is not a valid pseudo-element se...
...however, the two objects have different purposes: the object from getcomputedstyle is read-only, and should be used to inspect the element's style — including those set by a <style> element or an external stylesheet. the element.style object should be used to set styles on that element, o...
...e; } javascript let para = document.queryselector('p'); let compstyles = window.getcomputedstyle(para); para.textcontent = 'my computed font-size is ' + compstyles.getpropertyvalue('font-size') + ',\nand my computed line-height is ' + compstyles.getpropertyvalue('line-height') + '.'; result description the re
turned object is the same cssstyledeclaration type as the object re
turned from the element's style property. however, the two objects have different purposes: the object from getcomputedstyle is read-only, and should be used to inspect the element's style — including those set by a <style> element or an external stylesheet. the element.style object should be used to set styles on that element, or inspect styles directly added to it from javascript manipulation ...
...And 5 more matches
Index - HTTP
ence, so that it allows a user to differentiate according to the users' own preferred language. 25 content-length http, headers, reference the content-length entity header indicates the size of the entity-body, in bytes, sent to the recipient. 26 content-location http, reference, header the content-location header indicates an alternate location for the re
turned data. the principal use is to indicate the url of a resource transmitted as the result of content negotiation. 27 content-range http, http header, reference, response header, header the content-range response http header indicates where in a full body message a partial message belongs. 28 content-security-policy csp, http, reference, security, header th...
...n frame, and in iframes that it embeds. 64 feature-policy: autoplay directive, feature policy, feature-policy, http, reference, autoplay the http feature-policy header autoplay directive controls whether the current document is allowed to autoplay media requested through the htmlmediaelement interface. when this policy is enabled and there were no user gestures, the promise re
turned by htmlmediaelement.play() will reject with a domexception. the autoplay attribute on <audio> and <video> elements will be ignored. 65 feature-policy: camera directive, feature policy, feature-policy, http, reference, camera the http feature-policy header camera directive controls whether the current document is allowed to use video input devices. when this policy is enable...
...ement.play() will reject with a domexception. the autoplay attribute on <audio> and <video> elements will be ignored. 65 feature-policy: camera directive, feature policy, feature-policy, http, reference, camera the http feature-policy header camera directive controls whether the current document is allowed to use video input devices. ...
...And 5 more matches
Grammar and types - JavaScript
et y = 5; } console.log(y); // referenceerror: y is not defined variable hoisting another unusual thing about variables in javascript is that you can refer to a variable declared later, without getting an exception. this concept is known as hoisting. variables in javascript are, in a sense, "hoisted" (or "lifted") to the top of the function or statement. ...
...iables in javascript is that you can refer to a variable declared later, without getting an exception. this concept is known as hoisting. variables in javascript are, in a sense, "hoisted" (or "lifted") to the top of the function or statement. however, variables that are hoisted re
turn a value of undefined. so even if you declare and initialize after you use or refer to this variable, it still re
turns undefined. ...
...known as hoisting. variables in javascript are, in a sense, "hoisted" (or "lifted") to the top of the function or statement. however, variables that are hoisted re
turn a value of undefined. so even if you declare and initialize after you use or refer to this variable, it still re
turns undefined. ...
...And 5 more matches
Text formatting - JavaScript
rogate halves separately to achieve the same result. see also string.fromcodepoint() or string.prototype.codepointat(). '\u{2f804}' // the same with simple unicode escapes '\ud87e\udc04' string objects the string object is a wrapper around the string primitive data type. const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // re
turns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object. you can also use the string.length property with a string literal. you should use string literals unless you specifically need to use a string object, because st...
...ary string object. you can also use the string.length property with a string literal. you should use string literals unless you specifically need to use a string object, because string objects can have counterintuitive behavior. for example: const firststring = '2 + 2'; // creates a string literal value const secondstring = new string('2 + 2'); // creates a string object eval(firststring); // re
turns the number 4 eval(secondstring); // re
turns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string. for example, the following code assigns hellolength the value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit. you can access each code unit using an array bracket style. you can't change in...
... value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit. you can access each code unit using an array bracket style. you can't change individual characters because strings are immutable array-like objects: const hello = 'hello, world!'; const hellolength = hello.length; hello[0] = 'l'; // this has no effect, because strings are immutable hello[0]; // this re
turns "h" characters whose unicode scalar values are greater than u+ffff (such as some rare chinese/japanese/korean/vietnamese characters and some emoji) are stored in utf-16 with two surrogate code units each. for example, a string containing the single character u+1f600 "emoji grinning face" will have length 2. accessing the individual code units in such a string using brackets may have undesirabl...
...And 5 more matches
Public class fields - JavaScript
elow. both static and instance public fields are writable, enumerable, and configurable properties. as such, unlike their private counterparts, they participate in prototype inheritance. syntax class classwithinstancefield { instancefield = 'instance field' } class classwithstaticfield { static staticfield = 'static field' } class classwithpublicinstancemethod { publicmethod() { re
turn 'hello world' } } examples public static fields public static fields are useful when you want a field to exist only once per class, not on every class instance you create. this is useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. public static fields are declared using the static keyword. they are added to the class constructor at t...
...lasswithstaticfield.basestaticfield) // expected output: "base field" when initializing fields, this refers to the class constructor. you can also reference it by name, and use super to get the superclass constructor (if one exists). ...
...ethod output" public instance fields public instance fields exist on every created instance of a class. by declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. public instance fields are added with object.defineproperty() either at construction time in the base class (before the constructor body runs), or just after super() re
turns in a subclass. class classwithinstancefield { instancefield = 'instance field' } const instance = new classwithinstancefield() console.log(instance.instancefield) // expected output: "instance field" fields without initializers are initialized to undefined. class classwithinstancefield { instancefield } const instance = new classwithinstancefield() console.assert(instance.hasownproperty...
...And 5 more matches
Classes - JavaScript
e "constructor" in a class. a syntaxerror will be thrown if the class contains more than one occurrence of a constructor method. a constructor can use the super keyword to call the constructor of the super class. prototype methods see also method definitions. class rectangle { constructor(height, width) { this.height = height; this.width = width; } // getter get area() { re
turn this.calcarea(); } // method calcarea() { re
turn this.height * this.width; } } const square = new rectangle(10, 10); console.log(square.area); // 100 static methods the static keyword defines a static method for a class. static methods are called without instantiating their class and cannot be called through a class instance. static methods are often used to create utility functio...
...the static keyword defines a static method for a class. static methods are called without instantiating their class and cannot be called through a class instance. static methods are often used to create utility functions for an application. ...
...ods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. this behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode. ...
...And 5 more matches
Array.from() - JavaScript
ibute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax array.from(arraylike [, mapfn [, thisarg]]) parameters arraylike an array-like or iterable object to convert to an array. mapfn optional map function to call on every element of the array. thisarg optional value to use as this when executing mapfn. re
turn value a new array instance. description array.from() lets you create arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects such as map and set). array.from() has an optional parameter mapfn, which allows you to execute a map() function on each element of the array being created. more clearly, array.from(obj, mapfn, thisarg) h...
...!array.from) { array.from = (function () { var symboliterator; try { symboliterator = symbol.iterator ? symbol.iterator : 'symbol(symbol.iterator)'; } catch { symboliterator = 'symbol(symbol.iterator)'; } var tostr = object.prototype.tostring; var iscallable = function (fn) { re
turn ( typeof fn === 'function' || tostr.call(fn) === '[object function]' ); }; var tointeger = function (value) { var number = number(value); if (isnan(number)) re
turn 0; if (number === 0 || !isfinite(number)) re
turn number; re
turn (number > 0 ? 1 : -1) * math.floor(math.abs(number)); }...
...r = function (value) { var number = number(value); if (isnan(number)) re
turn 0; if (number === 0 || !isfinite(number)) re
turn number; re
turn (number > 0 ? 1 : -1) * math.floor(math.abs(number)); }; var maxsafeinteger = math.pow(2, 53) - 1; var tolength = function (value) { var len = tointeger(value); re
turn math.min(math.max(len, 0), maxsafeinteger); }; var setgetitemhandler = function setgetitemhandler(isiterator, items) { var iterator = isiterator && items[symboliterator](); re
turn function getitem(k) { re
turn isiterator ? iterator.next() : items[k]; }; }; var getarray = function getarray( t, ...
...And 5 more matches
Array.prototype.indexOf() - JavaScript
if the provided index value is a negative number, it is taken as the offset from the end of the array. ...
...ub 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 arr.indexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index to start the search at. ...
... description indexof() compares searchelement to elements of the array using strict equality (the same method used by the === or triple-equals operator). note: for the string method, see string.prototype.indexof(). ...
...And 5 more matches
Math.fround() - JavaScript
description javascript uses 64-bit double floating-point numbers internally, which offer a very high precision. ...
... 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 var singlefloat = math.fround(doublefloat); parameters doublefloat a number. if the parameter is of a different type, it will get converted to a number or to nan if it cannot be converted. re
turn value the nearest 32-bit single precision float representation of the given number. description javascript uses 64-bit double floating-point numbers internally, which offer a very high precision. however, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a float32array. this can create confusion: checking a 64-bit float and a 32-bit flo...
... even though the numbers are seemingly identical. to solve this, math.fround() can be used to cast the 64-bit float to a 32-bit float. internally, javascript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. ...
...And 5 more matches
Object.setPrototypeOf() - JavaScript
il engine developers address this issue, if you are concerned about performance, you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). syntax object.setprototypeof(obj, prototype) parameters obj the object which is to have its prototype set. prototype the object's new prototype (an object or null). re
turn value the specified object. description throws a typeerror exception if the object whose [[prototype]] is to be modified is non-extensible according to object.isextensible(). does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or undefined). otherwise, this method changes the [[prototype]] of obj to the new value. object.setprototypeof() is in the e...
...way to set the prototype of an object, vs. the more controversial object.prototype.__proto__ property. appending prototype chains a combination of object.getprototypeof() and object.prototype.__proto__ permits appending a whole prototype chain to a new prototype object: /** *** object.appendchain(@object, @prototype) * * appends the first non-native prototype of a chain to a new prototype. * re
turns @object (if it was a primitive value it will transformed into an object). * *** object.appendchain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body") *** object.appendchain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") * * appends the first non-native prototype of a chain to the native function.prototype object, then appends a * new fu...
...d into an object). * *** object.appendchain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body") *** object.appendchain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") * * appends the first non-native prototype of a chain to the native function.prototype object, then appends a * new function(["@arg"(s)], "@function_body") to that chain. ...
...And 5 more matches
Object.prototype.toSource() - JavaScript
you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
... you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
... you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
...And 5 more matches
String.prototype.replace() - JavaScript
the replace() method re
turns a new string with some or all matches of a pattern replaced by a replacement. the pattern can be a string or a regexp, and the replacement can be a string or a function to be called for each match. if pattern is a string, only the first occurrence will be replaced. the original string is left unchanged. 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 newstr = str.replace(regexp|substr, newsubstr|function) parameters regexp (pattern) a regexp object or literal. the match or matches are replaced with newsubstr or the value re
turned by the specified function. substr a ...
... or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. re
turn value a new string, with some or all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply re
turns a new string. to perform a global search and replace, include the g switch in the regular expression. specifying a string as a parameter the replacement string can include the following special replacement patterns: ...
...pturing group name. if the group is not in the regular expressions (or not in the match), this will resolve to the empty string. only available in browser versions supporting named capturing groups. specifying a function as a parameter you can specify a function as the second parameter. in this case, the function will be invoked after the match has been performed. the function's result (re
turn value) will be used as the replacement string. (note: the above-mentioned special replacement patterns do not apply in this case.) note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. the arguments to the function are as follows: possible name supplied value match the mat...
...And 5 more matches
String.prototype.split() - JavaScript
the division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call. 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 str.split([separator[, limit]]) parameters separator optional the pattern describing where each split should occur. ...
...parator is just a single character; this is used to split a delimited string. for example, a string containing tab separated values (tsv) could be parsed by passing a tab character as the separator, like this: mystring.split("\t"). if separator contains multiple characters, that entire character sequence must be found in order to split. if separator is omitted or does not occur in str, the re
turned array contains one element consisting of the entire string. if separator appears at the beginning (or end) of the string, it still has the effect of splitting. the result is an empty (i.e. zero length) string, which appears at the first (or last) position of the re
turned array. if separator is an empty string (""), str is converted to an array of each of its utf-16 "characters". warn...
...tive integer limiting the number of pieces. if provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. any leftover text is not included in the array at all. the array may contain fewer entries than limit if the end of the string is reached before the limit is reached. if limit is 1, str.split(separator)[0] is re
turned if limit is 0, [] is re
turned. re
turn value an array of strings, split at each point where the separator occurs in the given string. description when found, separator is removed from the string, and the substrings are re
turned in an array. if separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) ...
...And 5 more matches
Template literals (Template strings) - JavaScript
log(`fifteen is ${a + b} and not ${2 * a + b}.`); // "fifteen is 15 and // not 20." nesting templates in certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. within a backticked template, it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. for instance, if condition a is true, then re
turn this templated literal. in es5: let classes = 'header'; classes += (islargescreen() ? '' : item.iscollapsed ? ' icon-expander' : ' icon-collapser'); in es2015 with template literals and without nesting: const classes = `header ${ islargescreen() ? '' : (item.iscollapsed ? 'icon-expander' : 'icon-collapser') }`; in es2015 with nested template literals: const classes = `header ${ isl...
...psed ? 'expander' : 'collapser'}` }`; tagged templates a more advanced form of template literals are tagged templates. tags allow you to parse template literals with a function. the first argument of a tag function contains an array of string values. the remaining arguments are related to the expressions. the tag function can then perform whatever operations on these arguments you wish, and re
turn the manipulated string. (alternatively, it can re
turn something completely different, as described in one of the following examples.) the name of the function used for the tag can be whatever you want. let person = 'mike'; let age = 28; function mytag(strings, personexp, ageexp) { let str0 = strings[0]; // "that " let str1 = strings[1]; // " is a " // there is technically a string after...
...; function mytag(strings, personexp, ageexp) { let str0 = strings[0]; // "that " let str1 = strings[1]; // " is a " // there is technically a string after // the final expression (in our example), // but it is empty (""), so disregard. ...
...And 5 more matches
Navigation and resource timings - Web Performance
. the order is: performance timings details navigationstart when the prompt for unload terminates on the previous document in the same browsing context. if there is no previous document, this value will be the same as performancetiming.fetchstart. secureconnectionstart when the secure connection handshake starts. if no such connection is requested, it re
turns 0. redirectstart when the first http redirect starts. if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0. redirectend when the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirects is not of the same origin, the value r...
... connectend when the connection is opened network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment end time is given. ...
...k, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. unloadeventstart when the unload> event has been thrown, indicating the time at which the previous document in the window began to unload. if there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value re
turned is 0. unloadeventend when the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value re
turned is 0. dominteractive when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystate...
...And 5 more matches
Using custom elements - Web Components
age feature. this article introduces the use of the custom elements api. note: custom elements are supported by default in firefox, chrome, and edge (76). opera and safari so far support only autonomous custom elements. high-level view the controller of custom elements on a web document is the customelementregistry object — this object allows you to register a custom element on the page, re
turn information on what custom elements are registered, etc. to register a custom element on the page, you use the customelementregistry.define() method. this takes as its arguments: a domstring representing the name you are giving to the element. note that custom element names require a dash to be used in them (kebab-case); they can't be single words. a class object that defines the behaviour o...
...functionality the element will have when an instance of it is instantiated. in this case we attach a shadow root to the custom element, use some dom manipulation to create the element's internal shadow dom structure — which is then attached to the shadow root — and finally attach some css to the shadow root to style it. ...
...browsers implement an optimization for <style> tags either cloned from a common node or that have identical text, to allow them to share a single backing stylesheet. with this optimization the performance of external and internal styles should be similar. customized built-in elements now let's have a look at another customized built in element example — expanding-list (see it live also). this
turns any unordered list into an expanding/collapsing menu. first of all, we define our element's class, in the same manner as before: class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // write element functionality in here ... } } we will not explain the element functionality in any detail here, but you can disco...
...And 5 more matches
Using the WebAssembly JavaScript API - WebAssembly
= { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming counterparts, because they can
turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function into it, compile and instantiate it, and access its exported function — all in one step...
..., import a javascript function into it, compile and instantiate it, and access its exported function — all in one step. add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we call our exported webassembly function exported_func, which in
turn calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console. if you save your example code now and load it a browser that supports webassembly, you’ll see this in action! note: this is a convoluted, longwinded example that achieves very little, but it does serve to illustrate what is possible — using webassembly cod...
...sn’t aim to replace javascript; the two instead can work together, drawing on each other’s strengths. loading our wasm module without streaming if you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods webassembly.compile / webassembly.instantiate instead. these methods don't directly access the byte code, so require an extra step to
turn the response into an arraybuffer before compiling/instantiating the wasm module. the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { results.instance.exports.exported_func(); }); viewing wasm in developer tools in firefox 54+, the developer tool debugger pa...
...And 5 more matches
Downloading Files - Archive of obsolete content
} } persist.saveuri(obj_uri, null, null, null, "", targetfile, privacy); downloading files that require credentials before calling nsiwebbrowserpersist.saveuri(), you need to set the progresslistener property of the nsiwebbrowserpersist instance to an object that implements nsiauthprompt. normally, nsiauthprompt expects a prompt to be displayed so the user can enter credentials, but you can re
turn a username and password credentials directly without prompting the user. if you want to open a login prompt, you can use the default prompt by calling the window watcher's getnewauthprompter() method. components.utils.import("resource://gre/modules/privatebrowsingutils.jsm"); const webbrowserpersist = components.constructor("@mozilla.org/embedding/browser/nswebbrowserpersist;1", ...
... privacy = privatebrowsingutils.privacycontextfromwindow(urlsourcewindow); var hardcodedusername = "ericjung"; var hardcodedpassword = "foobar"; persist.progresslistener = { queryinterface: xpcomutils.generateqi(["nsiauthprompt"]), // implements nsiauthprompt prompt: function(dialogtitle, text, passwordrealm, savepassword, defaulttext, result) { result.value = hardcodedpassword; re
turn true; }, promptpassword: function(dialogtitle, text, passwordrealm, savepassword, pwd) { pwd.value = hardcodedpassword; re
turn true; }, promptusernameandpassword: function(dialogtitle, text, passwordrealm, savepassword, user, pwd) { user.value = hardcodedusername; pwd.value = hardcodedpassword; re
turn true; } }; persist.saveuri(urltosave, null, null, null, "", nsfil...
...// tried with .jpg, .ico, .gif (even .html). ...
...And 4 more matches
Finding window handles - Archive of obsolete content
illa.org/en/docs..._of_interfaces another way to find a window handle... is to query it from an object. once you have a docshell, queryinterface it into nsibasewindow, call getmainwidget on result, and then call getnativedata(ns_native_window). like this hwnd gethwnd(nsibasewindow *window) { nscomptr< nsiwidget > widget; window->getmainwidget(getter_addrefs(widget)); if (widget) re
turn (hwnd) widget->getnativedata(ns_native_window); } yet another way to find a window handle (parent window handle) this method is for people who want to get the top level window hwnd from the window object in javascript. comparing to the method above, by using this method, you don't have to compile your component with nsiwidget.h and other bunchs of h files that should not be exposed to outside...
... firefox source, or http://mxr.mozilla.org/mozilla/sourc...basewindow.idl), and use xpidl to compile it to .h file, although that's stll a unfrozen interface, but it should be a lot better. notice that by using only the c++ part of this code will get the the parent window handle of the nsibasewindow you give as a param. that means if you use the top level nsibasewindow as a param, null will be re
turned in the chain and cause crash of firefox, that's a bug of firefox.(https://bugzilla.mozilla.org/show_bug.cgi?id=489045) now, let's move forward. first, in javascript, the code gets the nsibasewindow we want, it's a direct child of the top nsibasewindow. var basewindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.i...
... .treeowner .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsibasewindow); then in c++ part, a function take nsibasewindow as param hwnd getparentwindowhwnd(nsibasewindow *window) { nativewindow hwnd; nsresult rv = window->getparentnativewindow(&hwnd); if (ns_failed(rv)) re
turn null; re
turn (hwnd)hwnd; } that's it; use with caution! os specific examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the examples below, the native handle to the most recent navigator:browser is obtained and then it is focused. run the snippets below from the scratchpad in environment > browser. recall that nsibasewindow -> nativehandle re
turns the following in ...
...And 4 more matches
LookupNamespaceURI - Archive of obsolete content
however, due to bug 312019, this method does not work with dynamically assigned namespaces (e.g., those set with node.prefix). ...
...ment : htmldocument; // support htmldocument if document not present // if document is present, is this method also present? ...
...a only xmlnspattern = /^xmlns:(.*)$/; switch (node.nodetype) { case 1: // element_node (could also just test for node.element_node, etc., if supported in all browsers) if (node.namespaceuri != null && node.prefix === prefix) { // note: prefix could be "null" in the case we are looking for default namespace re
turn node.namespaceuri; } if (node.attributes.length) { for (i = 0; i < node.attributes.length; i++) { att = node.attributes[i]; if (xmlnspattern.test(att.name) && xmlnspattern.exec(att.name)[1] === prefix) { if (att.value) { re
turn att.value; ...
...And 4 more matches
Preferences - Archive of obsolete content
he get methods of nsiprefbranch (assuming it's a branch of the tree with current values) is called, it does the following: checks whether the current tree has a value for the preference and whether or not the preference is locked. ...
... otherwise an ns_error_unexpected exception is thrown. if the branch is from the default tree, the get method doesn't check the tree with current values at all. ...
... .getservice(components.interfaces.nsiprefservice); var branch = prefs.getbranch("acce"); var enablesound = branch.getboolpref("ssibility.typeaheadfind.enablesound"); this is the reason why you should usually pass strings ending with a dot to getbranch(), like prefs.getbranch("accessibility."). ...
...And 4 more matches
Rosetta - Archive of obsolete content
(oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\". ...
...first, you should declare a function which will translate an input plain-text written in c to an output plain-text written in ecmascript. let us call t...
...; } if (typeof fcompiler !== "function") { throw new typeerror("rosetta.appendcompiler() \u2013 second argument must be a function"); } if (!array.isarray(vmimetypes)) { odicts[(vmimetypes).tostring()] = fcompiler; re
turn true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { odicts[(vmimetypes[nidx]).tostring()] = fcompiler; } re
turn true; }; })(); now, imagine you need a compiler for scripts written in c (mime type: text/x-c). first, you should declare a function which will translate an input plain-text written in c to an output plain-text written in ecmascript. let us call this function createecmasrc() and let us associate it with the c mime types: rosetta_c.js: a c compiler /* c compiler for rosetta */ (function (...
...And 4 more matches
getAttributeNS - Archive of obsolete content
g might be used to work on them as well. while namespaced attributes are less common than namespaced elements, some standards such as xlink depend on them. note that all gecko-based browsers (including firefox) support dom:element.getattributens. this function is not necessary for gecko-based browsers. ...
...butes are less common than namespaced elements, some standards such as xlink depend on them. note that all gecko-based browsers (including firefox) support dom:element.getattributens. this function is not necessary for gecko-based browsers. ...
...n them. note that all gecko-based browsers (including firefox) support dom:element.getattributens. this function is not necessary for gecko-based browsers. ...
...And 4 more matches
Adding windows and dialogs - Archive of obsolete content
should not be resizable unless they display dynamically generated content from a datasource, such as lists or trees that may need resizing to have a better view of the content. to open a new dialog, use the function window.opendialog, an extension of the open function. it allows you to send a set of optional parameters that can be used to communicate with the dialog. ...
...ew dialog, use the function window.opendialog, an extension of the open function. it allows you to send a set of optional parameters that can be used to communicate with the dialog. let somevalue = 2; let re
turnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, re
turnvalue); // you can send as many extra parameters as you need. ...
...tion. it allows you to send a set of optional parameters that can be used to communicate with the dialog. let somevalue = 2; let re
turnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, re
turnvalue); // you can send as many extra parameters as you need. // if (re
turnvalue.accepted) { do stuff } the optional parameters are available in the dialog code through the window.arguments property: let somevalue = window.arguments[0]; let re
turnvalue = window.arguments[1]; // re
turnvalue.accepted = true; // re
turnvalue.result = "something"; the parameter named re
turnvalue is an object that the dialog will modify to reflect what the user did in it. this is th...
...And 4 more matches
XPCOM Objects - Archive of obsolete content
at mdc, you'll see stuff like this: void setcharpref(in string aprefname, in string avalue); one of the most important details to notice is that both paratemers have the in keyword. this specifies that these are input parameters, values that the method will use to perform its actions. when is a parameter not an in parameter? in some methods the out keyword is used for parameters that are re
turn values in reality. this is done for certain value types that are not valid as re
turn values in idl, such as typed arrays. void getchildlist(in string astartingat, out unsigned long acount,[array, size_is(acount), retval] out string achildarray); this method re
turns an array of strings. the first parameter is an input that tells the method where to start looking. the second one will hold the...
...note the metadata included in the square brackets, indicating that the parameter is an array, and that its size is determined by the acount parameter. ...
..." /** * counter for the hello world extension. keeps track of how many times the * hello world message has been shown. */ [scriptable, uuid(bd46f689-6c1d-47d0-bc07-bb52b546b8b5)] interface xsihellocounter : nsisupports { /* the maximum allowed count. */ const short max_count = 100; /* the current count. */ readonly attribute short count; /** * increments the display count and re
turns the new count. * @re
turn the incremented count. */ short increment(); }; the bits about nsisupports are common to most xpcom interface definitions. nsisupports is the base interface for all interfaces, so it should always be included, except for cases where your interface extends another interface. in those cases you just need to replace nsisupports with the interface you're extending...
...And 4 more matches
MMgc - Archive of obsolete content
to wait for gc to clean it up. delete myobject; the destructor for a gcobject will never be called (unless the object is also a descendant of gcfinalizedobject... ...
...gcfinalizedobject base class: gcobject a garbage collected object with finalization support. all of the rules from gcobject above apply to gcfinalizedobject. the finalizer (c++ destructor) of a gcfinalizedobject will be invoked when mmgc collects the object. ...
...o be. finding missing write barriers there are some automatic aids in the mmgc library which can help you find missing write barriers. look in mmgc/gc.cpp. // before sweeping we check for missing write barriers bool gc::incrementalvalidation = false; // check for missing write barriers at every alloc bool gc::incrementalvalidationpedantic = false; if you suspect you have missing write barriers,
turn these switches on in a debug build. (the second switch will slow your application down a lot more than the first switch, so you could try the first, then the second.) when a missing write barrier is detected, mmgc will assert and drop you into the debugger, and will print out a message telling you which object contained the missing write barrier, the address of the member variable that needs it, ...
...And 4 more matches
Menu - Archive of obsolete content
node wrapped by jquery. hide() hides the menu if it is showing. insertbefore(newitems, target) inserts new items before an existing item. parameters newitems a single menuitem or an array of menuitems. target indicates the existing item. see targets. if no such target exists, the position at which the items are added is at the discretion of jetpack. item(target) re
turns an item in the menu. the item may be modified. if the menu is hidden, it will reflect the changes when it is next shown. if the menu is visible, it will reflect the changes immediately. parameters target indicates the existing item. see targets. re
turn value a menuitem object, or null if no such target exists. popupon(node) binds the menu to a given node. the menu will be shown ...
...api, pass one of the following types: null a simple menu separator. (note that any falsey value will suffice, including undefined, null, and the empty string. null is recommended because it stands out.) function a menuitem that will update itself when its menu is shown. the function is invoked just before the item's menu is shown and when the items array of the item's menu is retrieved. it must re
turn a non-function menuitem. if the item belongs to a context menu, the function is called as function(context) and otherwise function(). context is an object describing the context in which the menu was shown. string a simple menuitem with the given string label. object a menuitem with specific properties. the object may define any of the properties listed below. properties property ...
... change and in fact will be changing in firefox 3.7. by exposing functionality through jetpack.menu, a feature is guaranteed an easy transition. many users, especially those new to firefox, don't realize the distinction between add-ons and the browser itself. if a user forgets or is unable to tell whether a certain menuitem is part of firefox or provided by a feature, she does not know where to
turn when she has problems with it. if many features' menus are local to one area, the user need not hunt and peck through many menus trying to find a particular item of a feature. no one likes it when add-ons clutter her tools menu willy-nilly. it's less code. (ok, slightly less.) this is only a recommended practice; developers are of course free to do as they wish. jetpack.menu.file the brows...
...And 4 more matches
LIR - Archive of obsolete content
in nanojit, lir is the source language for compilation to machine code. lir stands for low-level intermediate representation. it is a typed assembly language. the lir instruction set is best learnt by reading nanojit/liropcode.tbl. code for manipulating lir is in nanojit/lir.h. nanojit lir instruction cheat sheet.also in pdf format see attachment. category op code code name re
turn type featured description miscellaneous 0 start void start of a fragment 1 regfence void a register fence causes no code to be generated, but it affects register allocation so that no registers are live when it is reached. 2 skip void links code chunks. 3 parami integer 32 bit load an int parameter (register or stack location). 4 paramq ...
... affects register allocation so that no registers are live when it is reached. 2 skip void links code chunks. 3 parami integer 32 bit load an int parameter (register or stack location). 4 paramq quad 64 bit load a quad parameter (register or stack location). ...
...ters are live when it is reached. 2 skip void links code chunks. 3 parami integer 32 bit load an int parameter (register or stack location). 4 paramq quad 64 bit load a quad parameter (register or stack location). ...
...And 4 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
this input is defined in line 22, where getfolder() is used to assign a value to the communicatorfolder variable representing the "program" folder on the local system: var communicatorfolder = getfolder("program"); spaceavailable = filegetdiskspaceavailable(dir...
...this input is defined in line 22, where getfolder() is used to assign a value to the communicatorfolder variable representing the "program" folder on the local system: var communicatorfolder = getfolder("program"); spaceavailable = filegetdiskspaceavailable(dirpath); spacerequired,...
...wser.xpi install script, the files are added in lines 26-41: err = adddirectory("program", "6.0.0.2000110807", "bin", // jar source folder communicatorfolder, // target folder "", // target subdir true ); // force flag logcomment("adddirectory() re
turned: " + err); // create the plugins folder next to mozilla var pluginsfolder = getfolder("plugins"); if (!fileexists(pluginsfolder)) { var ignoreerr = dircreate(pluginsfolder); logcomment("dircreate() re
turned: " + ignoreerr); } else logcomment("plugins folder already exists"); in this case, the files are contained within a single directory, so calling the install ...
...And 4 more matches
Commands - Archive of obsolete content
hods for retrieving controllers for commands and for retrieving and modifying the focus. adding controllers you can implement your own controllers to respond to commands. you could even override the default handling of a command with careful placement of the controller. a controller is expected to implement four methods, which are listed below: supportscommand (command) this method should re
turn true if the controller supports a command. if you re
turn false, the command is not handled and command dispatcher will look for another controller. a single controller may support multiple commands. iscommandenabled (command) this method should re
turn true if the command is enabled, or false if it is disabled. corresponding buttons will be disabled automatically. docommand (command) execute t...
...ed. really, we should ensure that the selection and focus is adjusted appropriately after a deletion. ...
... <window id="controller-example" title="controller example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ re
turn (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") re
turn (list.selecteditem != null); re
turn false; }, docommand : function(cmd){ list.removeitemat(list.selectedindex); }, onevent : function(evt){ } }; list.controllers.appendcontroller(listcontroller); } </script> <listbox id="thelist"> <listitem label="ocean"/> <listitem label="desert"/> <listitem label="jungle"/> <listitem label="swamp"/> </listbox> </window...
...And 4 more matches
Custom Tree Views - Archive of obsolete content
he view to get the information that it needs to display. in general, although the tree view has thirty or so functions that may be implemented, you only need to implement the ones that the tree will call. three methods that you should implement are listed below. rowcount this property should be set to the total number of rows in the tree. getcelltext( row , column ) this method should re
turn the text contents at the specified row and column. this will be called to display data for each cell. the rows are supplied as numeric values starting at 0. the columns are treecolumn objects. in the older versions of mozilla (before firefox 1.5 or mozilla 1.8), the columns are supplied as the values of the id attribute on the columns. if you need a id attribute like older versions, the id proper...
...the columns. if you need a id attribute like older versions, the id property of treecolumn can be used. settree( tree ) this method is called once to set the tree element on the view. ...
...attribute like older versions, the id property of treecolumn can be used. settree( tree ) this method is called once to set the tree element on the view. ...
...And 4 more matches
tabs - Archive of obsolete content
ton in the tab row. properties accessibletype type: integer a value indicating the type of accessibility object for the element. disabled type: boolean gets and sets the value of the disabled attribute. itemcount type: integer read only property holding the number of child items. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selecteditem type: element holds the currently selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a...
...ntly selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a select event will be sent to the controlling container (i.e. the listbox, richlistbox, radiogroup, etc., not the list item that was selected) when it is changed either via this property, the selectedindex property, or changed by the user. tabbox type: tabbox element re
turns the tabbox element that contains the tabs. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string gets and sets the value of the value attribute. for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax. methods inh...
...ore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata advanceselectedtab( dir, wrap ) re
turn type: no re
turn value if the argument dir is set to 1, the currently selected tab changes to the next tab. if the argument dir is set to -1, the currently selected tab changes to the previous tab. if the wrap argument is true, the adjustment will wrap around when the first or last tab is reached. appenditem( label, value ) re
turn type: element creates a new item and adds i...
...And 4 more matches
NPClass - Archive of obsolete content
unctionptr removeproperty; npenumerationfunctionptr enumerate; npconstructfunctionptr construct; }; warning: don't call these routines directly. you should instead use the appropriate api functions. fields structversion the version number of the structure. this is set to np_class_struct_version, which is 1 in mozilla 1.8.*, 2 since mozilla 1.9a1, and 3 since firefox 3.0b1. allocate re
turns a pointer to a newly allocated npobject. called by npn_createobject() if non-null, otherwise the browser calls malloc(). this function is expected to allocate and re
turn enough storage to hold the npobject that is being created. deallocate called by npn_releaseobject() when an object's reference count reaches zero. if this field is null, free() is called isntead. invalidate called on live ob...
...d is null, free() is called isntead. invalidate called on live objects that belong to a plugin instance that is being destroyed. this call is always followed by a call to the deallocate function, or free(). any attempt to use an invalidated object will result in undefined behavior. hasmethod called by npn_hasmethod() to determine whether or not a specified method exists on a given npobject. re
turns true if the method exists, otherwise re
turns false. invoke called by npn_invoke() to invoke a specific method on a given npobject. re
turns true if invocation succeeded or false if an error occurred. invokedefault called by npn_invokedefault() to invoke the default method (if available) on a given npobject. re
turns true if invocation succeeded or false if an error occurred. hasproperty call...
... invoke a specific method on a given npobject. re
turns true if invocation succeeded or false if an error occurred. invokedefault called by npn_invokedefault() to invoke the default method (if available) on a given npobject. re
turns true if invocation succeeded or false if an error occurred. hasproperty called by npn_hasproperty() to check whether a given property exists on a given npobject. re
turns true if the specified property exists, otherwise re
turns false. getproperty called by npn_getproperty() to get the value of the specified property on a given npobject. re
turns true if the value was successfully retrieved, otherwise re
turns false. ...
...And 4 more matches
XForms Custom Controls - Archive of obsolete content
sh custom control. </body> </method> <constructor> // we should redirect calls of input's 'refresh' method to custom control 'refresh' method. var control = this; var refreshstub = function() { control.refresh(); } this.ref1.refresh = refreshstub; this.ref2.refresh = refreshstub; </constructor> <property name="ref1" readonly="true" onget="re
turn this.ownerdocument.getanonymouselementbyattribute(this, 'anonid', 'ref1');"/> <property name="ref2" readonly="true" onget="re
turn this.ownerdocument.getanonymouselementbyattribute(this, 'anonid', 'ref2');"/> </implementation> new host language the mozilla xforms implementation currently only supports xforms hosted in xhtml or xul documents. if you need to have xforms in other kinds...
...node. */ void refresh(); /** * is called when focus is advanced to the xforms element. */ boolean focus(); /** * is called when control should be disabled. * this really only applies to the submit element. */ void disable(in boolean disable); /** * is called to get current value of control. */ string getcurrentvalue(); } notes: getcurrentvalue() should re
turn the current value of the control as seen by a user. the current value of a control could differ from the value of the bound node in cases where @incremental='false'. disable() is called by the xforms processor to indicate to a submit element that it needs to disable/enable due to the beginning/ending of the submission process. currently it has no meaning outside of this context. focus() is used b...
...iwidget interface. but certain xforms controls need to implement additional interfaces. such elements include upload and case. nsixformsaccessors the nsixformsaccessors interface allows access to the value and the state of the instance node that the control is bound to (see extensions/xforms/nsixformsaccessors.idl). ...
...And 4 more matches
HTML text fundamentals - Learn web development
answer this question, let's take a look at text-start.html—the starting point of our running example for this article (a nice hummus recipe). you should save a copy of this file on your local machine, as you'll need it for the exercises later on. this document's body currently contains multiple pieces of content—they aren't marked up in any way, but they are separated with linebreaks (enter/re
turn pressed to go onto the next line). however, when you open the document in your browser, you'll see that the text appears as a big chunk! this is because there are no elements to give the content structure, so the browser does not know what is a heading and what is a paragraph. furthermore: users looking at a web page tend to scan quickly to find relevant content, often just reading the hea...
...apply css to it (or do something to it with javascript) without giving it any extra meaning. (you'll find out more about these later on in the course.) we've applied some css to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. it is a good idea to use the relevant html element for the job. lists now let's
turn our attention to lists. lists are everywhere in life—from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! lists are everywhere on the web, too, and we've got three different types to worry about. unordered unordered lists are used to mark up lists of items for which the or...
...r code is being shown, // not the solution, so that solution is not saved over the user code if(solution.value === 'show solution') { userentry = textarea.value; } else { solutionentry = textarea.value; } updatecode(); }; ordered ordered lists are lists in which the order of the items does matter—let's take a set of directions as an example: drive to the end of the road
turn right go straight across the first two roundabouts
turn left at the third roundabout the school is on your right, 300 meters up the road the markup structure is the same as for unordered lists, except that you have to wrap the list items in an <ol> element, rather than <ul>: <ol> <li>drive to the end of the road</li> <li>
turn right</li> <li>go straight across the first two roundabouts</li...
...And 4 more matches
Images in HTML - Learn web development
to describe images is useful to most users. as described above, the spelling of the file or path name might be wrong. the browser doesn't support the image type. some people still use text-only browsers, such as lynx, which displays the alt text of images. you may want to provide text for search engines to utilize; for example, search engines can match alt text with search queries. users have
turned off images to reduce data transfer volume and distractions. this is especially common on mobile phones, and in countries where bandwidth is limited or expensive. what exactly should you write inside your alt attribute? it depends on why the image is there in the first place. in other words, what you lose if your image doesn't show up: decoration. you should use css background images for de...
...gnificant information, provide the same information in a brief alt text – or even better, in the main text which everybody can see. don't write redundant alt text. how annoying would it be for a sighted user if all paragraphs were written twice in the main content? if the image is described adequately by the main text body, you can just use alt="". link. if you put an image inside <a> tags, to
turn an image into a link, you still must provide accessible link text. in such cases you may, either, write it inside the same <a> element, or inside the image's alt attribute – whichever works best in your case. text. you should not put your text into images. if your main heading needs a drop shadow, for example, use css for that rather than putting the text into an image. however, if you really ...
...put your text into images. if your main heading needs a drop shadow, for example, use css for that rather than putting the text into an image. however, if you really can't avoid doing this, you should supply the text inside the alt attribute. essentially, the key is to deliver a usable experience, even when the images can't be seen. this ensures all users are not missing any of the content. try
turning off images in your browser and see how things look. you'll soon realize how helpful alt text is if the image cannot be seen. note: for more information, see our guide to text alternatives. width and height you can use the width and height attributes to specify the width and height of your image. you can find your image's width and height in a number of ways. for example on the mac you can...
...And 4 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
00) // with a function defined separately function sayhi() { alert('hello mr. universe!'); } let mygreeting = settimeout(sayhi, 2000); that can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example. but it can also just help keep your code tidy, especially if the timeout callback is more than a few lines of code. settimeout() re
turns an identifier value that can be used to refer to the timeout later, such as when you want to stop it. see clearing timeouts (below) to learn how to do that. passing parameters to a settimeout() function any parameters that you want to pass to the function being run inside the settimeout() must be passed to it as additional parameters at the end of the list. for example, you could refactor the...
... clearing intervals setinterval() keeps running a task forever, unless you do something about it. you'll probably want a way to stop such tasks, otherwise you may end up getting errors when the browser can't complete any further versions of the task, or if the animation being handled by the task has finished. you can do...
...nterval. clearing intervals setinterval() keeps running a task forever, unless you do something about it. you'll probably want a way to stop such tasks, otherwise you may end up getting errors when the browser can't complete any further versions of the task, or if the animation being handled by the task has finished. you can do this the same way you stop timeouts — by passing the identifier re
turned by the setinterval() call to the clearinterval() function: const myinterval = setinterval(myfunction, 2000); clearinterval(myinterval); active learning: creating your own stopwatch! with this all said, we've got a challenge for you. take a copy of our setinterval-clock.html example, and modify it to create your own simple stopwatch. you need to display a time as before, but in this example...
...And 4 more matches
Working with JSON - Learn web development
, arrays, booleans, and other object literals. ...
...nside the variable via your browser's javascript console. arrays as json above we mentioned that json text basically looks like a javascript object, and this is mostly right. the reason we said "mostly right" is that an array is also valid json, for example: [ { "name": "molecule man", "age": 29, "secretidentity": "dan jukes", "powers": [ "radiation resistance", "
turning tiny", "radiation blast" ] }, { "name": "madame uppercut", "age": 39, "secretidentity": "jane wilson", "powers": [ "million tonne punch", "damage resistance", "superhuman reflexes" ] } ] the above is perfectly valid json. you'd just have to access array items (in its parsed version) by starting with an array index, for example [0]["powers"...
...ndatory ones for this simple example: the http method to use when making the network request. in this case get is fine, as we are just retrieving some simple data. the url to make the request to — this is the url of the json file that we stored earlier. next, add the following two lines — here we are setting the responsetype to json, so that xhr knows that the server will be re
turning json, and that this should be converted behind the scenes into a javascript object. then we send the request with the send() method: request.responsetype = 'json'; request.send(); the last bit of this section involves waiting for the response to re
turn from the server, then dealing with it. add the following code below your previous code: request.onload = function() { const superheroe...
...And 4 more matches
React interactivity: Events and state - Learn web development
to use a react hook, we need to import it from the react module. in form.js, change your very first line so that it reads like this: import react, { usestate } from "react"; this allows us to import the usestate() function by itself, and utilize it anywhere in this file. usestate() creates a piece of state for a component, and its only parameter determines the initial value of that state. it re
turns two things: the state, and a function that can be used to update the state later. this is a lot to take in at once, so let's try it out. we're going to make ourselves a name state, and a function for updating the name state. write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what's going on in this line of code? we are se...
...out. we're going to make ourselves a name state, and a function for updating the name state. write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what's going on in this line of code? we are setting the initial name value as "use hooks!". we are defining a function whose job is to modify name, called setname(). usestate() re
turns these two things, so we are using array destructuring to capture them both in separate variables. reading state you can see the name state in action right away. add a value attribute to the form’s input, and set its value to name. your browser will render "use hooks!" inside the input. <input type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="of...
...al state. const [name, setname] = usestate(''); reading user input before we can change the value of name, we need to capture a user's input as they type. for this, we can listen to the onchange event. let’s write a handlechange() function, and listen for it on the <input /> tag. // near the top of the `form` component function handlechange(e) { console.log("typing!"); } // down in the re
turn statement <input type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="off" value={name} onchange={handlechange} /> currently, your input’s value will not change as you type, but your browser will log the word "typing!" to the javascript console, so we know our event listener is attached to the input. in order to change the input’s value, we have...
...And 4 more matches
Implementing QueryInterface
terface ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) { ns_assertion(ainstanceptr, "queryinterface requires a non-null destination!"); // it's a logic error, not a runtime error, to call me without any place to put my answer! // ...but that won't matter when someone calls me wrongly in a non-debug build. if ( !ainstanceptr ) re
turn ns_error_null_pointer; nsisupports* foundinterface; if ( aiid.equals(nscomtypeinfo<nsix>::getiid()) ) foundinterface = ns_static_cast(nsix*, this); else if ( aiid.equals(nscomtypeinfo<nsiy>::getiid()) ) foundinterface = ns_static_cast(nsiy*, this); // ...as many cases as needed... else if ( aiid.equals(nscomtypeinfo<nsisupports>::getiid()) ) foundinterfac...
... it only has one addref. it addrefs the resulting interface, not this, thus following the com-correct way (particularly important in aggregation) it uses nsco...
...// so first i cast to a specific base to avoid ambiguity else foundinterface = 0; nsresult status; if ( !foundinterface ) status = ns_nointerface; else { ns_addref(foundinterface); status = ns_ok; } *ainstanceptr = foundinterface; re
turn status; } what's so good about it? it's clear and simple. ok. it has more than one re
turn, but the primary re
turn is at the end of the function as expected; and the additional re
turn is clear and alone at the top of the function. it only has one addref. it addrefs the resulting interface, not this, thus following the com-correct way (particularly important in aggregation) it uses nscomtypeinfo<t>::getiid() instead of ktiid thus saving a global declaration and global space it uses ...
...And 4 more matches
L20n Javascript API
already present) will be used to negotiate the fallback chain for the user. ctx.registerlocalenegotiator(negotiator: function) register a function which will be used to negotiate the locales supported by the context instance. if you don't call this function, l20n will use the built-in intl.prioritizelocales negotiator. ...
...locales(available, requested, deflocale); }); negotiator is a function which takes 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 re
turn an array which is the final fallback chain of locales, or if the negotiation is asynchronous, it must re
turn 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(fallbackc...
...s.l20n'); ctx.linkresource(template: function) add a resource identified by a url to the context instance. the url is constructed dynamically when you call requestlocales. the function passed to linkresource (called a template function) takes one argument which is the code of the current locale, which needs to be first registered with registerlocales. ctx.linkresource(function(locale) { re
turn '../locales/' + locale + '/strings.l20n'; }); the resource is added to all registered locales. if there are no registered locales (see registerlocales), the default i-default locale is used. in this case, addresource(string) and linkresource(string) might be better suited for adding resources. ctx.addeventlistener(event: string, callback: function) register an event handler on the context in...
...And 4 more matches
AsyncTestUtils extended framework
this is likely to happen when i/o is involved or a potentially expensive process wants to break itself up into smaller chunks (like a search operation) so that the ui stays responsive. in the mozilla platform, the "top level" of a program is the event loop. it is a never-ending loop that dequeues pending events and runs them. this is how asynchronous callbacks get their chance ...
...t the function stops running at the line where you use a yield statement and resumes execution on the next line when resumed. this allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. ...
...ou to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or re
turn false when something asynchronous is going on. when the asynchronous operation is complete, something needs to call async_driver(). re
turning false tells the asynchronous driver that it should yield control up to the top-level. calling async_driver() lets it know to start up again. a function should yield true or re
turn true when the asynchronous driver should continue executing without stopping. a function that does not re
turn anything (or re
turns undefined) and is not a generator is treated like a function that re
turned true. ...
...And 4 more matches
NSS Sample Code Sample_1_Hashing
hash.h> typedef struct { const char *hashname; secoidtag oid; } nametagpair; /* the hash algorithms supported */ static const nametagpair hash_names[] = { { "md2", sec_oid_md2 }, { "md5", sec_oid_md5 }, { "sha1", sec_oid_sha1 }, { "sha256", sec_oid_sha256 }, { "sha384", sec_oid_sha384 }, { "sha512", sec_oid_sha512 } }; /* * maps a hash name to a secoidtag. ...
...ecoidtag. ...
... break; } } re
turn hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); re
turn; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } ...
...And 4 more matches
Hashing - sample 1
<nss.h> typedef struct { const char *hashname; secoidtag oid; } nametagpair; /* the hash algorithms supported */ static const nametagpair hash_names[] = { { "md2", sec_oid_md2 }, { "md5", sec_oid_md5 }, { "sha1", sec_oid_sha1 }, { "sha256", sec_oid_sha256 }, { "sha384", sec_oid_sha384 }, { "sha512", sec_oid_sha512 } }; /* * maps a hash name to a secoidtag. ...
...ecoidtag. ...
...ak; } } re
turn hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); re
turn; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } ...
...And 4 more matches
Initialize NSS database - sample 2
tderr, "%-15s specify a password file\n\n", "-f "); exit(-1); } /* * initslotpassword */ char * initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { re
turn filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { re
turn pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "error opening input terminal for read\n"); re
turn null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, ...
...ize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); re
turn null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0...
...sword: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
...And 4 more matches
sslerr.html
ted in database. wrong password for key database. missing database. ssl_error_bad_certificate -12284 "unable to communicate securely with peer: peers's certificate was rejected." a certificate was received from the remote system and was passed to the certificate authentication callback function provided by the local application. that callback function re
turned secfailure, and the bad certificate callback function either was not configured or did not choose to override the error code re
turned by the certificate authentication callback function. -12283 (unused) ssl_error_bad_client -12282 "the server has encountered bad data from the client." this error code should occur only on sockets that are acting as s...
... ssl_error_post_warning -12275 (unused) ssl_error_ssl2_disabled -12274 "peer only supports ssl version 2, which is l...
... ssl_error_bad_cert_hash_value_alert -12180 "ssl peer reported bad certificate hash value." unspecified errors that occurred while attempting some operation: all the error codes in the following block describe the operation that was being attempted at the time of the unspecified failure. these failures may be caused by the system running out of memory, or errors re
turned by pkcs#11 routines that did not provide meaningful error codes of their own. these should rarely be seen. (certain of these error codes have more specific meanings, as described.) ssl_error_generate_random_failure -12223 "ssl experienced a failure of its random number generator." ssl_error_sign_hashes_failure -12222 "unable to digitally sign data require...
...And 4 more matches
NSS Tools ssltap
ction is established. syntax to run the ssl debugging tool, type this command in a command shell: ssltap [-vhfsxl] [-p port] hostname:port options the command does not require any options other than hostname:port, but you normally use them to control the connection interception and output. the options for the command are the following: -v print a version string for the tool. -h
turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f
turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply i...
...the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. ...
...tion so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x
turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l
turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: http 80 h...
...And 4 more matches
Rhino Debugger
ities for you to control the execution of scripts you are debugging: step into to single step entering any function calls, you may do any of the following: select the debug->step into menu item on the menu bar press the step into button on the toolbar press the f11 key on the keyboard execution will resume. if the current line in the script contains a function call control will re
turn to the debugger upon entry into the function. otherwise control will re
turn to the debugger at the next line in the current function. step over to single step to the next line in the current function, you may do any of the following: select the debug->step over menu item on the menu bar press the step over button on the toolbar press the f7 key on the keyboard execution will res...
...ntry into the function. otherwise control will re
turn to the debugger at the next line in the current function. step over to single step to the next line in the current function, you may do any of the following: select the debug->step over menu item on the menu bar press the step over button on the toolbar press the f7 key on the keyboard execution will resume but control will re
turn to the debugger at the next line in the current function or top-level script. ...
... next line in the current function, you may do any of the following: select the debug->step over menu item on the menu bar press the step over button on the toolbar press the f7 key on the keyboard execution will resume but control will re
turn to the debugger at the next line in the current function or top-level script. step out to continue execution until the current function re
turns you may do any of the following: select the debug->step out menu item on the menu bar press the step out button on the toolbar press the f8 key on the keyboard execution will resume until the current function re
turns or a breakpoint is hit. go to resume execution of a script you may do any of the following: select the debug->go menu item on the menu bar press the go but...
...And 4 more matches
Scripting Java
forms of the method: js> f.listfiles function listfiles() {/* java.io.file[] listfiles() java.io.file[] listfiles(java.io.filenamefilter) java.io.file[] listfiles(java.io.filefilter) */} this output shows that the file class defines three overloaded methods listfiles: one that takes no arguments, another with a filenamefilter argument, and a third with a filefilter argument. all the methods re
turn an array of file objects. being able to view the parameters and re
turn type of java methods is particularly useful in exploratory programming where we might be investigating a method and are unsure of the parameter or re
turn types. another useful feature for exploratory programming is the ability to see all the methods and fields defined for an object. using the javascript for..in construct, we ...
...n rhino it occurs at runtime. this difference is inevitable given javascript's use of dynamic typing as was discussed in chapter 2: since the type of a variable is not known until runtime, only then can overload resolution occur. as an example, consider the following java class that defines a number of overloaded methods and calls them. ...
...table given javascript's use of dynamic typing as was discussed in chapter 2: since the type of a variable is not known until runtime, only then can overload resolution occur. as an example, consider the following java class that defines a number of overloaded methods and calls them. ...
...And 4 more matches
Querying Places
storyqueryoptions, allows configuration of the search result the history service: nsinavhistoryservice, executes the query the first first step is to create the query and options, and fill them with the parameters you want. use nsinavhistoryservice.getnewquery() and nsinavhistoryservice.getnewqueryoptions() to retrieve empty objects. ...
...the different values for this property are listed below. ...
...ueryoptions.sort_by_none. let options = placesutils.history.getnewqueryoptions(); // no query parameters will re
turn everything let query = placesutils.history.getnewquery(); // execute the query let result = placesutils.history.executequery(query, options); result types nsinavhistoryqueryoptions has a resulttype property that allows configuration of the grouping and level of detail to be re
turned in the results. the different values for this property are listed below. these values are also properties of nsinavhistoryqueryoptions, and are accessed like this: components.interfaces.nsinavhistoryqueryoptions.results_as_visit. results_as_uri: this is the default, and re
turns one result node of type result_type_uri for each uri that matches the query. the visit date for each node will be t...
...And 4 more matches
Components.utils.exportFunction
object to attach the function to. this does not have to be the global window object: it could be any other object in the target window, or an object created by the caller. options : object optional parameter that supplies additional options. the following options are currently defined: defineas: determines the name of the function in targetscope. if this is omitted, you need to assign the re
turn value of exportfunction() to an object in the target scope. allowcallbacks: deprecated/redundant from firefox 34. this option allows the exported function to accept callbacks as arguments. boolean, defaulting to false. this option is new in firefox 33. from firefox 34 onwards this option has no effect: the exported function is always able to accept callbacks as arguments. allowcrossoriginargume...
... is always able to accept callbacks as arguments. allowcrossoriginarguments: do not check that arguments to the exported function are subsumed by the caller: this allows the caller to pass objects with a different origin into the exported function, which can then use its privileged status to make cross-origin requests with them. boolean, defaulting to false. this option is new in firefox 34. ...
...however, in firefox 33, you could use the allowcallbacks option to enable the function to accept callbacks. from firefox 34 onwards, any arguments passed into the function are not cloned. instead, they are passed through to the privileged scope as xrays. ...
...And 4 more matches
IAccessibleEditableText
) copies the text range into the clipboard. the specified text between the two given indices is copied into the system clipboard. hresult copytext( [in] long startoffset, [in] long endoffset ); parameters startoffset start index of the text to moved into the clipboard. the valid range is 0..length. endoffset end index of the text to moved into the clipboard. the valid range is 0..length. re
turn value e_invalidarg if bad [in] passed. s_ok. cuttext() deletes a range of text and copies it to the clipboard. the text between the two given indices is deleted from the text represented by this object and copied to the clipboard. hresult cuttext( [in] long startoffset, [in] long endoffset ); parameters startoffset start index of the text to be deleted. the valid range is 0..length. endoffs...
...f text and copies it to the clipboard. the text between the two given indices is deleted from the text represented by this object and copied to the clipboard. hresult cuttext( [in] long startoffset, [in] long endoffset ); parameters startoffset start index of the text to be deleted. the valid range is 0..length. endoffset end index of the text to be deleted. the valid range is 0..length. re
turn value e_invalidarg if bad [in] passed. s_ok. deletetext() deletes a range of text. the text between and including the two given indices is deleted from the text represented by this object. hresult deletetext( [in] long startoffset, [in] long endoffset ); parameters startoffset start index of the text to be deleted. the valid range is 0..length. endoffset end index of the text to be deleted.
...ssed. s_ok. deletetext() deletes a range of text. the text between and including the two given indices is deleted from the text represented by this object. hresult deletetext( [in] long startoffset, [in] long endoffset ); parameters startoffset start index of the text to be deleted. the valid range is 0..length. endoffset end index of the text to be deleted. the valid range is 0..length. ...
...And 4 more matches
mozIStorageAggregateFunction
this is an interface that must be implemented by consumers. it allows consumers to add aggregate functions that are available to sql queries and triggers. an aggregate function is a function that re
turns 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(). storage/public/mozistorageaggregatefunction.idlscriptable please add a summary to this article. ...
...torageconnection.createaggregatefunction(). storage/public/mozistorageaggregatefunction.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void onstep(in mozistoragevaluearray afunctionarguments); nsivariant onfinal(); methods onstep() this is called for each row of results re
turned by the query. the implementation should store or perform some work to prepare to re
turn 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 ...
...ve applies to your use of the storage apis! void onstep( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray 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 re
turn 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 i...
...And 4 more matches
mozIStorageValueArray
signed long the number of entries in the array. constants constant value description value_type_null 0 null data type. value_type_integer 1 integer data type. value_type_float 2 float data type. value_type_text 3 text data type. value_type_blob 4 blob data type. ...
...type. value_type_float 2 float data type. value_type_text 3 text data type. value_type_blob 4 blob data type. methods gettypeofindex() re
turns the type of the value at the given column index. long gettypeofindex( in unsigned long aindex ); parameters aindex the zero-based numerical index for the column to get the data from. re
turn value one of the constants mozistoragevaluearray.value_type_null, mozistoragevaluearray.value_type_integer, mozistoragevaluearray.value_type_float, mozistoragevaluearray.value_type_text, or mozistoragevaluearray.value_type_blob describing the type aindex is. getint32() obtains a int32 from the specified index. long getint32( in unsigned long aindex ); parameters aindex the zero-bas...
...e_null, mozistoragevaluearray.value_type_integer, mozistoragevaluearray.value_type_float, mozistoragevaluearray.value_type_text, or mozistoragevaluearray.value_type_blob describing the type aindex is. getint32() obtains a int32 from the specified index. long getint32( in unsigned long aindex ); parameters aindex the zero-based numerical index for the column to get the data from. re
turn value the int32 for the specified entry. getint64() obtains a int64 from the specified index. long long getint64( in unsigned long aindex ); parameters aindex the zero-based numerical index for the column to get the data from. re
turn value the int64 for the specified entry. getdouble() obtains a double from the specified index. double getdouble( in unsigned long aindex )...
...And 4 more matches
nsIAccessibleDocument
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) you can queryinterface to nsiaccessibledocument from the nsiaccessible or nsiaccessnode for the root node of a document. ...
... the nsidomwindow that the document resides in. read only. windowhandle voidptr the window handle for the os window the document is being displayed in. for example, in windows you can static cast it to an hwnd. read only. ...
...indowhandle voidptr the window handle for the os window the document is being displayed in. for example, in windows you can static cast it to an hwnd. read only. native code only! methods getaccessibleinparentchain() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) re
turns the first accessible parent of a dom node. guaranteed not to re
turn null if the dom node is in a document. ...
...And 4 more matches
nsIAccessibleHyperLink
, the visible output of the html:a tag. with an image map, reflects the actual areas within the map. read only. note: renamed from anchors in gecko 1.9 exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. endindex long the end offset of the hyperlink accessible within the parent accessible. the re
turned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. note: the link itself is represented by one embedded character within the parent text, so the endindex should be startindex + 1. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. selected ...
...erlink. read only. note: the link itself is represented by one embedded character within the parent text, so the endindex should be startindex + 1. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. selected boolean determines whether the element currently has the focus, for example after re
turning from the destination page. read only. note: aria links can only be focused if they have the tabindex attribute set. also, state_focused should then be set on the accessible for this link. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. startindex long the offset of the hyperlink acce...
... note: aria links can only be focused if they have the tabindex attribute set. also, state_focused should then be set on the accessible for this link. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. startindex long the offset of the hyperlink accessible within the parent accessible. the re
turned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. valid boolean determines whether the hyperlink is valid, for example points to a valid url. read only. note: currently only used ...
...And 4 more matches
nsICommandLine
read only. constants state constants constant value description state_initial_launch 0 the first launch of the application instance. state_remote_auto 1 a remote command line automatically redirected to this instance. state_remote_explicit 2 a remote command line explicitly redirected to this instance using xremote/windde/appleevents. ...
...icit 2 a remote command line explicitly redirected to this instance using xremote/windde/appleevents. methods findflag() finds a command-line flag, re
turning its position on the command line. long findflag( in astring aflag, in boolean acasesensitive ); parameters aflag the flag name to locate. do not include the initial hyphen. acasesensitive whether to do case-sensitive comparisons. re
turn value the position of the flag in the command line, or -1 if the flag is not found.getargument() gets the value an argument from the array of command-line arguments, given the index into the argument list. on windows, flags of the form /flag are normalized to -flag. /flag:param are normalized to -flag param. on unix/linux and mac os x, flags of the form --flag are normalized to -flag, and flags o...
...lags of the form /flag are normalized to -flag. /flag:param are normalized to -flag param. on unix/linux and mac os x, flags of the form --flag are normalized to -flag, and flags of the form --flag=param are normalized to the form -flag param. astring getargument( in long aindex ); parameters aindex the argument to retrieve. this index is 0-based, and does not include the application name. re
turn value the value of the specified argument. this is the full text of that argument, so if the argument is a flag, the re
turned value is "-flag [<flagvalue>]". exceptions thrown ns_error_invalid_arg the specified index is out of bounds. handleflag() finds the specified flag, removing it from the array of flags. reports whether or not the specified flag was found. this is useful for boolean flags;...
...And 4 more matches
nsIFilePicker
lter to be selected by default. constants mode constants these constants are used to specify the type of file picker to create when calling init(). constant value description modeopen 0 load a file. modesave 1 save a file. modegetfolder 2 select a folder/directory. modeopenmultiple 3 load multiple files. ...
...nstants mode constants these constants are used to specify the type of file picker to create when calling init(). constant value description modeopen 0 load a file. modesave 1 save a file. modegetfolder 2 select a folder/directory. modeopenmultiple 3 load multiple files. ...
...odeopen 0 load a file. modesave 1 save a file. modegetfolder 2 select a folder/directory. modeopenmultiple 3 load multiple files. re
turn value constants these values are re
turned by show() or passed as an argument to open()'s callback, indicating the result of the file picker activity. constant value description re
turnok 0 the file picker dialog was closed by the user hitting 'ok' re
turncancel 1 the file picker dialog was closed by the user hitting 'cancel' re
turnreplace 2 the user chose an existing file and acknowledged that they want to overwrite the file filter constants these constants are used to create filters for commonly-used file types. for the most up to dat...
...And 4 more matches
nsILivemarkService
ark( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri of the actual rss feed. index the index to insert at, or -1 to append to the end of the list. re
turn value the id of the folder for the livemark. createlivemarkfolderonly() this method also creates a new livemark but use this method during startup to avoid http traffic. long long createlivemarkfolderonly( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when disp...
...nly( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri of the actual rss feed. index the index to insert at, or -1 to append to the end of the list. ...
... long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder. name the name to show when displaying the livemark. siteuri the uri of the site from which the livemark was created. feeduri the uri of the actual rss feed. index the index to insert at, or -1 to append to the end of the list. ...
...And 4 more matches
nsIMsgCustomColumnHandler
() nsimsgcustomcolumnhandler.getsortstringforrow() nsimsgcustomcolumnhandler.getsortlongforrow() nsimsgcustomcolumnhandler.isstring() and optionally: nsitreeview.getrowproperties() from c++ you must implement all of nsitreeview and nsimsgcustomcolumnhandler. ...
...optionally: nsitreeview.getrowproperties() from c++ you must implement all of nsitreeview and nsimsgcustomcolumnhandler. ...
...+ you must implement all of nsitreeview and nsimsgcustomcolumnhandler. ...
...And 4 more matches
nsIPluginHost
resultingagentstring); native code only! attributes attribute type description plugincount unsigned long read only. native code only! methods native code only!createtempfiletopost to create temp file with content len header in, it will use by http post. nsifile createtempfiletopost( in string apostdataurl ); parameters apostdataurl re
turn value native code only!createtmpfiletopost obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)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. to create temp file with content len header in, it will use by http post. void createtmpfiletopost( in string apostdat...
.... void deletepluginnativewindow( in nspluginnativewindowptr apluginnativewindow ); parameters apluginnativewindow native code only!destroy void destroy(); parameters none. native code only!findproxyforurl fetches a url. (corresponds to npn_geturl and npn_geturlnotify.) posts to a url with post data and/or post headers. (corresponds to npn_posturl and npn_posturlnotify.) re
turns the proxy info for a given url. the caller is required to free the resulting memory with nsimalloc.free(). the result will be in the following format. "direct" -- no proxy "proxy xxx.xxx.xxx.xxx" -- use proxy "socks xxx.xxx.xxx.xxx" -- use socks mixed. for example "proxy 111.111.111.111;proxy 112.112.112.112", "proxy 111.111.111.111;socks 112.112.112.112".... which proxy/socks to use is ...
..." -- use socks mixed. for example "proxy 111.111.111.111;proxy 112.112.112.112", "proxy 111.111.111.111;socks 112.112.112.112".... which proxy/socks to use is determined by the plugin. void findproxyforurl( in string aurl, out string aresult ); parameters aurl aresult native code only!getplugin nsiplugin getplugin( in string amimetype ); parameters amimetype re
turn value getplugincount() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void getplugincount( out unsigned long aplugincount ); parameters aplugincount native code only!getpluginfactory obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)this feature is obsolete. although it may still work in some browsers, its...
...And 4 more matches
nsIProtocolProxyService
lter afilter, in unsigned long aposition); void unregisterfilter(in nsiprotocolproxyfilter afilter); constants constant value description resolve_non_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 re
turn immediately. so, calling resolve without this flag may result in locking up the calling thread for a lengthy period of time. by passing this flag to resolve, one can failover to asyncresolve to avoid locking up the calling thread if a pac query is required. when this flag is passed to resolve, resolve may throw the exception ns_base_stream_would_block to indicate that it failed due to th...
...ilover to asyncresolve to avoid locking up the calling thread if a pac query is required. when this flag is passed to resolve, resolve may throw the exception ns_base_stream_would_block to indicate that it failed due to this flag being present. methods resolve() deprecated since gecko 18 this method has been removed in firefox 18. use resolveasync instead previous doc this method re
turns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri. otherwise, this method re
turns 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. if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo i...
...xyinfo instance that identifies a proxy to be used for loading the given uri. otherwise, this method re
turns 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. if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance re
turned from resolve may be passed to the nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy. however, if the nsiproxyinfo type is "http", then it means that the given uri should be loaded using the http protocol handler, which also supports nsiproxiedprotocolhandler. nsiproxyinfo resolve( in nsiuri auri, in unsigned long ...
...And 4 more matches
nsISHEntry
am post data for the document. referreruri nsiuri referrer uri. refreshurilist nsisupportsarray saved refresh uri list for the content viewer. savelayoutstateflag boolean indicate whether layouthistorystate should be saved. statedata nsistructuredclonecontainer get/set data associated with this history state via a pushstate() call, serialized using structured clone. (prior to gecko 6.0 re
turned a json encoded string.) sticky boolean whether the content viewer is marked "sticky" windowstate nsisupports saved state of the global window object. methods addchildshell() saved child docshells corresponding to contentviewer. the child shells are restored as children of the parent docshell, in this order, when the parent docshell restores a saved presentation. append a child shell t...
...hild shells are restored as children of the parent docshell, in this order, when the parent docshell restores a saved presentation. append a child shell to the end of our list. void addchildshell( in nsidocshelltreeitem shell ); parameters shell childshellat() nsidocshelltreeitem childshellat( in long index ); parameters index the child shell at index; null if index is out of bounds. re
turn value clearchildshells() clear the child shell list. void clearchildshells(); parameters none. clone() nsishentry clone(); parameters none. re
turn value native code only!create additional ways to create an entry. void create( in nsiuri uri, in astring title, in nsiinputstream inputstream, in nsilayouthistorystate layouthistorystate, in nsisupports cachekey, in acstring contenttype...
...ccreation ); parameters uri title inputstream layouthistorystate cachekey contenttype owner docshellid dynamiccreation violates the xpcom interface guidelines forgeteditordata() gets the owning pointer to the editor data assosicated with this shistory entry. this forgets its pointer, so free it when you're done. nsdocshelleditordataptr forgeteditordata(); parameters none. ...
...And 4 more matches
Working with windows in chrome code
indowwatcher's methods. var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen", null); window object note the win variable in the above section, which is assigned the re
turn value of window.open. it can be used to access the opened window. the re
turn value of window.open (and similar methods) is a window object (usually chromewindow) – the same type as the window variable. technically speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the ...
...lly chromewindow) – the same type as the window variable. technically speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the window. so, for example, to access the dom document corresponding to the window, you can use win.document. note however, that the open() call re
turns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail. to overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. you can get a window object from a document using document.defaultview. content windows when a xul window contains a widget capable of disp...
...less in a different context). accessing content documents assume you have a document loaded in a <tabbrowser>, <browser>, or <iframe> element inside your document. you can use browser.contentdocument to access that document and browser.contentwindow to access the window object of that document. you should be aware of xpcnativewrappers when working with untrusted content. with xpcnativewrappers
turned on (which is the default in firefox 1.5+), your extension can safely access the dom of the content document, but not the content javascript. bypassing xpcnativewrapper to work with content javascript directly can lead to security problems. see interaction between privileged and non-privileged pages if you need to interact with the content page. the content shortcut in case of <browser type="...
...And 4 more matches
Drawing and Event Handling - Plugins
nt->embedprint.window contains the window in which the plug-in should print. on ms windows, note that the coordinates for the window rectangle are in twips format. for this reason, you need to convert the x - and y - coordinates using the windows api call dptolp when you output text. setting the window the browser calls the npp_setwindow function to set the window in which a plug-in draws or re
turns an error code. this window is valid for the life of the instance, or until npp_setwindow is called again with a different value. subsequent calls to npp_setwindow for a given instance usually mean that the window has been resized. if either window or window->window is null, the plug-in must not perform any additional graphics operations on the window and should free any associated resources. n...
...o a subwindow of the netscape window hierarchy. mac os the window->window field points to an np_port structure. getting information to receive information from the browser, the plug-in calls the npn_getvalue method. nperror npn_getvalue(npp instance, npnvariable variable, void *value); the instance parameter represents the current plug-in. unix and ms windows the queried information is re
turned in the variable parameter. this parameter is valid only for the unix and ms windows platforms. for unix, the values are either the current display (npnvxdisplay) or the application's context (npnvxtappcontext). for ms windows, the value is the native window on which the plug-in drawing occurs (npnvnetscapewindow). the value parameter contains the name of the plug-in. you can also use npn_getv...
...paint message making a plug-in opaque making a plug-in transparent creating pop-up menus and dialog boxes event handling for windowless plug-ins specifying that a plug-in is windowless to specify that a plug-in is windowless, use the npn_setvalue method. the instance parameter represents the current plug-in. the variable parameter contains plug-in information to set. the value parameter re
turns the name of the plug-in. to specify that a plug-in is windowless, use npn_setvalue with nppvpluginwindowbool as the value of variable and false as the value of value. the plug-in makes this call from its npp_new method. if a plug-in does not make this call, it is considered a windowed plug-in. plug-ins on mac os x are always windowless. nperror npp_new(npmimetype plugintype, ...
...And 4 more matches
Debugger.Script - Firefox Developer Tools
rmat if the instance refers to a jsscript, "js". if the instance refers to webassembly code, "wasm". function properties of the debugger.script prototype object the functions described below may only be called with a this value referring to a debugger.script instance; they may not be used as methods of other kinds of objects. getalloffsets() if the instance refers to a jsscript, re
turn an arrayl describing the relationship between bytecode instruction offsets and source code positions in this script.l is sparse, and indexed by source line number. if a source line numberline has no code, thenl has noline property. if there is code forline, then l[line] is an array of offsets of byte code instructions that are entry points to that line. for example, suppose we have a script for...
...t head has two entry points at offsets 5 and 20 (for the initialization, which is performed only once, and the loop test, which is performed at the start of each iteration); the third line has no code; and the fourth line begins at offset 10. if the instance refers to webassembly code, throw a typeerror. getallcolumnoffsets(): if the instance refers to a jsscript, re
turn an array describing the relationship between bytecode instruction offsets and source code positions in this script. unlike getalloffsets(), which re
turns all offsets that are entry points for each line, getallcolumnoffsets() re
turns all offsets that are entry points for each (line, column) pair. the elements of the array are objects, each of which describes a single entry point, and contains th...
...lling getallcolumnoffsets() on that code might yield an array like this: [{ linenumber: 0, columnnumber: 0, offset: 0 }, { linenumber: 1, columnnumber: 5, offset: 5 }, { linenumber: 1, columnnumber: 10, offset: 20 }, { linenumber: 3, columnnumber: 4, offset: 10 }] if the instance refers to webassembly code, throw a typeerror. getlineoffsets(line) if the instance refers to a jsscript, re
turn an array of bytecode instruction offsets representing the entry points to source lineline. if the script contains no executable code at that line, the array re
turned is empty. getoffsetlocation(offset) if the instance refers to a jsscript, re
turn an object describing the source code location responsible for the bytecode atoffset in this script. the object has the following properties: ...
...And 4 more matches
Cache.put() - Web APIs
rs to be added to the current cache object. often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } re
turn cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. note: cache.add/cache.addall do not cache responses with response.status values that are not in the 200 range, whereas cache.put lets you store any request/response pair. as a result, cache.add/cache.addall can't be used to store opaque responses, whereas cach...
...store any request/response pair. as a result, cache.add/cache.addall can't be used to store opaque responses, whereas cache.put can. syntax cache.put(request, response).then(function() { // request/response pair has been added to the cache }); parameters request the request object or url that you want to add to the cache. response the response you want to match up to the request. re
turn value a promise that resolves with undefined. note: the promise will reject with a typeerror if the url scheme is not http or https. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). i...
...r https. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). if so, serve that. ...
...And 4 more matches
CacheStorage.match() - Web APIs
the match() method of the cachestorage interface checks if a given request or url string is a key for a stored response. this method re
turns a promise for a response, or a promise which resolves to undefined if no match is found. you can access cachestorage through the global caches property. cache objects are searched in creation order. note: caches.match() is a convenience method. equivalent functionality is to call cache.match() on each cache (in the order re
turned by caches.keys()) until a response is re
turned. syntax caches.match(request, options).then(function(response) { // do something with the response }); parameters request the request you want to match. this can be a request object or a url string. options optional an object whose properties control how matching is...
...y only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header or not. it defaults to false. cachename: a domstring that represents a specific cache to search within. re
turn value a promise that resolves to the matching response. if no matching response to the specified request is found, the promise resolves with undefined. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachest...
...ndefined. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). if so, serve that. if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and re
turn a clone of the default network request using re
turn response.clone(). the last is necessary because put() consumes the response body. if this fails (e.g., because the network is down), re
turn a fallback response. self.addeventlistener('fetch', function(event) { event.respondwith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of ...
...And 4 more matches
DOMLocator - Web APIs
methods this interface neither implements, nor inherits, any method. ...
... methods this interface neither implements, nor inherits, any method. ...
... methods this interface neither implements, nor inherits, any method. ...
...And 4 more matches
EventTarget.addEventListener() - Web APIs
s not always been optional. ideally, you should include it for the widest possible browser compatibility. wantsuntrusted a firefox (gecko)-specific parameter. if true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). this parameter is useful for code found in add-ons, as well as the browser itself. ...
...gular web pages). this parameter is useful for code found in add-ons, as well as the browser itself. re
turn value undefined usage notes the event listener callback the event listener can be specified as either a callback function or an object that implements eventlistener, whose handleevent() method serves as the callback function. the callback function itself has the same parameters and re
turn value as the handleevent() method; that is, the callback accepts a single parameter: an object based on event describing the event that has occurred, and it re
turns nothing. for example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look like this: function eventhandler(event) { if (event.type == 'fullscreenchange') { /* handle a full...
...ario intelligently. you can do this by using feature detection for each of the options you're interested in. for example, if you want to check for the passive option: let passivesupported = false; try { const options = { get passive() { // this function will be called when the browser // attempts to access the passive property. passivesupported = true; re
turn false; } }; window.addeventlistener("test", null, options); window.removeeventlistener("test", null, options); } catch(err) { passivesupported = false; } this creates an options object with a getter function for the passive property; the getter sets a flag, passivesupported, to true if it gets called. that means that if the browser checks the value of the passive property on the op...
...And 4 more matches
FileSystemEntrySync - Web APIs
true if filesystementrysync is a directory. isfile readonly boolean true if the filesystementrysync is a file. name readonly domstring the name of the entry, excluding the path leading to it. methods getmetadata() look up metadata about this entry. [ todo: specify what kind of metadata ] metadata getmetada () raises (fileexception); parameter none re
turns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist. invalid_state_err the filesystemsync is no longer valid for some reason besides being deleted. moveto() move an entry to a different location on the file system. moving a file over an existing file...
...to a path occupied by a file move any element to a path occupied by a directory that is not empty. filesystementrysync moveto ( in directoryentrysync parent, optional domstring newname ) raises (fileexception); parameters parent the directory to which to move the entry. newname the new name of the entry. if you do not specify a name, the browser preserves the entry's current name. re
turns filesystementrysync an object that represents an entry in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the name supplied is invalid, because at least one of the characters is reserved or illegal. examples include a backslash (\), dot (.), and two dots (..). not_found_err ...
...s of the directory are copied. you cannot change this behavior. files are simply duplicated. void copyto ( in directoryentrysync parent, optional domstring newname ) raises (fileexception); parameters parent the directory where you want the entry to move to. newname the new name of the entry. if you do not specify a name, the browser preserves the filesystementrysync's current name. re
turns filesystementrysync an object that represents an entry in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the name supplied is invalid, because at least one of the characters is reserved or illegal. examples include a backslash (\), dot (.), and two dots (..). not_found_err ...
...And 4 more matches
Fullscreen API - Web APIs
as fscreen for vendor agnostic access to the fullscreen api. interfaces the fullscreen api has no interfaces of its own. instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. these are listed in the following sections. methods the fullscreen api adds methods to the document and element interfaces to allow
turning off and on full-screen mode. methods on the document interface document.exitfullscreen() requests that the user agent switch from full-screen mode back to windowed mode. re
turns a promise which is resolved once full-screen mode has been completely shut off. methods on the element interface element.requestfullscreen() asks the user agent to place the specified element (and, by extens...
... properties the document interface provides properties that can be used to determine if full-screen mode is supported and available, and if full-screen mode is currently active, which element is using the screen. ...
.... document.fullscreenenabled the fullscreenenabled property tells you whether or not it is possible to engage full-screen mode. this is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported). event handlers the fullscreen api defines two events which can be used to detect when full-screen mode is
turned on and off, as well as when errors occur during the process of changing between full-screen and windowed modes. event handlers for these events are available on the document and element interfaces. note: these event handler properties are not available as html content attributes. in other words, you cannot specify event handlers for fullscreenchange and fullscreenerror in the html content. th...
...And 4 more matches
Using the Gamepad API - Web APIs
the focused window, gamepaddisconnected: window.addeventlistener("gamepaddisconnected", function(e) { console.log("gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id); }); the gamepad's index property will be unique per-device connected to the system, even if multiple controllers of the same type are used. the index property also functions as the index into the array re
turned by navigator.getgamepads(). var gamepads = {}; function gamepadhandler(event, connecting) { var gamepad = event.gamepad; // note: // gamepad === navigator.getgamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.addeventlistener("gamepadconnected", function(e) { gamepadhandler(e, true); }, false...
...w.addeventlistener("gamepaddisconnected", function(e) { gamepadhandler(e, false); }, false); this previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later. querying the gamepad object as you can see, the gamepad events discussed above include a gamepad property on the event object, which re
turns a gamepad object. we can use this in order to determine which gamepad (i.e., its id) had caused the event, since multiple gamepads might be connected at once. we can do much more with the gamepad object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. doing so is often desirable for games or other interactive web pages tha...
...r games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires. performing such checks tends to involve using the gamepad object in conjunction with an animation loop (e.g., requestanimationframe), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads. the navigator.getgamepads() method re
turns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be re
turned if there are no gamepads connected.) this can then be used to get the same information. for example, the first code example above you be rewritten as shown below: window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.game...
...And 4 more matches
HTMLFormElement - Web APIs
automatically populated by the browser. htmlformelement.novalidate a boolean reflecting the value of the form's novalidate html attribute, indicating whether the form should not be validated. named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named action will have its action property re
turn that input instead of the form's action html attribute). methods this interface also inherits methods from its parent, htmlelement. checkvalidity() re
turns true if the element's child controls are subject to constraint validation and satisfy those contraints; re
turns false if some controls do not satisfy their constraints. fires an event named invalid at any control that does not satisfy it...
...ue if the element's child controls are subject to constraint validation and satisfy those contraints; re
turns false if some controls do not satisfy their constraints. fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. it is up to the programmer to decide how to respond to false. reportvalidity() re
turns true if the element's child controls satisfy their validation constraints. when false is re
turned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. requestsubmit() requests that the form be submitted using the specified submit button and its corresponding configuration. reset() resets the form to its initial state. submit() submit...
...hen a form is reset. also available via the onreset property. submit the submit event fires when a form is submitted. also available via the onsubmit property. usage notes obtaining a form element object to obtain an htmlformelement object, you can use a css selector with queryselector(), or you can get a list of all of the forms in the document using its forms property. document.forms re
turns an array of htmlformelement objects listing each of the forms on the page. you can then use any of the following syntaxes to get an individual form: document.forms[index] re
turns the form at the specified index into the array of forms. document.forms[id] re
turns the form whose id is id. document.forms[name] re
turns the form whose name attribute's value is name. accessing the form's ele...
...And 4 more matches
HTMLImageElement - Web APIs
it accepts optional width and height parameters. when called without parameters, new image() is equivalent to calling document.createelement("img"). properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus i...
...and height parameters. when called without parameters, new image() is equivalent to calling document.createelement("img"). properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. htmlimageelement.complete read only re
turns a boolean that is true if the browser has finished fetching the image, whether successful or not. that means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be null if cors is not used. htmlimageelement.curre...
...true if the browser has finished fetching the image, whether successful or not. that means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be null if cors is not used. htmlimageelement.currentsrc read only re
turns a usvstring representing the url from which the currently displayed image was loaded. this may change as the image is adjusted due to changing conditions, as directed by any media queries 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 permit...
...And 4 more matches
HTMLMediaElement.play() - Web APIs
exceptions the promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
... exceptions the promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). ...
...is resolved when playback has been successfully started. failure to begin playback for any reason, such as permission issues, result in the promise being rejected. syntax var promise = htmlmediaelement.play(); parameters none. re
turn value a promise which is resolved when playback has been started, or is rejected if for any reason playback cannot be started. note: older browsers may not re
turn a value from play(). exceptions the promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). possible errors include: notallowederror the user agent (browser) or operating system doesn't allow playback of media in the current context or situation. this may happen, for example, if the browser req...
...And 4 more matches
HTMLSelectElement - Web APIs
ocument can have this attribute specified. htmlselectelement.disabled a boolean reflecting the disabled html attribute, which indicates whether the control is disabled. if it is disabled, it does not accept clicks. htmlselectelement.formread only an htmlformelement referencing the form that this element is associated with. if the element is not associated with of a <form> element, then it re
turns null. htmlselectelement.labelsread only a nodelist of <label> elements associated with the element. htmlselectelement.length an unsigned long the number of <option> elements in this select element. htmlselectelement.multiple a boolean reflecting the multiple html attribute, which indicates whether multiple items can be selected. htmlselectelement.name a domstring reflecting the name htm...
...ionsread only an htmlcollection representing the set of <option> elements that are selected. htmlselectelement.size a long reflecting the size html attribute, which contains the number of visible items in the control. the default is 1, unless multiple is true, in which case it is 4. htmlselectelement.typeread only a domstring represeting the form control's type. when multiple is true, it re
turns "select-multiple"; otherwise, it re
turns "select-one". htmlselectelement.validationmessageread only a domstring representing a localized message that describes the validation constraints that the control does not satisfy (if any). this attribute is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. htmlselect...
...onstraints that the control does not satisfy (if any). this attribute is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. htmlselectelement.validityread only a validitystate reflecting the validity state that this control is in. htmlselectelement.value a domstring reflecting the value of the form control. re
turns the value property of the first selected option element if there is one, otherwise the empty string. htmlselectelement.willvalidateread only a boolean that indicates whether the button is a candidate for constraint validation. it is false if any conditions bar it from constraint validation. methods this interface inherits the methods of htmlelement, and of element and node. htmlselectel...
...And 4 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
as each context is created, it is placed on the execution context stack. when it exits, the context is remov...
...n it exits, the context is removed from the context stack. upon starting the program, the global context is created. when greetuser("mike") is reached, a context is created for the greetuser() function; this execution context is pushed onto the execution context stack. when greetuser() calls localgreeting(), another context is created to run that function. when this function re
turns, the context for localgreeting() is removed from the execution stack and destroyed. program execution resumes with the next context found on the stack, which is greetuser(); this function resumes execution where it left off. the greetuser() function re
turns and its context is removed from the stack and destroyed. when greetuser("teresa") is reached, a context is created for it a...
... stack, which is greetuser(); this function resumes execution where it left off. the greetuser() function re
turns and its context is removed from the stack and destroyed. when greetuser("teresa") is reached, a context is created for it and pushed onto the stack. when greetuser() calls localgreeting(), another context is created to run that function. when this function re
turns, the context for localgreeting() is removed from the execution stack and destroyed. greetuser() continues to execute where it left off. the greetuser() function re
turns and its context is removed from the stack and destroyed. when greetuser("veronica") is reached, a context is created for it and pushed onto the stack. when greetuser() calls localgreeting(), another con...
...And 4 more matches
IDBObjectStoreSync - Web APIs
snapshot_read 2 any read operations must access a snapshot view of the data, which cannot change once it is created. methods add() stores the given value into this object store, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters re
turns exceptions this method can raise a idbdatabaseexception with the following codes: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the va...
...ing to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. data_err if this object store uses out-of-line keys, and the key parameter was not passed. serial_err if the data being stored could not be serialized by the internal structured cloning algorithm. ...
...hm. createindex() creates and re
turns a new index with the given name in the connected database. idbindexsync createindex ( in domstring name, in domstring keypath, in optional boolean unique ); parameters name the name of a new index. keypath the key path used by the new index. unique if true, keys in the index must be unique; if false, duplicate keys are allowed. re
turns idbindexsync an object to access the newly created index. get() retrieves and re
turns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. re
turns any the value retrieved from the object store. exceptions this method can r...
...And 4 more matches
Timing element visibility with the Intersection Observer API - Web APIs
rticular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site. there's a good reason why the notion of tracking visibility of ads is being used in this example. it
turns out that one of the most common uses of flash or other script in advertising on the web is to record how long each ad is visible, for the purpose of billing and payment of revenues. without the intersection observer api, this winds up being done using intervals and timeouts for each individual ad, or other techniques that tend to slow the page down. using this api lets everything get streamlined...
...iv> this is the framework for the entire site. at the top is the site's header region, contained within a <header> block. below that, we define the site's sidebar as a list of links within an <aside> block. finally comes the main body. we start with an empty <main> element here. this box will be populated using script later. styling the site with css with the structure of the site defined, we
turn to the styling for the site. let's look at the style for each component of the page individually. the basics we provide styles for the <body> and <main> elements to define the site's background as well as the grid the various parts of the site will be placed in. body { font-family: "open sans", "arial", "helvetica", sans-serif; background-color: aliceblue; } .wrapper { display: grid; ...
...'ll use to track the ads currently visible on the screen. previouslyvisibleads used to temporarily store the list of visible ads while the document is not visible (for example, if the user has tabbed to another page). adobserver will hold our intersectionobserver used to track the intersection between the ads and the <main> element's bounds. refreshintervalid used to store the interval id re
turned by setinterval(). this interval will be used to trigger our periodic refreshes of the ads' content. setting up to set things up, we run the startup() function below when the page loads: window.addeventlistener("load", startup, false); function startup() { contentbox = document.queryselector("main"); document.addeventlistener("visibilitychange", handlevisibilitychange, false); let o...
...And 4 more matches
KeyboardEvent.code - Web APIs
the keyboardevent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). in other words, this property re
turns a value that isn't altered by keyboard layout or the state of the modifier keys. if the input device isn't a physical keyboard, but is instead a virtual keyboard or accessibility device, the re
turned value will be set by the browser to match as closely as possible to what would happen with a physical keyboard, to maximize compatibility between physical and virtual input devices. this property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys; this is especially common when writing code to handle input for games that simulate ...
...handle input for games that simulate a gamepad-like environment using keys on the keyboard. be aware, however, that you can't use the value reported by keyboardevent.code to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed. for example, the code re
turned is "keyq" for the q key on a qwerty layout keyboard, but the same code value also represents the ' key on dvorak keyboards and the a key on azerty keyboards. that makes it impossible to use the value of code to determine what the name of the key is to users if they're not using an anticipated keyboard layout. to determine what character corresponds with the key event, use the keyboardevent.key...
... background-color: black; width: 400px; height: 400px; } #spaceship { fill: orange; stroke: red; stroke-width: 2px; } javascript the first section of the javascript code establishes some variables we'll be using. shipsize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moverate and
turnrate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. angle is the current amount of rotation applied to the ship, in degrees; it starts at 0° (pointing straight up). finally, spaceship is set to refer to the element with the id "spaceship", which is the svg polygon representing t...
...And 4 more matches
MediaStreamTrack - Web APIs
lse if it is disabled, that is not rendering the media source stream but silence and blackness. if the track has been disconnected, this value can be changed but has no more effect. note: you can implement standard "mute" functionality by setting enabled to false. the muted property refers to a condition in which there's no media because of a technical issue. mediastreamtrack.id read only re
turns a domstring containing a unique identifier (guid) for the track; it is generated by the browser. mediastreamtrack.isolated read only re
turns a boolean value which is true if the track is isolated; that is, the track cannot be accessed by the document that owns the mediastreamtrack. this happens when the peeridentity property is set, or if the track comes from a cross-origin source. mediastre...
...unique identifier (guid) for the track; it is generated by the browser. mediastreamtrack.isolated read only re
turns a boolean value which is true if the track is isolated; that is, the track cannot be accessed by the document that owns the mediastreamtrack. this happens when the peeridentity property is set, or if the track comes from a cross-origin source. mediastreamtrack.kind read only re
turns a domstring set to "audio" if the track is an audio track and to "video", if it is a video track. it doesn't change if the track is deassociated from its source. mediastreamtrack.label read only re
turns a domstring containing a user agent-assigned label that identifies the track source, as in "internal microphone". the string may be left empty and is empty as long as no source has been connec...
... if the track is deassociated from its source. mediastreamtrack.label read only re
turns a domstring containing a user agent-assigned label that identifies the track source, as in "internal microphone". the string may be left empty and is empty as long as no source has been connected. when the track is deassociated from its source, the label is not changed. mediastreamtrack.muted read only re
turns a boolean value indicating whether the track is unable to provide media data due to a technical issue. note: you can implement standard "mute" functionality by setting enabled to false, and unmute the media by setting it back to true again. ...
...And 4 more matches
Capabilities, constraints, and settings - Web APIs
. this isn't always necessary, since any that aren't known will simply be ignored when you specify them—but if you have any that you can't get by without, you can start by checking to be sure they're on the list. once the script knows whether the property or properties it wishes to use are supported, it can then check the capabilities of the api and its implementation by examining the object re
turned by the track's getcapabilities() method; this object lists each supported constraint and the values or range of values which are supported. finally, the track's applyconstraints() method is called to configure the api as desired by specifying the values or ranges of values it wishes to use for any of the constrainable properties about which it has a preference. the track's getconstraints() me...
...he track's getcapabilities() method; this object lists each supported constraint and the values or range of values which are supported. finally, the track's applyconstraints() method is called to configure the api as desired by specifying the values or ranges of values it wishes to use for any of the constrainable properties about which it has a preference. the track's getconstraints() method re
turns the set of constraints passed into the most recent call to applyconstraints(). this may not represent the actual current state of the track, due to properties whose requested values had to be adjusted and because platform default values aren't represented. for a complete representation of the track's current configuration, use getsettings(). in the media stream api, both mediastream and medias...
...st a width no smaller than 640 and no larger than 1920 (but preferably 1920), a height no smaller than 400 (but ideally 1080), an aspect ratio of 16:9 (1.777777778), and a frame rate no greater than 30 frames per second. in addition, the only acceptable input device is a camera facing the user (a "selfie cam"). if the width, height, framerate, or facingmode constraints can't be met, the promise re
turned by applyconstraints() will be rejected. constraints which are specified using any or all of max, min, or exact are always treated as mandatory. if any constraint which uses one or more of those can't be met when calling applyconstraints(), the promise will be rejected. advanced constraints so-called advanced constraints are created by adding an advanced property to the constraint set; this...
...And 4 more matches
PaymentRequest.show() - Web APIs
ntrequest.show() method can't just be initiated at any time. it may only be called while handling events that represent user interactions, such as click, keyup, or the like. only one payment request can be in the process of being handled at once, across all documents. once one paymentrequest's show() method has been called, any other call to show() will by rejected with an aborterror until the re
turned promise has been concluded, either by being fulfilled with a paymentresponse indicating the results of the payment request, or by being rejected with an error. note: in reality, despite the fact that the specification says this can't be done, some browsers, including firefox, support multiple active payment requests at a time. if your architecture doesn't necessarily have all of the data re...
...mise = paymentrequest.show(detailspromise); parameters detailspromise optional an optional promise that you can provide if your architecture requires that the payment request's details need to be updated between instantiating the payment interface and the user beginning to interact with it. the promise should resolve with a paymentdetailsupdate object containing the updated information. re
turn value a promise that eventually resolves with a paymentresponse. the promise is resolved when the user accepts the payment request (such as by clicking a "pay" button in the browser's payment sheet). exceptions aborterror the re
turned promise rejects with an aborterror if the user agent is already showing a payment panel. only one payment panel may be visible at a time across all document...
...)); const repsonse = await payrequest.show(); await validateresponse(response); } catch(err) { /* handle the error; aborterror usually means a user cancellation */ } } in this code, the methods checkaddress() and checkshipping(), respectively, check the shipping address and the shipping option changes and supply in response either a paymentdetailsupdate object or a promise to re
turn one; this object contains the fields in the paymentresponse which have been or need to be changed. the validateresponse() method, below, is called once show() re
turns, in order to look at the re
turned response and either submit the payment or reject the payment as failed: async function validateresponse(response) { try { if (await checkallvalues(response)) { await response.complete(...
...And 4 more matches
Using the Screen Capture API - Web APIs
that recent versions of the webrtc adapter.js shim include implementations of getdisplaymedia() to enable screen sharing on browsers that support it but do not implement the current standard api. this works with at least chrome, edge, and firefox. ...
...ediadevices.getdisplaymedia(), which re
turns a promise that resolves 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); } re
turn 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. ...
...ediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } re
turn 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; re
turn navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); re
turn null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share. both of these implementations of startcapture() re
turn the mediastream containing the captured display imagery. see options and constraints, b...
...And 4 more matches
Selection - Web APIs
selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button. anchor and focus should not be confused with the start and end positions of a selection. the anchor can be placed before the focus or vice-versa, depending on the direction you made your selection. properties selection.anchornoderead only re
turns the node in which the selection begins. can re
turn null if selection never existed in the document (e.g., an iframe that was never clicked on). selection.anchoroffsetread only re
turns a number representing the offset of the selection's anchor within the anchornode. if anchornode is a text node, this is the number of characters within anchornode preceding the anchor. if anchornode is an elemen...
...iframe that was never clicked on). selection.anchoroffsetread only re
turns a number representing the offset of the selection's anchor within the anchornode. if anchornode is a text node, this is the number of characters within anchornode preceding the anchor. if anchornode is an element, this is the number of child nodes of the anchornode preceding the anchor. selection.focusnoderead only re
turns the node in which the selection ends. can re
turn null if selection never existed in the document (for example, in an iframe that was never clicked on). selection.focusoffsetread only re
turns a number representing the offset of the selection's anchor within the focusnode. if focusnode is a text node, this is the number of characters within focusnode preceding the focus. if focusnode is an elem...
...in an iframe that was never clicked on). selection.focusoffsetread only re
turns a number representing the offset of the selection's anchor within the focusnode. if focusnode is a text node, this is the number of characters within focusnode preceding the focus. if focusnode is an element, this is the number of child nodes of the focusnode preceding the focus. selection.iscollapsedread only re
turns a boolean indicating whether the selection's start and end points are at the same position. selection.rangecountread only re
turns the number of ranges in the selection. selection.typeread only re
turns a domstring describing the type of the current selection. methods selection.addrange() a range object that will be added to the selection. selection.collapse() collapses the current s...
...And 4 more matches
SubtleCrypto.sign() - Web APIs
you can use the corresponding subtlecrypto.verify() method to verify the signature. ...
..., pass an rsapssparams object. to use ecdsa, pass an ecdsaparams object. to use hmac, pass the string "hmac" or an object of the form { "name": "hmac" }. key is a cryptokey object containing the key to be used for signing. if algorithm identifies a public-key cryptosystem, this is the private key. data is an arraybuffer or arraybufferview object containing the data to be signed. re
turn value signature is a promise that fulfills with an arraybuffer containing the signature. exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the signing key is not a key for the request signing algorithm or when trying to use an algorithm that is either unknown or isn't suitable for signing. supported algorithms the web crypt...
...gning and the public key for verification. these systems all use a digest algorithm to hash the message to a short fixed size before signing. the choice of digest algorithm is passed into the generatekey() or importkey() functions. the fourth algorithm — hmac — uses the same algorithm and key for signing and for verification: this means that the verification key must be kept secret, which in
turn means that this algorithm is not suitable for many signature use cases. it can be a good choice however when the signer and verifier are the same entity. rsassa-pkcs1-v1_5 the rsassa-pkcs1-v1_5 algorithm is specified in rfc 3447. rsa-pss the rsa-pss algorithm is specified in rfc 3447. it's different from rsassa-pkcs1-v1_5 in that it incorporates a random salt in the signature operation, so t...
...And 4 more matches
Touch - Web APIs
amount of pressure placed on the surface, the force value will always be 0. this may also be the case for radiusx and radiusy; if the hardware reports only a single point, these values will be 1. constructor touch() creates a touch object. properties this interface has no parent, and doesn't inherits or implements any other property. ...
...erface has no parent, and doesn't inherits or implements any other property. basic properties touch.identifier read only re
turns a unique identifier for this touch object. a given touch point (say, by a finger) will have the same identifier for the duration of its movement around the surface. this lets you ensure that you're tracking the same touch all the time. touch.screenx read only re
turns the x coordinate of the touch point relative to the left edge of the screen. touch.screeny read only re
turns the y coordinate of the touch point relative to the top edge of the screen. ...
...ave the same identifier for the duration of its movement around the surface. this lets you ensure that you're tracking the same touch all the time. touch.screenx read only re
turns the x coordinate of the touch point relative to the left edge of the screen. touch.screeny read only re
turns the y coordinate of the touch point relative to the top edge of the screen. touch.clientx read only re
turns the x coordinate of the touch point relative to the left edge of the browser viewport, not including any scroll offset. touch.clienty read only re
turns the y coordinate of the touch point relative to the top edge of the browser viewport, not including any scroll offset. touch.pagex read only re
turns the x coordinate of the touch point relative to the left edge of the document. unlike clien...
...And 4 more matches
USBDevice - Web APIs
ties are usbdevice.usbversionmajor and usbdevice.usbversionsubminor. usbdevice.usbversionsubminor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. usbdevice.vendorid read only the official usg.org-assigned vendor id. ...
...three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. usbdevice.vendorid read only the official usg.org-assigned vendor id. methods usbdevice.claiminterface() re
turns a promise that resolves when the requested interface is claimed for exclusive access. usbdevice.clearhalt() re
turns a promise that resolves when a halt condition is cleared. usbdevice.controltransferin() re
turns a promise that resolves with a usbtransferinresult when a command or status operation has been transmitted to the usb device. usbdevice.controltransferout() re
turns a promise that resolves with a usbtransferoutresult when a command or status operation has been transmitted from the usb device. usb...
...esolves when a halt condition is cleared. usbdevice.controltransferin() re
turns a promise that resolves with a usbtransferinresult when a command or status operation has been transmitted to the usb device. usbdevice.controltransferout() re
turns a promise that resolves with a usbtransferoutresult when a command or status operation has been transmitted from the usb device. usbdevice.close() re
turns a promise that resolves when all open interfaces are released and the device session has ended. usbdevice.isochronoustransferin() re
turns a promise that resolves with a usbisochronousintransferresult when time sensitive information has been transmitted to the usb device. ...
...And 4 more matches
WebRTC connectivity - Web APIs
er. the caller receives the answer. the caller calls rtcpeerconnection.setremotedescription() to set the answer as the remote description for its end of the call. it now knows the configuration of both peers. media begins to flow as configured. pending and current descriptions taking one step deeper into the process, we find that localdescription and remotedescription, the properties which re
turn these two descriptions, aren't as simple as they look. because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a new format but not actually switch to it until it's accepted by the other peer. for that reason, webrtc uses pending and current descriptions. the current description (which is r...
...these two descriptions, aren't as simple as they look. because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a new format but not actually switch to it until it's accepted by the other peer. for that reason, webrtc uses pending and current descriptions. ...
...her peer. for that reason, webrtc uses pending and current descriptions. the current description (which is re
turned by the rtcpeerconnection.currentlocaldescription and rtcpeerconnection.currentremotedescription properties) represents the description currently in actual use by the connection. this is the most recent connection that both sides have fully agreed to use. the pending description (re
turned by rtcpeerconnection.pendinglocaldescription and rtcpeerconnection.pendingremotedescription) indicates a description which is currently under consideration following a call to setlocaldescription() or setremotedescription(), respectively. ...
...And 4 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
to see what the other peer sees. handling incoming tracks we next need to set up a handler for track events to handle inbound video and audio tracks that have been negotiatied to be received by this peer connection. to do this, we implement the the rtcpeerconnection's ontrack event handler. pc.ontrack = ({track, streams}) => { track.onunmute = () => { if (remotevideo.srcobject) { re
turn; } remotevideo.srcobject = streams[0]; }; }; when the track event occurs, this handler executes. using destructuring, the rtctrackevent's track and streams properties are extracted. the former is either the video track or the audio track being received. the latter is an array of mediastream objects, each representing a stream containing this track (a track may in rare cases belong to ...
...time a message arrives from the signaling server. ...
...d a description, we prepare to respond to the incoming offer or answer. first, we check to make sure we're in a state in which we can accept an offer. if the connection's signaling state isn't stable or if our end of the connection has started the process of making its own offer, then we need to look out for offer collision. if we're the impolite peer, and we're receiving a colliding offer, we re
turn without setting the description, and instead set ignoreoffer to true to ensure we also ignore all candidates the other side may be sending us on the signaling channel belonging to this offer. doing so avoids error noise since we never informed our side about this offer. if we're the polite peer, and we're receiving a colliding offer, we don't need to do anything special, because our existing off...
...And 4 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
iew of around 135° (about 2.356 radians) and a vertical fov of about 180° (π or around 3.142 radians). making the camera's fov smaller reduces the arc that will be included in the viewport, thus enlarging that content when rendered to the view. there are differences between this and an optical zoom effect, but the result is generally close enough to get the job done. ...
... the perspective matrix encapsulates the field of view (technically, this is the vertical field of view), aspect ratio, and th...
...ns and computing the aspect ratio of the xrviewport specified by the viewport parameter, this function uses the glmatrix library's mat4.perspective() function to compute the perspective matrix. the perspective matrix encapsulates the field of view (technically, this is the vertical field of view), aspect ratio, and the near and far clipping planes within the 4x4 matrix transform, which is then re
turned to the caller. the near clipping plane is the distance in meters to a plane parallel to the display surface closer than which nothing gets drawn. any vertices which lie on the same side of that plane as the camera are not drawn. conversely, the far clipping plane is the distance in meters to a plane beyond which no vertices are drawn. to zoom using a scaling factor or percentage, you can map ...
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
et our release sweepenv.gain.linearramptovalueattime(0, audioctx.currenttime + sweeplength - releasetime); osc.connect(sweepenv).connect(audioctx.destination); osc.start(); osc.stop(audioctx.currenttime + sweeplength); } note: we'll talk about the property baseaudiocontext.currenttime later, so don't worry if you're unsure of it for now. all you really need to know is that it re
turns the time we are at right now. the "pulse" — low frequency oscillator modulation great, now we've got our sweep! let's move on and take a look at that nice pulse sound. we can achieve this with a basic oscillator, modulated with a second oscillator. initial oscillator we'll set up our first oscillatornode the same way as our sweep sound, except we won't use a wavetable to set a bespoke wav...
... in the data we've created: let noise = audioctx.createbuffersource(); noise.buffer = buffer; if we connect this through our audio graph and play it — noise.connect(audioctx.destination); noise.start(); you'll notice that it's pretty hissy or tinny. we've created white noise, that's how it should be. our values are running from -1 to 1, which means we have peaks of all frequencies, which in
turn is actually quite dramatic and piercing. we could modify the function to run values from 0.5 to -0.5 or similar to take the peaks off and reduce the discomfort, however, where's the fun in that? let's route the noise we've created through a filter. adding a biquad filter to the mix we want something in the range of pink or brown noise. we want to cut off those high frequencies and possibly some...
...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); re
turn 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 fi...
...And 4 more matches
Example and tutorial: Simple synth keyboard - Web APIs
ng the waveform to use when the user selects "custom" from the waveform picker. sineterms and cosineterms will be used to store the data for generating the waveform; each will contain an array that's generated when the user chooses "custom". creating the note table the createnotetable() function builds the array notefreq to contain an array of objects representing each octave. each octave, in
turn, has one named property for each note in that octave; the property's name is the note's name (such as "c#" to represent c-sharp), and the value is the frequency, in hertz, of that note. function createnotetable() { let notefreq = []; for (let i=0; i< 9; i++) { notefreq[i] = []; } notefreq[0]["a"] = 27.500000000000000; notefreq[0]["a#"] = 29.135235094880619; notefreq[0]["b"] = 30...
...each octave object has named properties in it where the property name is the name of the note (such as "c#" to represent c-sharp) and the property's value is the note's frequency in hertz. in part, the resulting object looks like this: octave notes 0 "a" ⇒ 27.5 "a#" ⇒ 29...
...y for a given note in a particular octave quite easily. if we want the frequency for the note g# in octave 1, we simply use notefreq[1]["g#"] and get the value 51.9 as a result. the values in the example table above have been rounded to two decimal places. this polyfill stands in when object.entries() doesn't exist. if (!object.entries) { object.entries = function entries(o) { re
turn reduce(keys(o), (e, k) => concat(e, typeof k === 'string' && isenumerable(o, k) ? [[k, o[k]]] : []), []); }; } building the keyboard the setup() function is responsible for building the keyboard and preparing the app to play music. function setup() { notefreq = createnotetable(); volumecontrol.addeventlistener("change", changevolume, false); mastergainnode = audiocontext.createga...
...And 4 more matches
WorkerNavigator - Web APIs
calling window.self.navigator. properties the workernavigator interface implements properties from the navigatorid, navigatorlanguage, navigatoronline, navigatordatastore, and navigatorconcurrenthardware interfaces. workernavigator.connectionread only provides a networkinformation object containing information about the network connection of a device. ...
...ore, and navigatorconcurrenthardware interfaces. workernavigator.connectionread only provides a networkinformation object containing information about the network connection of a device. workernavigator.locks read only re
turns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object. workernavigator.permissions read only re
turns a permissions object that can be used to query and update permission status of apis covered by the permissions api. navigator.storageread only re
turns a storagemanager interface for managing persistance permissions and estimating available storage. inherited properties navigatorid.appcodename read only always re
turns 'mozilla', in any browser. this property is kept only for compatib...
... update permission status of apis covered by the permissions api. navigator.storageread only re
turns a storagemanager interface for managing persistance permissions and estimating available storage. inherited properties navigatorid.appcodename read only always re
turns 'mozilla', in any browser. this property is kept only for compatibility purposes. navigatorid.appname read only re
turns the official name of the browser. do not rely on this property to re
turn the correct value. navigatorid.appversion read only re
turns the version of the browser as a string. do not rely on this property to re
turn the correct value. ...
...And 4 more matches
XRView - Web APIs
rendering into the correct half of the layer. if in the future it becomes possible for each view to render into a different layer, there would have to be changes made to the api, so it's safe for now to assume that all views will render into the same layer. examples preparing to render every view for a pose to draw eerything the user sees each frame requires iterating over the list of views re
turned by the xrviewerpose object's views list: for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // draw the scene; the eye being drawn is identified // by view.eye. } special view transforms there are a few special transforms that are used on the view while rendering and lighting a scene. mod...
...en transposing the model view matrix: mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); teleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes. the createteleporttransform() function re
turns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes. function applymousemovement(refspace) { if (!mouseyaw && !mousepitch && !axialdistance &&...
... current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes. function applymousemovement(refspace) { if (!mouseyaw && !mousepitch && !axialdistance && !transversedistance && !verticaldistance) { re
turn refspace; } // compute the quaternion used to rotate the image based // on the pitch and yaw. quat.identity(inverseorientation); quat.rotatex(inverseorientation, inverseorientation, -mousepitch); quat.rotatey(inverseorientation, inverseorientation, -mouseyaw); // compute the true "up" vector for our object. vec3.cross(vecx, vecy, cubeorientation); vec3.cross(vecy, cubeorient...
...And 4 more matches
<angle> - CSS: Cascading Style Sheets
it is used, for example, in <gradient>s and in some transform functions. 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 the <angle> data type consists of a <number> followed by one of the units listed below. as with all dimensions, there is no space between the unit literal and the number. the angle unit is optional after the number 0. optionally, it may be preceded by a single + or - sign. ...
...e is no space between the unit literal and the number. the angle unit is optional after the number 0. optionally, it may be preceded by a single + or - sign. positive numbers represent clockwise angles, while negative numbers represent counterclockwise angles. for static properties of a given unit, any angle can be represented by various equivalent values. for example, 90deg equals -270deg, and 1
turn equals 4
turn. for dynamic properties, like when applying an animation or transition, the effect will nevertheless be different. units deg represents an angle in degrees. one full circle is 360deg. examples: 0deg, 90deg, 14.23deg. grad represents an angle in gradians. one full circle is 400grad. examples: 0grad, 100grad, 38.8grad. rad represents an angle in radians. one full circle is 2π...
...ertheless be different. units deg represents an angle in degrees. one full circle is 360deg. examples: 0deg, 90deg, 14.23deg. grad represents an angle in gradians. one full circle is 400grad. examples: 0grad, 100grad, 38.8grad. rad represents an angle in radians. one full circle is 2π radians which approximates to 6.2832rad. 1rad is 180/π degrees. examples: 0rad, 1.0708rad, 6.2832rad. ...
...And 4 more matches
Adding captions and subtitles to HTML5 video - Developer guides
w the user to easily select which subtitle language they want to see. src is assigned a valid url pointing to the relevant webvtt subtitle file in each case. srclang indicates what language each subtitle files' contents are in. the default attribute is set on the english <track> element, indicating to the browser that this is the default subtitle file definition to use when subtitles have been
turned on and the user has not made a specific selection. in addition to adding the <track> elements, we have also added a new button to control the subtitles menu that we will build. as a consequence, the video controls now look as follows: <div id="video-controls" class="controls" data-state="hidden"> <button id="playpause" type="button" data-state="play">play/pause</button> <button id="sto...
...efine our own. browsers do vary as to what they support, so we will be attempting to bring a more unified ui to each browser where possible. there's more on browser compatibility issues later on. initial setup as with all the other buttons, one of the first things we need to do is store a handle to the subtitles' button: var subtitles = document.getelementbyid('subtitles'); we also initially
turn off all subtitles, in case the browser
turns any of them on by default: for (var i = 0; i < video.texttracks.length; i++) { video.texttracks[i].mode = 'hidden'; } the video.texttracks property contains an array of all the text tracks attached to the video. we loop through each one and set its mode to hidden. note: the webvtt api gives us access to all the text tracks that are defined for an...
... text tracks attached to the video. we loop through each one and set its mode to hidden. note: the webvtt api gives us access to all the text tracks that are defined for an html5 video using the <track> element. building a caption menu our aim is to use the subtitles button we added earlier to display a menu that allows users to choose which language they want the subtitles displayed in, or to
turn them off entirely. we have added the button, but before we make it do anything, we need to build the menu that goes with it. this menu is built dynamically, so that languages can be added or removed later by simply editing the <track> elements within the video's markup. all we need to do is to go through the video's texttracks, reading their properties and building the menu up from there: va...
...And 4 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
ce, a browser could integrate with a device's contacts list to autocomplete email addresses in an email input field. see values in the html autocomplete attribute for permitted values. the autocomplete attribute is valid on hidden, text, search, url, tel, email, date, month, week, time, datetime-local, number, range, color, and password. this attribute has no effect on input types that do not re
turn numeric or text data, being valid for all input types except checkbox, radio, file, or any of the button types. see the html autocomplete attribute for additional information, including information on password security and how autocomplete is slightly different for hidden than for other input types. autofocus a boolean attribute which, if present, indicates that the input should automatic...
...bility. the tooltip is an enhancement. see client-side validation for more information. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. note: the placeholder attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. see labels in <input>: the input (form input) element for more information. readonly a boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. the readonly ...
...icating whether or not autocorrect is on or off. safari only. incremental whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. webkit and blink only (safari, chrome, opera, etc.). mozactionhint a string indicating the type of action that will be taken when the user presses the enter or re
turn key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. firefox for android only. orient sets the orientation of the range slider. firefox only. results the maximum number of items that should be displayed in the drop-down list of previous search queries. safari only. webkitdirectory a boolean indicating w...
...And 4 more matches
Inheritance and the prototype chain - JavaScript
s, its value is 4. console.log(o.d); // undefined // is there a 'd' own property on o? no, check its prototype. // is there a 'd' own property on o.[[prototype]]? no, check its prototype. // o.[[prototype]].[[prototype]] is object.prototype and there is no 'd' property by default, check its prototype. // o.[[prototype]].[[prototype]].[[prototype]] is null, stop searching, // no property found, re
turn undefined. code link setting a property to an object creates an own property. the only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter. inheriting "methods" javascript does not have "methods" in the form that class-based languages define them. in javascript, any function can be added to an object in the form of a property. ...
... can be added to an object in the form of a property. an inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding). when an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property. var o = { a: 2, m: function() { re
turn this.a + 1; } }; console.log(o.m()); // 3 // when calling o.m in this case, 'this' refers to o var p = object.create(o); // p is an object that inherits from o p.a = 4; // creates a property 'a' on p console.log(p.m()); // 5 // when p.m is called, 'this' refers to p. // so when p inherits the function m of o, // 'this.a' means p.a, the property 'a' of p using prototypes in javascript le...
...rties. all functions have a special property named prototype. please note that the code below is free-standing (it is safe to assume there is no other javascript on the webpage other than the below code). for the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below javascript code, and run it by pressing the enter/re
turn key. (the console is included in most web browser's developer tools. more information is available for firefox developer tools, chrome devtools, and edge devtools.) function dosomething(){} console.log( dosomething.prototype ); // it does not matter how you declare the function, a // function in javascript will always have a default // prototype property. // (ps: there is one exception that ...
...And 4 more matches
getter - JavaScript
n/interactive-examples and send us a pull request. syntax {get prop() { ... } } {get [expression]() { ... } } parameters prop the name of the property to bind to the given function. expression starting with ecmascript 2015, you can also use expressions for a computed property name to bind to the given function. description sometimes it is desirable to allow access to a property that re
turns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. in javascript, this can be accomplished with the use of a getter. it is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to...
... setter functions must now have exactly zero or one arguments for more information); it must not appear in an object literal with another get or with a data entry for the same property ({ get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden). examples defining a getter on new objects in object initializers this will create a pseudo-property latest for object obj, which will re
turn the last array item in log. const obj = { log: ['example','test'], get latest() { if (this.log.length === 0) re
turn undefined; re
turn this.log[this.log.length - 1]; } } console.log(obj.latest); // "test" note that attempting to assign a value to latest will not change it. deleting a getter using the delete operator if you want to remove the getter, you can just delete it: dele...
...ting to assign a value to latest will not change it. deleting a getter using the delete operator if you want to remove the getter, you can just delete it: delete obj.latest; defining a getter on existing objects using defineproperty to append a getter to an existing object later at any time, use object.defineproperty(). const o = {a: 0}; object.defineproperty(o, 'b', { get: function() { re
turn this.a + 1; } }); console.log(o.b) // runs the getter, which yields a + 1 (which is 1) using a computed property name const expr = 'foo'; const obj = { get [expr]() { re
turn 'bar'; } }; console.log(obj.foo); // "bar" smart / self-overwriting / lazy getters getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. a gett...
...And 4 more matches
Atomics - JavaScript
xt operation starts and that operations are not interrupted. wait and notify the wait() and notify() methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. static methods atomics.add() adds the provided value to the existing value at the specified index of the array. ...
...r-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. static methods atomics.add() adds the provided value to the existing value at the specified index of the array. re
turns the old value at that index. atomics.and() computes a bitwise and on the value at the specified index of the array with the provided value. re
turns the old value at that index. atomics.compareexchange() stores a value at the specified index of the array, if it equals a value. ...
...methods atomics.add() adds the provided value to the existing value at the specified index of the array. re
turns the old value at that index. atomics.and() computes a bitwise and on the value at the specified index of the array with the provided value. re
turns the old value at that index. atomics.compareexchange() stores a value at the specified index of the array, if it equals a value. re
turns the old value. atomics.exchange() stores a value at the specified index of the array. re
turns the old value. atomics.islockfree(size) an optimization primitive that can be used to determine whether to use locks or atomic operations. re
turns true if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). experts onl...
...And 4 more matches
Date.prototype.toLocaleString() - JavaScript
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. ...
...ub.com/mdn/interactive-examples and send us a pull request. syntax dateobj.tolocalestring([locales[, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...And 4 more matches
Map - JavaScript
key equality key equality is based on the samevaluezero algorithm. ...
...if you're not careful. note: as of es5, this can be bypassed by using object.create(null), but this is seldom done. key types a map's keys can be any value (including functions, objects, or any primitive). the keys of an object must be either a string or a symbol. key order the keys in map are ordered. thus, when iterating over it, a map object re
turns keys in order of insertion. the keys of an object are not ordered. note: since ecmascript 2015, objects do preserve creation order for string and symbol keys. in javascript engines that comply with the ecmascript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion. size the number of items in a map is easi...
...321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object. static properties get map[@@species] the constructor function that is used to create derived objects. ...
...And 4 more matches
Math.ceil() - JavaScript
description because ceil() is a static method of math, you always use it as math.ceil(), rather than as a method of a math object you created (math is not a constructor). ...
... description because ceil() is a static method of math, you always use it as math.ceil(), rather than as a method of a math object you created (math is not a constructor). ...
...th.ceil(4); // 4 math.ceil(7.004); // 8 math.ceil(-0.95); // -0 math.ceil(-4); // -4 math.ceil(-7.004); // -7 decimal adjustment // closure (function() { /** * decimal adjustment of a number. * * @param {string} type the type of adjustment. * @param {number} value the number. * @param {integer} exp the exponent (the 10 logarithm of the adjustment base). * @re
turns {number} the adjusted value. */ function decimaladjust(type, value, exp) { // if the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { re
turn math[type](value); } value = +value; exp = +exp; // if the value is not a number or the exp is not an integer... if (isnan(value) || !(typeof exp === 'number' && exp % 1 === 0)) { retur...
...And 4 more matches
Object.defineProperties() - JavaScript
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 object.defineproperties(obj, props) parameters obj the object on which to define or modify properties. props an object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. ...
...alid javascript value (number, object, function, etc). defaults to undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. defaults to false. an accessor descriptor also has the following optional keys: get a function which serves as a getter for the property, or undefined if there is no getter. the function's re
turn value will be used as the value of the property. defaults to undefined. set a function which serves as a setter for the property, or undefined if there is no setter. the function will receive as its only argument the new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if ...
...on which serves as a setter for the property, or undefined if there is no setter. the function will receive as its only argument the new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. re
turn value the object that was passed to the function. polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { fu...
...And 4 more matches
Object.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the object. 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 obj.tostring() re
turn value a string representing the object. description every object has a tostring() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring() method is inherited by every object descended from object. if this method is not overridden in a custom object, tostring() re
turns "[object type]", where type is the object type. the following code illus...
...is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring() method is inherited by every object descended from object. if this method is not overridden in a custom object, tostring() re
turns "[object type]", where type is the object type. the following code illustrates this: const o = new object(); o.tostring(); // re
turns [object object] note: starting in javascript 1.8.5, tostring() called on null re
turns [object null], and undefined re
turns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata. see using tostring() to detect object class. parameters for numbers and bigints tostring() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. b...
...et bignum = bigint(20); console.log(bignum.tostring(2)); // expected output is "10100" some common radix are 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers. examples overriding the default tostring method you can create a function to be called in place of the default tostring() method. the tostring() method takes no arguments and should re
turn a string. the tostring() method you create can be any value you want, but it will be most useful if it carries information about the object. the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocola...
...And 4 more matches
Promise.any() - JavaScript
promise.any() takes an iterable of promise objects and, as soon as one of the promises in the iterable fulfils, re
turns a single promise that resolves with the value from that promise. if no promises in the iterable fulfil (if all of the given promises are rejected), then the re
turned promise is rejected with an aggregateerror, a new subclass of error that groups together individual errors. 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. re
turn value an already resolved promise if the iterable passed is empty. an asynchronously...
... 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. re
turn 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 re
turned 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 re
turning the first promise that fulfils. it short-circuits after a promise fulfils, so it does not wait for the other promises to complete once it finds one. unlike promise.all(), ...
...se 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 re
turning the first promise that fulfils. it short-circuits after a promise fulfils, so it does not wait for the other promises to complete once it finds one. unlike promise.all(), which re
turns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). this can be beneficial if we need only one promise to fulfil but we do not care which one does. also, unlike promise.race(), which re
turns the first settled value (either fulfillment or rejection), this method re
turns the first fulfilled value. this method will ignore all rejected promises...
...And 4 more matches
Set - JavaScript
nd 0" in the browser compatibility table for details. nan and undefined can also be stored in a set. all nan values are equated (i.e. nan is considered the same as nan, even though nan !== nan). constructor set() creates a new set object. static properties get set[@@species] the constructor function that is used to create derived objects. instance properties set.prototype.size re
turns the number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. re
turns the set object. set.prototype.clear() removes all elements from the set object. set.prototype.delete(value) removes the element associated to the value and re
turns the value that set.prototype.has(value) would have previously re
turned. set.prototype.has(value) will...
...he number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. re
turns the set object. set.prototype.clear() removes all elements from the set object. set.prototype.delete(value) removes the element associated to the value and re
turns the value that set.prototype.has(value) would have previously re
turned. set.prototype.has(value) will re
turn false afterwards. set.prototype.has(value) re
turns a boolean asserting whether an element is present with the given value in the set object or not. ...
... set.prototype.delete(value) removes the element associated to the value and re
turns the value that set.prototype.has(value) would have previously re
turned. set.prototype.has(value) will re
turn false afterwards. set.prototype.has(value) re
turns a boolean asserting whether an element is present with the given value in the set object or not. iteration methods set.prototype[@@iterator]() re
turns a new iterator object that yields the values for each element in the set object in insertion order. set.prototype.keys() re
turns a new iterator object that yields the values for each element in the set object in insertion order. ...
...And 4 more matches
String.prototype.substring() - JavaScript
description substring() extracts characters from indexstart up to but not including indexend. ...
...and end indexes, or to the end of the string. 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 str.substring(indexstart[, indexend]) parameters indexstart the index of the first character to include in the re
turned substring. indexend optional the index of the first character to exclude from the re
turned substring. re
turn value a new string containing the specified part of the given string. description substring() extracts characters from indexstart up to but not including indexend. in particular: if indexend is omitted, substring() extracts characters to the end of the string. if indexstart is...
... if indexstart is greater than indexend, then the effect of substring() is as if the two arguments were swapped; see example below. any argument value that is less than 0 or greater than stringname.length is treated as if it were 0 and stringname.length, respectively. ...
...And 4 more matches
Nullish coalescing operator (??) - JavaScript
in other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). see below for more examples. the source for this interactive example is stored in a github repository. ...
...wanted to assign a default value to a variable, a common pattern was to use the logical or operator (||): let foo; // foo is never assigned any value so it is still undefined let somedummytext = foo || 'hello!'; however, due to || being a boolean logical operator, the left hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', nan, null, undefined) was not re
turned. this behavior may cause unexpected consequences if you consider 0, '', or nan as valid values. let count = 0; let text = ""; let qty = count || 42; let message = text || "hi!"; console.log(qty); // 42 and not 0 console.log(message); // "hi!" and not "" the nullish coalescing operator avoids this pitfall by only re
turning the second operand when the first one evaluates to either null or...
...lo world'; console.log(notfalsytext); // hello world let preservingfalsy = mytext ?? 'hi neighborhood'; console.log(preservingfalsy); // '' (as mytext is neither undefined nor null) short-circuiting like the or and and logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined. ...
...And 4 more matches
typeof - JavaScript
for more information about types and primitives, see also the javascript data structure page. ...
...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 the typeof operator is followed by its operand: typeof operand typeof(operand) parameters operand an expression representing the object or primitive whose type is to be re
turned. description the following table summarizes the possible re
turn values of typeof. for more information about types and primitives, see also the javascript data structure page. type result undefined "undefined" null "object" (see below) boolean "boolean" number "number" bigint (new in ecmascript 2020) "bigint" ...
... the only known browser to have actually taken advantage of this is old internet explorer (see below). examples basic usage // numbers typeof 37 === 'number'; typeof 3.14 === 'number'; typeof(42) === 'number'; typeof math.ln2 === 'number'; typeof infinity === 'number'; typeof nan === 'number'; // despite bei...
...And 4 more matches
yield - JavaScript
is used to pause and resume a generator function (function* or legacy generator function). 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 [rv] = yield [expression] expression optional defines the value to re
turn from the generator function via the iterator protocol. if omitted, undefined is re
turned instead. rv optional retrieves the optional value passed to the generator's next() method to resume its execution. description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is re
turned to the generator's caller. it can be thought of ...
...terator protocol. if omitted, undefined is re
turned instead. rv optional retrieves the optional value passed to the generator's next() method to resume its execution. description the yield keyword pauses generator function execution and the value of the expression following the yield keyword is re
turned to the generator's caller. it can be thought of as a generator-based version of the re
turn keyword. yield can only be called directly from the generator function that contains it. it cannot be called from nested functions or from callbacks. the yield keyword causes the call to the generator's next() method to re
turn an iteratorresult object with two properties: value and done. the value property is the result of evaluating the yield expression, and done is false, indicating that the ...
...is false, indicating that the generator function has not fully completed. once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and re
turn the generator's new value. the next time next() is called, execution resumes with the statement immediately after the yield. throw is used to throw an exception from the generator. this halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). the end of the generator function is reached. in this case, execution of the ...
...And 4 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
e workers can only be executed in secure contexts (meaning https). if you want to experiment first before pushing your code to production, you can always test on a localhost or setup github pages — both support https. offline first the "offline first" — or "cache first" — pattern is the most popular strategy for serving content to the user. if a resource is cached and available offline, re
turn it first before trying to download it from the server. if it isn’t in the cache already, download it and cache it for future usage. "progressive" in pwa when implemented properly as a progressive enhancement, service workers can benefit users who have modern browsers that support the api by providing offline support, but won't break anything for those using legacy browsers. service workers i...
... caches is a special cach...
...aituntil( caches.open(cachename).then((cache) => { console.log('[service worker] caching all: app shell and content'); re
turn cache.addall(contenttocache); }) ); }); there are two things that need an explanation here: what extendableevent.waituntil does, and what the caches object is. the service worker does not install until the code inside waituntil is executed. it re
turns a promise — this approach is needed because installing may take some time, so we have to wait for it to finish. caches is a special cachestorage object available in the scope of the given service worker to enable saving data — saving to web storage won't work, because web storage is synchronous. with service workers, we use the cache api instead. here, we open a cache with a given name, th...
...And 4 more matches
Example - SVG: Scalable Vector Graphics
iv> (c) 2006 <a id='emailme' href='#'>nick johnson</a> <script type='text/javascript'> <![cdata[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.getelementbyid('emailme').href = 'mailto:'+email; ]]> </script> this software is free for you to use in any way whatsoever, and comes with no warranty at all. </div> <form action="" onsubmit="re
turn false;"> <p> <label>number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>max. velocity:</label> <input id='max_velocity' value='15'/> <br/> <label>attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script ty...
...abel> <input id='max_velocity' value='15'/> <br/> <label>attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![cdata[ // array of motes var motes; // get the display element. ...
...<input id='attract_cursor' value='6'/> <br/> <label>repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![cdata[ // array of motes var motes; // get the display element. function display() { re
turn document.getelementbyid('display'); } // determine dimensions of the display element. ...
...And 4 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
he webp codec is written in c and available on github as well as some extensive api documentation. that's a pretty good starting point. $ git clone https://github.com/webmproject/libwebp to start off simple, expose webpgetencoderversion() from encode.h to javascript by writing a c file called webp.c: #include "emscripten.h" #include "src/webp/encode.h" emscripten_keepalive int version() { re
turn webpgetencoderversion(); } this is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function. to compile this program, you need to tell the compiler where it can find libwebp's header files using the -i flag and also pass it all the c files of libwebp that it needs. a useful st...
... 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 re
turns 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 number is great, but encoding 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 fin...
...ync function loadimage(src) { // load image const imgblob = await fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); re
turn ctx.getimagedata(0, 0, img.width, img.height); } now it's "only" a matter of copying the data from javascript into wasm. for that, you need to expose two additional functions — one that allocates memory for the image inside wasm and one that frees it up again: #include <stdlib.h> // required for malloc definition emscripten_keepalive uint8_t* create_buffer(int width, int height) { re
turn m...
...And 4 more matches
Classes and Inheritance - Archive of obsolete content
allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it
turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. classes in javascript are defined using constructor functions. each constructor function has an associated object, known as its prototype, which is shared between all instances of that class. we will show how to define classes using constructors, a...
...s of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call. constructor calls differ from ordinary function calls in that javascript automatically creates a new object and binds it to the keyword this for the duration of the call. moreover, if the constructor does not re
turn a value, the result of the call defaults to the value of this. constructors are just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. in fact, some people (including the add-on sdk team) prefer to use constructors this way. however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert the...
...ors are just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. in fact, some people (including the add-on sdk team) prefer to use constructors this way. however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function shape(x, y) { if (!this) re
turn new shape(x, y); this.x = x; this.y = y; } prototypes every object has an implicit property, known as its prototype. when javascript looks for a property, it first looks for it in the object itself. if it cannot find the property there, it looks for it in the object's prototype. if the property is found on the prototype, the lookup succeeds, and javascript pretends that it found the pr...
...And 3 more matches
/loader - Archive of obsolete content
es that are already loaded. for example in the sdk, the loader is loaded at bootstrap as a jsm module but is then exposed as a pseudo-module to avoid the overhead of subsequent loads: let loadermodule = cu.import('resource://gre/modules/commonjs/toolkit/loader.js'); let loader = loadermodule.loader({ modules: { // overlay `toolkit/loader` so that `require('toolkit/loader')` // will re
turn our `loadermodule`. 'toolkit/loader': loadermodule } }); use this feature with a great care though. while reuse may sound like a compelling idea it comes with the side effect of shared state, which can cause problems. for example, unload of a loader won't trigger unload hooks on pseudo-modules. globals each module loaded via the loader instance is secured in own js sandbox. these modu...
...n better, modules. resolve the optional resolve option enables you to completely customize module resolution logic. resolve is assigned a function that takes: the id of the module passed into require() the id of the module that called require() on each require() call, the supplied function is then called with the id of the required module and that of the requiring module. the function re
turns a string representing the resolved module id, which is then resolved to its location url using the mapping provided in the paths option. if this option is not provided, the loader will use plain path resolution. this feature may also be used to implement specific security constraints. for example, the sdk generates a manifest file at build time representing a dependency graph of all modules us...
... id add-on...
...And 3 more matches
IsDefaultNamespace - Archive of obsolete content
the following is a snippet to get isdefaultnamespace() supported across other browsers. note that all gecko-based browsers (including firefox) support node.isdefaultnamespace. this function is not necessary for gecko-based browsers (though the function will quickly re
turn the standard value for mozilla browsers). ...
...s function is not necessary for gecko-based browsers (though the function will quickly re
turn the standard value for mozilla browsers). ...
...om-level-3-core/core.html#node3-isdefaultnamespace // http://www.w3.org/tr/dom-level-3-core/namespaces-algorithms.html#isdefaultnamespacealgo function isdefaultnamespace(node, namespaceuri) { if (node.isdefaultnamespace) { re
turn node.isdefaultnamespace(namespaceuri); } switch (node.nodetype) { case 1: // element_node if (!node.prefix) { re
turn (node.namespaceuri === namespaceuri); } if (node.attributes.length) { for (var i=0; i < node.attributes.length; i++) { var att = node.attributes[i]; if (att.localname === 'xmlns') { re
turn att.value === namespaceuri; } } } if (node.par...
...And 3 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
indow. to overcome this limitation, nsiwindowmediator makes it possible to access all of firefox's windows. get active window one thing that nsiwindowmediator is often used for is to get the active window. listing 4 shows how to get the active browser window and the number of open tabs. passing the name of the window type as the parameter of the nsiwindowmediator.getmostrecentwindow() method re
turns the most recently active window from among the root element's windows with that type set for the windowtype attribute value. setting the parameter to null re
turns the active window from among all windows, including dialogs, etc. listing 4: get active browser window netscape.security.privilegemanager .enableprivilege('universalxpconnect'); var windowmediator = components .classes['@mozil...
...type. listing 5 shows how to get a summary of all browser windows in firefox and then close them. listing 5: closing all browser windows var browsers = windowmediator.getenumerator('navigator:browser'); var browser; while (browsers.hasmoreelements()) { browser = browsers.getnext().queryinterface(components.interfaces.nsidomwindowinternal); browser.browsertrytoclosewindow(); } this method re
turns an overview of the specified window type in the form of an iterator pattern object called nsisimpleenumerator. after getting an element with the nsisimpleenumerator.getnext() method, use the queryinterface method to get the interface, which allows you to handle each element as a window object. like the getmostrecentwindow() method, passing null as the parameter for the getenumerator() method en...
...() method gives the type of file to create. this is defined using constant properties—to create a normal file, use normal_file_type, to create a folder use directory_type. the second parameter gives the access privileges to that file using unix-style octal values. note: windows ignores the privileges parameter; other platforms may do so as well. the nsilocalfile object includes methods that re
turn virtual state values for the current file, as shown in table 1. table 1: methods for checking file states method name description nsilocalfile.exists() determines whether or not the file exists. nsilocalfile.iswriteable() determines whether or not the file can be written to. nsilocalfile.isreadable() determines whether or not the file can be read.
...And 3 more matches
Supporting search suggestions in search plugins - Archive of obsolete content
to construct the suggestion list box. see creating opensearch plugins for firefox to learn more about how to implement a search plugin. implementing search suggestion support on the server the majority of the work in handling search suggestions is actually implemented on the server side. ...
...this allows firefox to verify that the suggestions match the current search term. completion list an array of suggested search terms. the array should be enclosed in square brackets. ...
...he suggestions match the current search term. completion list an array of suggested search terms. the array should be enclosed in square brackets. for example: ["term 1", "term 2", "term 3", "term 4"] descriptions this optional element is an array of descriptions for each of the suggestions in thecompletion list . these can be any additional information the search engine might want to re
turn to be displayed by the browser, such as the number of results available for that search. descriptions are not supported in firefox, and are ignored if any are specified. query urls this optional element is an array of alternate urls for each of the suggestions in thecompletion list . for example, if you want to offer a map link instead of just a search result page for a given suggestion, yo...
...And 3 more matches
Using microformats - Archive of obsolete content
ional. if provided, this is a javascript object that contains zero or more of the following flags: recurseexternalframes if true, child frames are included in the search. the default is true. showhidden if true, hidden microformats are added; otherwise they're left out. the default is false. debug specify true if debug mode is in use; otherwise, specify false. the default is false. re
turn value an integer value indicating the number of microformats that match the specified criteria. debug() re
turns a string that describes a microformat object. note: you can simply call debug() on a microformat object: microformatobject.debug() instead of using this method if you prefer. var dumpstring = debug(microformatobject) parameters microformatobject the microformat object to dump...
... an integer value indicating the number of microformats that match the specified criteria. debug() re
turns a string that describes a microformat object. note: you can simply call debug() on a microformat object: microformatobject.debug() instead of using this method if you prefer. var dumpstring = debug(microformatobject) parameters microformatobject the microformat object to dump. re
turn value a string that describes the contents of the specified microformat object. get() re
turns an array of microformat objects corresponding to the microformats found that match specified criteria. var microformatsarray = microformats.get(name, rootelement, options, targetarray); parameters name the name of the microformat to find. rootelement required. the dom element at which to begi...
...at reference external content are included in the search. the default is true. showhidden if true, hidden microformats are added; otherwise they're left out. the default is false. debug specify true if debug mode is in use; otherwise, specify false. the default is false. targetarray optional. if provided, this is an array of microformat objects to which the search results are added. re
turn value a new array of microformat objects matching the search criteria, or the array specified by microformats with the newly found microformat objects added. getnamesfromnode() re
turns a space-delineated list of microformat names that correspond to the specified microformat node. var namelist = microformats.getnamesfromnode(node); parameters node the node for which to retrieve a list of...
...And 3 more matches
JavaScript Client API - Archive of obsolete content
it useful to override other methods of the base implementation, for example applyincomingbatch if the underlying storage for your data supports batch operations. createrecord the createrecord( id, collection ) method gets called by the engine to request a new record for an item with a given guid. it's your store's responsibility to instantiate a record object, assign the given guid, and re
turn it. itemexists(guid) should simply re
turn true if an item with the given guid exists in the store, false otherwise. changeitemid(oldid, newid) must find the stored item currently associated with the guid oldid and change it to be associated with the guid newid. getallids() must re
turn an iterable list containing the guids of every item being stored on the local system. thi...
...is is the method that the engine will call the first time it syncs, in order to get a complete inventory of what data there is that will need to be uploaded to the server. unless the items you're syncing have their own inherent guids already defined, you'll need to invent guids for all your items at this time. when one of these guids is later passed as an argument to createrecord(), you need to re
turn a record based on the matching data. therefore, it's the responsibility of this method to define the guid -> item mapping, and to store it for later reference by other methods. wipe() when this method is called, your store needs to completely wipe all of its stored data from the local application. that doesn't mean just whatever caches of the data the store happens to be maintaining; it m...
...t is passed in to this method having any of its attributes set correctly except for .id. the .id should be al you need, anyway.) applyincomingbatch : todo example store skeleton // maintains the store of all your foo-type items and their guids. ...
...And 3 more matches
JavaScript crypto - Archive of obsolete content
yption private key is wrapped with public key of key recovery authority (kra) (passed in in the form of a certificate as part of the script, and checked against a pre-installed certificate copy in the local certificate database) the public keys, wrapped encryption private key, and text string from the script (possibly containing naming or enrollment info) are signed by the user signed blob is re
turned to the script script submits signed blob and any other necessary info to the ca/ra ca/ra verifies signature on signed blob ca/ra validates identity of user ca/ra sends wrapped encryption private key to kra kra sends escrow verification back to ca ca creates and signs certificates ca sends certificates back to the user (importusercertificates) typical use the ca's enrollment page could...
...nsportcert = null; var crmfobject = null; var form = document.forms[0]; function validate() { // generate keys for nsm. ...
...*/); loading pkcs #11 modules long deletemodule(domstring modulename); long addmodule(domstring modulename, domstring libraryfullpath, long cryptomechanismflags, long cipherflags); ...
...And 3 more matches
Index - Archive of obsolete content
r, some background. 938 rule compilation xul, xul_template_guide a xul template is made up of a query and a series of rules. a query contains instructions for how to retrieve a set of data from the datasource. the exact syntax is dependent on the type of datasource used in the template. for instance, for an sqlite datasource, an sql statement is used as the query. this will re
turn a table of result records which are then used to generate output. for rdf and xml, the query contains a set of instructions for navigating through the rdf graph or xml document tree. a query is declared with the query tag (new to ff3; ff2 only worked with rdf datasources and had no query tag), which you would place directly inside the <template>. the job of the query is to generate a set of outpu...
...played. both types of builders implement the nsixultemplatebuilder interface, while the tree builder also implements the nsixultreebuilder interface.</tree> 946 template logging debugging problems with a template can be difficult as many problems are logic errors that are often not possible to determine automatically. for example, if you spell a value wrong, no data may be re
turned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. 947 template and tree listeners xul, xul_template_guide there are several listeners (or observers) used during the template build process, each used fo...
...executed when a <menupopup>, <panel> or <tooltip> has become visible. 993 xul faq xul this document contains answers to frequently asked questions about xul, mozilla's markup language for describing application's user interface. 994 xul parser in python/source source code for the xul parser in python. 995 xul questions and answers re
turn to mozilla-dev-tech-xul summaries 996 xul reference xul, xul reference no summary! 997 xul element attributes xul attributes, xul reference no summary! 998 xulbrowserwindow needscontent, xul the xulbrowserwindow object provides methods and properties that let the browser update the user interface of the enclosing xul window. in order ...
...And 3 more matches
Tree Box Objects - Archive of obsolete content
number of visible rows. for example if the tree shows 10 rows at a time, a page will be equivalent to 10 rows. this is a convenient method since when the user resizes a flexible tree, the page size will grow and shrink, so you don't need to calculate the page size manually. this isn't too hard to calculate manually anyway since the tree box object also provides a getpagelength() function which re
turns the number of rows in a page. in the scrolling example above, getpagelength() would re
turn four. note that in firefox 1.0 and mozilla 1.7 and earlier, the getpagelength() function is called getpagecount() instead. the name was changed to getpagelength() since it was confusing before since it doesn't re
turn the number of pages, but the size of each page. you could determine the number of pages ...
... several functions which may be used to get the parts of the tree at specific coordinates and vice versa. the getcellat() function may be used to get the cell at specific pixel location the getrowat() function may be used to get a row at a specific location. the getrowat() function takes two arguments, the x and y coordinates to use. tree.boxobject.getrowat( 50, 100 ); this example will re
turn the index of the row with a horizontal position of 50 and a vertical position of 100. naturally, it doesn't really matter what the value of the x coordinate is since rows always take up the entire horizontal space of the tree. one important thing to note is that the coordinates are measured from the upper left corner of the containing document, not the edge of the tree itself. this makes it eas...
...l label="spoon"/> <treecell label="8"/> </treerow> </treeitem> </treechildren> </tree> <label value="row:"/> <label id="row"/> <label value="column:"/> <label id="column"/> <label value="child type:"/> <label id="part"/> the getcellat() function takes five arguments, the coordinates to look up and three out parameters. an out parameter is used since the function needs to re
turn more that one value. you will see a number of interfaces that use out parameters in the xulplanet object reference (fixme: deadlink). these are indicated by the word 'out' before the argument. for these, you will need to supply an empty object and the function will fill in the 'value' property with the necessary value. the three out parameters will be filled in with the row, the column and a chi...
...And 3 more matches
menulist - Archive of obsolete content
type: string gets and sets the value of the crop attribute. description type: string set to the description of the currently selected menuitem. disableautoselect type: boolean gets and sets the value of the disableautoselect attribute. disabled type: boolean gets and sets the value of the disabled attribute. editable type: boolean re
turns true if the element is editable. autocomplete fields are editable so this property always re
turns true for those. editor type: nsieditor a reference to the nsieditor for editable text. this property is read only. image type: image url the image associated with the currently selected item. inputfield type: textbox element a reference to the textbox element used for editable men...
...f the label attribute. menuboxobject type: nsimenuboxobject a reference to the nsimenuboxobject which implements the menu. menupopup type: menupopup element a reference to the menupopup used by the menu or menulist. this property is read-only. open type: boolean gets and sets the value of the open attribute. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selecteditem type: element holds the currently selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a ...
...it...
...And 3 more matches
radiogroup - Archive of obsolete content
gets and sets the value of the disabled attribute. focuseditem type: radio element holds the currently focused item in the radiogroup, which may or may not be the same as the selected item. you can change the focused item by setting this property. itemcount type: integer read only property holding the number of child items. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selecteditem type: element holds the currently selected item. if no item is currently selected, this value will be null. you can select an item by setting this value. a...
...if the argument dir is true, the next radio button is selected. if i...
...removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) re
turn type: element creates a new item and adds it to the end of the existing list of items. you may optionally set a value. the function re
turns the newly created element. ...
...And 3 more matches
tree - Archive of obsolete content
d the tree data. the builder provides access to the rdf resources for each row in the tree, and allows sorting the data by column. in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript. this property is read-only. columns type: nsitreecolumns re
turns the columns for the tree as an nsitreecolumns object. contentview type: nsitreecontentview for trees built with a content builder - that is, those that do not have flags set -- the contentview will be a reference to the nsitreecontentview for the tree. this interface lets you retrieve the dom element corresponding to a given a row index and vice versa. for trees that are n...
...if the shouldaccept parameter is true, the cell's la...
...if the shouldaccept parameter is true, the cell's label is changed t...
...And 3 more matches
wizard - Archive of obsolete content
et to true if the user can press the back button to go to the previous page. if this property is false, the user cannot navigate to the previous page. set this property to true to indicate that the user can go back a page. set to false to disallow moving to the previous page. this has the effect of enabling or disabling the back button. currentpage type: wizardpage element this property re
turns the wizardpage element that is currently displayed. you can modify this value to change the current page. onfirstpage type: boolean this property is set to true if the user is on the first page, which may or may not be the first index. onlastpage type: boolean this property is set to true if the user is on the last page of the wizard. pagecount type: integer this property...
...the current page. onfirstpage type: boolean this property is set to true if the user is on the first page, which may or may not be the first index. onlastpage type: boolean this property is set to true if the user is on the last page of the wizard. pagecount type: integer this property holds the number of pages in the wizard. pageindex type: integer this property re
turns the index of the currently selected page. you can change the selected page by modifying this property. pagestep type: integer this property re
turns the number of pages that the user has navigated through so far, meaning that the user would press the back button this many times to go back to the beginning. this property is different than pageindex, because pages are not necessarily naviga...
...tnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata « xul reference home advance( pageid ) re
turn type: no re
turn value call this method to go to the next page. this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the pageid argument allows you to specify the index of the page to which to jump. supply null as the argument to go to the next page in the sequence. cancel() re
turn type: no re
turn value call this method to c...
...And 3 more matches
nsIContentPolicy - Archive of obsolete content
icy implementations, and should not be used outside gecko core code. type_internal_track 32 an internal constant used to represent content loaded from <track> elements. important: this type is mapped to type_media before being passed to content policy implementations, and should not be used outside gecko core code. reject_request -1 re
turned from shouldload() or shouldprocess() if the load or process request is rejected based on details of the request. reject_type -2 re
turned from shouldload() or shouldprocess() if the load/process is rejected based solely on its type (of the above flags). note: this rejection only applies to the current request on this server, not to future requests of the same type. ...
...oad or process request is rejected based on details of the request. reject_type -2 re
turned from shouldload() or shouldprocess() if the load/process is rejected based solely on its type (of the above flags). note: this rejection only applies to the current request on this server, not to future requests of the same type. reject_server -3 re
turned from shouldload() or shouldprocess() if the load/process is rejected based on the server it is hosted on or requested from (acontentlocation or arequestorigin), e.g., if you block an image because it is served from goatse.cx (even if you don't necessarily block other types from that server/domain). note: this rejection only applies to the current request on this server, not to future ...
...sed on the server it is hosted on or requested from (acontentlocation or arequestorigin), e.g., if you block an image because it is served from goatse.cx (even if you don't necessarily block other types from that server/domain). note: this rejection only applies to the current request on this server, not to future requests of the same type. reject_other -4 re
turned from shouldload() or shouldprocess() if the load/process is rejected based on some other criteria. mozilla callers will handle this like reject_request; third-party implementors may, for example, use this to direct their own callers to consult the extra parameter for additional details. note: this rejection only applies to the current request on this server, not to future requests of ...
...And 3 more matches
Table Reflow Internals - Archive of obsolete content
red size (if requested) - the size it would like to be given no size constraints. desired size - the size it would like to be given the avail size. this is equivalent to preferred size if the avail size is not constrained. review of reflow the reflowee sets various sizes in the reflow metrics after (possibly) reflowing some or all of its children which reflows it children, etc. the reflowee re
turns a reflow status which indicates if it is complete, and thus not have to continue (split) breaking status (in the case of some inline frames) if there is truncation (it can't fit in the space and can't split). this is just a convience mechanism. kinds of reflows initial - reflowee's first reflow must be of this type (reflower's responsibility). resize - reflowee gets a change in available sp...
...et's content changed (e.g. ...
...w groups, rows and cells. in each pass, row groups reflow rows which reflow cells which reflow cell blocks. ...
...And 3 more matches
Using the W3C DOM - Archive of obsolete content
in most standards-compliant browsers. instead, use the w3c dom properties and methods (examples in the next section). these are supported by internet explorer too so there is no need to use msie-specific attributes and methods. accessing elements with the w3c dom the basic method for referencing elements in an html page is document.getelementbyid(). all modern browsers support it. the method re
turns a reference to the uniquely identified element, which can then be used to script the element. for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementa...
...tified element, which can then be used to script the element. for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementation of getelementbyid(), which re
turns the first element with a matching name or id (id versus name when using getelementbyid, msdn: getelementbyid method). ie-specific ways to access elements w3c web standards replacements id_attribute_value document.getelementbyid() document.all.id_attribute_value document.getelementbyid() document.all[id_attribute_value] document.getelementbyid() ...
... document.forms[0] more on accessing forms and form elements: referencing forms and form controls by comp.lang.javascript newsgroup faq notes dom 2 specification on accessing forms and form elements referencing forms and form elements correctly, javascript best practices, by matt kruse for accessing a group of elements, the dom specification also includes getelementsbytagname, which re
turns a nodelist of all the elements with the given tag name in the order they appear in the document: var arrcollection_of_pargs = document.getelementsbytagname("p"); var objfirst_parg = arrcollection_of_pargs[0]; // objfirst_parg will reference the first paragraph in the document objfirst_parg.style.border = "2px solid green"; // and now, the first paragraph in the document // gets a 2px solid gree...
...And 3 more matches
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray. created by any java method which re
turns an array. in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript. javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. in javascript 1.4 and later, the componenttype parameter is either a javaclass object representing the type of the array or class object, such as one re
turned by java.lang.class.forname. in...
...when the javaarray is passed back to java, the array is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. ...
...when the javaarray is passed back to java, the array is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. in javascript 1.4 and later, the methods of java.lang.object are inherited by javaarray. ...
...And 3 more matches
Desktop gamepad controls - Game development
oop through them; if the pressed property is set to true, then we add them to the buttonspressed array for later processing. next, we'll consider the gamepadbuttonpressedhandler() function: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press = true; } } re
turn press; } the function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonspressed array. if it is, then the function re
turns true; false otherwise. next, in the draw() function we do two things — execute the gamepadupdatehandler() function to get the current state of pressed buttons on every frame, an...
... the button.
...tus = axes; gamepadapi.buttons.status = pressed; re
turn pressed; }, the function above clears the buttons cache, and copies their status from the previous frame to the cache. next, the button status is cleared and the new information is added. the same goes for the axes information — looping through axes adds the values to the array. received values are assigned to the proper objects and re
turns the pressed info for debugging purposes. the button.pressed() function detects the actual button presses: pressed: function(button, hold) { var newpress = false; for(var i=0,s=gamepadapi.buttons.status.length; i<s; i++) { if(gamepadapi.buttons.status[i] == button) { newpress = true; if(!hold) { for(var j=0,p=gamepadapi.buttons.cache.length; j<p; j++) { if(...
...And 3 more matches
How to build custom form controls - Learn web development
does not change when: the user hits the up arrow key when the first option is selected. the user hits the down arrow key when the last option is selected. finally, let's define how the control's options will behave: when the control is opened, the selected option is highlighted when the mouse is over an option, the option is highlighted and the previously highlighted option is re
turned to its normal state for the purposes of our example, we'll stop with that; however, if you're a careful reader, you'll notice that some behaviors are missing. for example, what do you think will happen if the user hits the tab key while the control is in its open state? the answer is... nothing. ok, the right behavior seems obvious but the fact is, because it's not defined in our specs, it is...
...-proof nor will not work on legacy browsers. it also has redundant parts that should be optimized in production code. why isn't it working? before starting, it's important to remember javascript in the browser is an unreliable technology. custom controls rely on javascript to tie everything together. however, there are cases in which javascript isn't able to run in the browser: the user has
turned off javascript: this is unusual; very few people
turn off javascript nowadays. the script did not load: this is one of the most common cases, especially in the mobile world where the network is not very reliable. the script is buggy: you should always consider this possibility. the script is in conflict with a third party script: this can happen with tracking scripts or any bookmarklets the ...
...t in the page. making the job easier in the code we are about to build, we will use the standard javascript and dom apis to do all the work we need. the features we plan to use are the following: classlist addeventlistener() foreach queryselector() and queryselectorall() beyond the availability of those specific features, there is still one issue remaining before starting. the object re
turned by the queryselectorall() function is a nodelist rather than an array. this is important because array objects support the foreach function, but nodelist doesn't. because nodelist really looks like an array and because foreach is so convenient to use, we can easily add the support of foreach to nodelist in order to make our life easier, like so: nodelist.prototype.foreach = function (callback)...
...And 3 more matches
JavaScript basics - Learn web development
; 'hello ' + 'world!'; subtraction, multiplication, division these do what you'd expect them to do in basic math. -, *, / 9 - 3; 8 * 2; // multiply in js is an asterisk 9 / 3; assignment as you've seen already: this assigns a value to a variable. = let myvariable = 'bob'; equality this performs a test to see if two values are equal. it re
turns a true/false (boolean) result. === let myvariable = 3; myvariable === 4; not, does-not-equal this re
turns the logically opposite value of what it precedes. it
turns a true into a false, etc.. when it is used alongside the equality operator, the negation operator tests whether two values are not equal. !, !== for "not", the basic expression is true, but the compar...
...e/false (boolean) result. === let myvariable = 3; myvariable === 4; not, does-not-equal this re
turns the logically opposite value of what it precedes. it
turns a true into a false, etc.. when it is used alongside the equality operator, the negation operator tests whether two values are not equal. !, !== for "not", the basic expression is true, but the comparison re
turns false because we negate it: let myvariable = 3; !(myvariable === 3); "does-not-equal" gives basically the same result with different syntax. here we are testing "is myvariable not equal to 3". this re
turns false because myvariable is equal to 3: let myvariable = 3; myvariable !== 3; there are a lot more operators to explore, but this is enough for now. see exp...
...ors to explore, but this is enough for now. see expressions and operators for a complete list. note: mixing data types can lead to some strange results when performing calculations. be careful that you are referring to your variables correctly, and getting the results you expect. for example, enter '35' + '25' into your console. why don't you get the result you expected? because the quote marks
turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. if you enter, 35 + 25 you'll get the total of the two numbers. conditionals conditionals are code structures used to test if an expression re
turns true or not. a very common form of conditionals is the if ... else statement. for example: let icecream = 'chocolate'; if(icecream === 'chocolate') { a...
...And 3 more matches
Looping code - Learn web development
pdate</button> <canvas></canvas> <script> const btn = document.queryselector('button'); const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); let width = document.documentelement.clientwidth; let height = document.documentelement.clientheight; canvas.width = width; canvas.height = height; function random(number) { re
turn math.floor(math.random()*number); } function draw() { ctx.clearrect(0,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } btn.addeventlistener('click',draw); </script> </body> </html> ...
... width and height are the width and height of the inner browser window. you should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page. the amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000. only one number has to change. if...
..., then the process will start again. when i becomes equal to cats.length (in this case, 5), the loop will stop, and the browser will move on to the next bit of code below the loop. note: we have made the condition i < cats.length, not i <= cats.length, because computers count from 0, not 1 — we are starting i at 0, and going up to i = 4 (the index of the last array item). cats.length re
turns 5, as there are 5 items in the array, but we don't want to get up to i = 5, as that would re
turn undefined for the last item (there is no array item with an index of 5). so, therefore, we want to go up to 1 less than cats.length (i <), not the same as cats.length (i <=). note: a common mistake with conditions is making them use "equal to" (===) rather than say "less than or equal to" (<=). if...
...And 3 more matches
Handling text — strings in JavaScript - Learn web development
in this article, we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in strings, and joining strings together. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to gain familiarity with the basics of strings in javascript. the power of words words are very important to humans — they are a large part of how we communicate. ...
...ou dig deeper you'll start to see some notable differences. let's start by entering some basic lines into the browser developer console to familiarize ourselves. creating a string to start with, enter the following lines: let string = 'the revolution will not be televised.'; string; just like we did with numbers, we are declaring a variable, initializing it with a string value, and then re
turning the value. the only difference here is that when writing a string, you need to surround the value with quotes. if you don't do this, or miss one of the quotes, you'll get an error. try entering the following lines: let badstring = this is a test; let badstring = 'this is a test; let badstring = this is a test'; these lines don't work because any text without quotes around it is assumed to...
...p your strings in. both of the following will work okay: let sgl = 'single quotes.'; let dbl = "double quotes"; sgl; dbl; there is very little difference between the two, and which you use is down to personal preference. you should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two different quotes on the same string! the following will re
turn an error: let badquotes = 'what on earth?"; the browser will think the string has not been closed because the other type of quote you are not using to contain your strings can appear in the string. for example, both of these are okay: let sgldbl = 'would you eat a "fish supper"?'; let dblsgl = "i'm feeling blue."; sgldbl; dblsgl; however, you can't include the same quote mark inside the...
...And 3 more matches
Server-side web frameworks - Learn web development
t will make your life a lot easier. this section discusses some of the functionality that is often provided by web frameworks (not every framework will necessarily provide all of these features!). work directly with http requests and responses as we saw in the last article, web servers and browsers communicate via the http protocol — servers wait for http requests from the browser and then re
turn information in http responses. web frameworks allow you to write simplified syntax that will generate server-side code to work with these requests and responses. this means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. the example below shows how this works in the django (python) web framework. every "view" function (a...
... server-side code to work with these requests and responses. this means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. the example below shows how this works in the django (python) web framework. ...
...amework. every "view" function (a request handler) receives an httprequest object containing request information, and is required to re
turn an httpresponse object with the formatted output (in this case a string). # django view function from django.http import httpresponse def index(request): # get an httprequest (request) # perform operations using information from the request. # re
turn httpresponse re
turn httpresponse('output string to re
turn') route requests to the appropriate handler most sites will provide a number of different resources, accessible through distinct urls. handling these all in one function would be hard to maintain, so web frameworks provide simple mechanisms to map url patterns to specific handler functions. this approach also has benefits in terms o...
...And 3 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
themselves. when svelte analyzes this code, if can detect that the todos array is being modified. ...
...ied. another solution is to assign a new array to todos containing a copy of all the todos with the completed property updated accordingly, like this: const checkalltodos = (completed) => { todos = todos.map(t => { // shorter version: todos = todos.map(t => ({...t, completed})) re
turn {...t, completed: completed} }) } in this case we are using the map() method, which re
turns a new array with the results of executing the provided function for each item. the function re
turns a copy of each todo using spread syntax and overwrites the property of the completed value accordingly. this solution has the added benefit of re
turning a new array with new objects, completely avoiding mutating the original todos array. note: svelte allows us to specify different options that a...
...s() 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 re
turns 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...
...And 3 more matches
Mozilla’s UAAG evaluation report
oint title status notes/plans 2.1 render content according to specification. (p1) vg renders html, css, and a number of graphic image formats. does not contradict current specifications for html and css rendering. 2.2 provide text view. (p1) c also known as view source. 2.3 render conditional content. (p1) vg alt for img: rendered when images
turned off. see meta bug 41924 for open issues with the alt attribute. title for *any* element: rendered as tooltip longdesc for img element: in context menu - properties content of object element: ? alt for area element: ? alt for input element: ? acronym element: supported abbr element: supported abbr attribute for td/th: not supported summary for table: supported...
...ted in this problem can look at the getalternatetext() method -- see the cvs history for suggestions. we consider this to be a very difficult problem. 2.8 no repair text. (p3) p we have no repair strategy in 2.7 we have no way to configure that alt="" still needs to be repaired 2.9 render conditional content automatically. ...
.... (p2) vg preferences, advanced, scripts & windows - allow scripts to "open unrequested windows" we do not have a strategy to "alert the user and allow the user to open it on demand" we do not have exposed prefs for all of our popup control options. ...
...And 3 more matches
Creating Sandboxed HTTP Connections
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 re
turned data, networking conditions, etc). onstoprequest - the request has finished. onchannelredirect - when a redirect happens, a new nsichannel is created, and both the old and new ones are passed in as arguments. since nsistreamlistener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (cover...
...cessfull this.mcallbackfunc(this.mdata); } else { // request failed this.mcallbackfunc(null); } gchannel = null; }, // nsichanneleventsink onchannelredirect: function (aoldchannel, anewchannel, aflags) { // if redirecting, store the new channel gchannel = anewchannel; }, // nsiinterfacerequestor getinterface: function (aiid) { try { re
turn this.queryinterface(aiid); } catch (e) { throw components.results.ns_nointerface; } }, // nsiprogresseventsink (not implementing will cause annoying exceptions) onprogress : function (arequest, acontext, aprogress, aprogressmax) { }, onstatus : function (arequest, acontext, astatus, astatusarg) { }, // nsihttpeventsink (not implementing will cause annoying exceptions) ...
...it would be better to have the entire implementation inside a class and storing the channel as a member: function myclass() { this.mchannel = null; // ... var listener = new this.streamlistener...
...And 3 more matches
Performance best practices for Firefox front-end engineers
e 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. we could do it this way: async function nodeisdisplaynone(node) { let display = await window.promisedocumentflushed(() => { // do _not_ under any circumstances write to the dom in one of these // callbacks! re
turn window.getcomputedstyle(node).display; }); re
turn display == "none"; } see detecting and avoiding synchronous reflow for a more advanced example of getting layout information, and then setting it safely, without causing flushes. promisedocumentflushed is only available to priviledged script, and should be called on the inner window of a top-level frame. calling it on the outer window of...
...ding 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. here's an example: async function matchwidth(elem, otherelem) { let width = await window.promisedocumentflushed(() => { // do _not_ under any circumstances write to the dom in one of these // callbacks! re
turn elem.clientwidth; }); requestanimationframe(() => { otherelem.style.width = `${width}px`; }); } please see the section on promisedocumentflushed in detecting and avoiding synchronous style flushes for more information on how to use the api. note that queries for size and position information are only expensive if the dom has been written to. otherwise, we're doing a cheap look-up of ...
...tomainthread(() => { // same-ish as above. }); }); this also implies that querying for size and position information in requestanimationframe() has a high probability of causing a synchronous reflow. other useful methods below you'll find some suggestions for other methods which may come in handy when you need to do things without incurring synchronous reflow. these methods generally re
turn the most-recently-calculated value for the requested value, which means the value may no longer be current, but may still be "close enough" for your needs. unless you need precisely accurate information, they can be valuable tools in your performance toolbox. nsidomwindowutils.getboundswithoutflushing() getboundswithoutflushing() does exactly what its name suggests: it allows you to get the bou...
...And 3 more matches
HTTP Cache
. //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicachestorageservice.idl "@mozilla.org/netwerk/cache-storage-service;1" provides methods accessing “storage” objects – see nsicachestorage below – giving further access to cache entries – see nsicacheentry more below – per specific url. ...
...ticular app cache version in a group) in hands, this storage will provide read and write access to entries in that application cache; when the app cache is not specified, this storage will operate over all existing app caches the service also provides methods to clear the whole disk and memory cache content or purge any intermediate memory structures: clear – after it re
turns, all entries are no longer accessible through the cache apis; the method is fast to execute and non-blocking in any way; the actual erase happens in background purgefrommemory – removes (schedules to remove) any intermediate cache data held in memory for faster access (more about the intermediate cache below) nsiloadcontextinfo distinguishes the scope of the storag...
...r 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 re
turns 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 re
turns (i.e. immediately); there is currently no way to opt out of this feature (watch bug 938186). nsicacheentry //github.com/realityripple/u...
...And 3 more matches
AddonManager
one of the forces of the addonmanager is that it deals with any kind (type) of add-on in a generic manner. ...
...ile directory. scope_system 8 this add-on is installed somewhere global to the system (installed for all users of the computer). scope_user 2 this add-on is installed somewhere specific to the current user (all profiles of the logged-in user). note: the extensions.enabledscopes preference lets you configure which of these scopes are enabled; however, you can't
turn off the profile scope. starting in firefox 8, you can also set the value of the preference extensions.autodisabledscopes to prevent firefox from automatically installing add-ons from the specified scopes. addontype viewtypes constant description view_type_list the type should be displayed in a regular list view in the ui. addontype flags constant desc...
...nge list. removestartupchange() removes an add-on from the add-on changes list. void addstartupchange( in string changetype, in string id ); parameters changetype the type of change to remove for the specified add-on. this can be one of the startup change types or a custom value defined by your own provider. id the add-on id to remove from the change list. ...
...And 3 more matches
AsyncShutdown.jsm
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 re
turn promise; }, function info() { let status = ... // collect any information that may be useful for debugging shutdown issues with this blocker re
turn status; } }); in this example, at some point during phase profilebeforechange, function condition will be called. phase profilebeforechange is guaranteed to not terminate until promise is either resolved or rejected. if, for some re...
...romise is either resolved or rejected. if, for some reason, promise is never resolved/rejected, firefox will crash during shutdown to avoid blocking system shutdown, preventing the user 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 re
turned 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 ...
...ion|promise|* condition, optional in function info ) arguments name the human-readable name of the blocker. used for debugging/error reporting. please make sure that the name respects the following model: "some service: some action in progress" - for instance "os.file: flushing all pending i/o". condition a condition blocking the completion of the phase. generally, this is a function re
turning a promise. this function is evaluated during the phase and the phase is guaranteed to not terminate until the resulting promise is either resolved or rejected. if condition is not a function but another value v, it behaves as if it were a function re
turning v. info optionally, a function re
turning information about the current state of the blocker as an object. used for providing more detail...
...And 3 more matches
NetUtil.jsm
methods asynccopy() the asynccopy() method performs a simple asynchronous copy of data from a source input stream to a destination output stream. both streams are automatically closed when the copy operation is completed. nsiasyncstreamcopier asynccopy( asource, asink, acallback ); parameters asource the input stream from which to read the sourc...
...ters asource the input stream from which to read the source data. this must be an nsiinputstream based object. asink the output stream to which to copy the data. this must be an nsioutputstream based object. acallback an optional function that will be called when the copy operation is completed. the callback receives a single parameter: the nsresult status code for the copy operation. re
turn value re
turns the nsiasyncstreamcopier object that is handling the copy. exceptions thrown this method throws an exception with the message "must have a source and a sink" if either asource or asink is null. example this example writes a string to a file; it comes from the test suite for the netutil module. var file = cc["@mozilla.org/file/directory_service;1"]. getservice(ci.nsi...
...ceptions thrown this method throws an exception with the message "must have a source and a callback" if either asource or acallback is null. example this example shows the basic code consumers would need to implement to be correct. netutil.asyncfetch(channel, function(ainputstream, aresult) { // check that we had success. if (!components.issuccesscode(aresult)) { // handle error re
turn; } // consume the input stream. }); remarks note: if you specify an nsichannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsibadcertlistener and nsisslerrorlistener. newchannel() creates a new channel for the specified uri string, nsiuri, or nsifile. nsichannel newchannel( awhattoload, [optional] aorigincharset...
...And 3 more matches
Promise.jsm
promise. this may be any value, 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. ...
...for example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. ...
...for example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. see the documentation of the then method for details. ...
...And 3 more matches
NSPR Poll Method
method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is already able to make progress in the manner suggested by the polling flags. the arguments and re
turn value of the poll method are described below. in_flags [input argument] the in_flags argument specifies the events at the top layer of the i/o layer stack that the caller is interested in. for pr_recv, you should pass pr_poll_read as the in_flags argument to the poll method for pr_send, you should pass pr_poll_write as the in_flags argument to the poll method out_flags [output argument] ...
... in. for pr_recv, you should pass pr_poll_read as the in_flags argument to the poll method for pr_send, you should pass pr_poll_write as the in_flags argument to the poll method out_flags [output argument] if an i/o layer is ready to satisfy the i/o request defined by in_flags without involving the underlying network transport, its poll method sets the corresponding event in *out_flags on re
turn. for example, consider an i/o layer that buffers input data. if the caller wishes to test for read ready (that is, pr_poll_read is set in in_flags) and the layer has input data buffered, the poll method would set the pr_poll_read event in *out_flags. it can determine that without asking the underlying network transport. the current implementation of pr_poll (the primary user of the poll method) r...
...g the underlying network transport. the current implementation of pr_poll (the primary user of the poll method) requires that the events in *out_flags reflect the caller's view. this requirement may be relaxed in a future nspr release. to remain compatible with this potential semantic change, nspr clients should only use *out_flags as described in the how to use the poll method section below. ...
...And 3 more matches
PR_Poll
parameters the function has the following parameters: pds a pointer to the first element of an array of prpolldesc structures. npds the number of elements in the pds array. if this parameter is zero, pr_poll is equivalent to pr_sleep with a timeout. timeout amount of time the call will block waiting for i/o to become ready. ...
...e function has the following parameters: pds a pointer to the first element of an array of prpolldesc structures. npds the number of elements in the pds array. if this parameter is zero, pr_poll is equivalent to pr_sleep with a timeout. timeout amount of time the call will block waiting for i/o to become ready. if this time expires without any i/o becoming ready, pr_poll re
turns zero. ...
...lowing parameters: pds a pointer to the first element of an array of prpolldesc structures. npds the number of elements in the pds array. if this parameter is zero, pr_poll is equivalent to pr_sleep with a timeout. timeout amount of time the call will block waiting for i/o to become ready. if this time expires without any i/o becoming ready, pr_poll re
turns zero. ...
...And 3 more matches
NSS 3.16.3 release notes
8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 cn = quovadis root ca 3 g3 sha1 fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d the trust bits were changed for the following ca certificates ou = class 3 public primary certification authority sha1 fingerprint: a1:db:63:93:91:6f:17:e4:18:55:09:40:04:15:c7:02:40:b0:ae:6b
turned off websites and code signing trust bits (1024-bit root) ou = class 3 public primary certification authority sha1 fingerprint: 74:2c:31:92:e6:07:e4:24:eb:45:49:54:2b:e1:bb:c5:3e:61:74:e2
turned off websites and code signing trust bits (1024-bit root) ou = class 2 public primary certification authority - g2 sha1 fingerprint: b3:ea:c4:47:76:c9:c8:1...
... sha1 fingerprint: cb:a1:c5:f8:b0:e3:5e:b8:b9:45:12:d3:f9:34:...
... root) ou = class 2 public primary certification authority - g2 sha1 fingerprint: b3:ea:c4:47:76:c9:c8:1c:ea:f2:9d:95:b6:cc:a0:08:1b:67:ec:9d
turned off code signing trust bit (change requested by ca) cn = verisign class 2 public primary certification authority - g3 sha-1 fingerprint: 61:ef:43:d7:7f:ca:d4:61:51:bc:98:e0:c3:59:12:af:9f:eb:63:11
turned off code signing trust bit (change requested by ca) cn = ac raíz certicámara s.a. ...
...And 3 more matches
NSS Sample Code Sample_2_Initialization of NSS
y a password file\n\n", "-f <plainpasswc>"); exit(-1); } /* initialize the slot password */ char *initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { re
turn filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { re
turn pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "error opening input terminal for read\n"); re
turn null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, ...
...ize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); re
turn null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0...
...sword: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
...And 3 more matches
sample1
def struct { const char *hashname; secoidtag oid; } nametagpair; /* the hash algorithms supported */ static const nametagpair hash_names[] = { { "md2", sec_oid_md2 }, { "md5", sec_oid_md5 }, { "sha1", sec_oid_sha1 }, { "sha256", sec_oid_sha256 }, { "sha384", sec_oid_sha384 }, { "sha512", sec_oid_sha512 } }; /* maps a hash name to a secoidtag. ...
...re
turns null if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } re
turn hashtag; } /* newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); re
turn; } ...
...e, prfiledesc *infile, secoidtag hashoidtag) { unsigned int nb; unsigned char ibuf[4096]; unsigned char digest[64]; unsigned int len; unsigned int digestlen; hash_hashtype hashtype; hashcontext *hashcontext = null; hashtype = hash_gethashtypebyoidtag(hashoidtag); hashcontext = hash_create(hashtype); if (hashcontext == null) { re
turn secfailure; } do { hash_begin(hashcontext); /* incrementally hash the file contents */ while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { hash_update(hashcontext, ibuf, nb); } hash_end(hashcontext, digest, &len, 64); /* normally we would write it out in binary with * nb = pr_write(outfile, diges...
...And 3 more matches
NSS tools : ssltab
ssltap — tap into ssl connections and display the data going by synopsis libssltap [-vhfsxl] [-p port] [hostname:port] description the ssl debugging tool ssltap is an ssl-aware command-line proxy. it watches tcp connections and displays the data going by. if a connection is ssl, the data display includes interpreted ssl records and handshaking options -v print a version string for the tool. -h
turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f
turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is ...
...the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. ...
...s option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x
turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix
turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http...
...And 3 more matches
NSS tools : ssltap
ssltap — tap into ssl connections and display the data going by synopsis libssltap [-vhfsxl] [-p port] [hostname:port] description the ssl debugging tool ssltap is an ssl-aware command-line proxy. it watches tcp connections and displays the data going by. if a connection is ssl, the data display includes interpreted ssl records and handshaking options -v print a version string for the tool. -h
turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f
turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is ...
...the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. ...
...s option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x
turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix
turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http...
...And 3 more matches
NSS tools : ssltap
the data going by synopsis libssltap [-vhfsxl] [-p port] [hostname:port] description the ssl debugging tool ssltap is an ssl-aware command-line proxy. it watches tcp connections and displays the data going by. if a connection is ssl, the data display includes interpreted ssl records and handshaking options -v print a version string for the tool. -h
turn on hex/ascii printing. instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f
turn on fancy printing. output is printed in colored html. data ...
...the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. ...
...ool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x
turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix
turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) t...
...And 3 more matches
JS::Value
mbol() js::symbolvalue(js::symbol*) val.tosymbol() val.setsymbol(js::symbol &) numbers are stored in a js::value either as a double or as an int32_t. the different representations are visible using the separate int32/double methods but do not affect observable semantics (ignoring performance). the number mutators attempt to use int32_t representation for compatible input values, re
turning true when int32 could be used and false when double representation was required. any double value may be stored in a js::value, in one of these two representations. the only exception is that only a single nan value can be represented. (note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) js::value further provides these methods combi...
...ed. any double value may be stored in a js::value, in one of these two representations. the only exception is that only a single nan value can be represented. ...
... int32_t representation.) js::value further provides these methods combining various aspects of the above methods: js::objectornullvalue(jsobject*) re
turns an object value corresponding to the given non-null pointer, or a null value if the pointer is null. val.setobjectornull(jsobject *) sets the given value to the specified object, or to null if the pointer was null. val.isobjectornull() re
turns true if the value is either an object or undefined. correspondingly, val.toobjectornull() re
turns a non-null jsobject * if the value is an object, and null if the value is null. val.isprimitive() re
turns true if the value is a primitive value -- that is, not an object. it is equivalent to !val.isobject(). val.isnullorundefined() re
turns true if the value is either null or undefined. val.isgc...
...And 3 more matches
Redis Tips
i: 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 re
turn value is error or null; second re
turn 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 that last example, the values pointed to by keys ar...
...cally. get key set key value exists key setnx key value incr key incrby key int incrbyfloat key float getset key value get and set are fairly obvious. setnx sets a value on a key only if there is no existing value. this is so useful. and it is a single, atomic command. redis> get foo (nil) redis> setnx foo 17 (integer) 1 redis> get foo "17" redis> setnx foo 42 (integer) 0 the re
turn value from setnx is 1 if the value was set, 0 otherwise. incr, incrby, and incrbyfloat all increment counters. they are also atomic operations. they re
turn the post-increment value of your key. redis> set foo 42 ok redis> incr foo (integer) 43 redis> incrby foo 17 (integer) 60 notice that these results come back as numbers, not strings. incrbyfloat is in redis 2.6. getset is awesome...
... redis> del foo (integer) 1 redis> get foo (nil) redis> getset foo 3 (nil) redis> getset foo 4 "3" efficient multiple queries and transaction blocks you'll often want to do several queries together. ...
...And 3 more matches
Aggregating the In-Memory Datasource
xpcom aggregation1 with the in-memory datasource. why would you want to do this? say you were writing a datasource2, and the way you chose to implement it was to "wrap" the in-memory datasource; i.e., myclass : public nsimyinterface, public nsirdfdatasource { private: nscomptr<nsirdfdatasource> minner; public: // nsirdfdatasource methods ns_imethod init(const char* auri) { re
turn minner->init(auri); } ns_imethod geturi(char* *auri) { re
turn minner->geturi(auri); } // etc., for each method in nsirdfdatasource! }; very painful, prone to errors, and fragile as the interfaces are still in flux (a wee bit). aggregation to the rescue! here are the gory details on how. when it won't work although this magic is terribly convenient to use, it won't wo...
...terface, it willforward the query interface to its "outer" (which is "us"). this preserves the symmetrical property of queryinterface(). ...
...fo...
...And 3 more matches
How to build a binary XPCOM component using Visual Studio
he component files to add your own functionality. to make the project, you start with a standard multi-thread dll project. then make the following tweaks: add "..\gecko-sdk\include" to additional include directories add "..\gecko-sdk\lib" to additional library directories add "nspr4.lib xpcom.lib xpcomglue_s.lib" to additional dependencies add "xp_win;xp_win32″ to preprocessor definitions
turn off precompiled headers (just to keep it simple) use a custom build step for the xpcom idl file (spawns xpidl-build.bat to process the idl with mozilla toolset, not midl) vc++ express project: xpcom-test.zip note: the project uses xpcom_glue. it also uses frozen linkage (dependent on xpcom). i am not defining xpcom_glue and i am linking against xpcomglue_s.lib create an xpcom component a ful...
...pcomglue_s.lib create an xpcom component a full tutorial of xpcom is beyond the scope of this posting. check out the resources at the end of the tutorial for more information on the world of xpcom. ok then, on with the basic, oversimplified example. your xpcom component is made up of 3 parts: component interface described using idl. the interface defines the methods, including arguments and re
turn types, of the component. component implementation using c++. the implementation is where the methods actually do the work. component factory module, also in c++. the factory is in charge of creating instances of the implementations. let’s specify a simple interface: #include "nsisupports.idl" [scriptable, uuid(263ed1ba-5cc1-11db-9673-00e08161165f)] interface ispecialthing : nsisupports { ...
...i put this together from some samples i found on the mdc site: #include "nsigener...
...And 3 more matches
Components.isSuccessCode
summary determines whether a given xpcom re
turn code (that is, an nsresult value) indicates the success or failure of an operation, re
turning true or false respectively. syntax var succeeded = components.issuccesscode(re
turncode); parameters re
turncode the re
turn code (of type nsresult) to be checked. description components.issuccesscode() may be used to determine whether an xpcom re
turn code (an nsresult) indicates success or failure. an xpcom re
turn code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. note: a non-zero xpcom re
turn code (that is, not ns_ok) does not necessarily indicate failure. ...
...however, if you are using asynchronous apis, it may be essential. ...
...however, if you are using asynchronous apis, it may be essential. ...
...And 3 more matches
Language bindings
the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read...
...the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in...
...al native component manager service. the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of errors), with the value of each corresponding to that constant's value.components.re
turncodecomponents.stackcomponents.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack. this can be used for various diagnostic purposes.components.utilscomponents.utils is a collection of various useful xpconnect features. its interface is defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis functi...
...And 3 more matches
Core XPCOM functions
xpcom provides a number of global functions which are used to initialize and shut down the xpcom library, as well as to allocate memory, get access to services, and to instantiate interfaces. ...
...ell as to allocate memory, get access to services, and to instantiate interfaces. ...
... ns_newlocalfilethe ns_newloc...
...And 3 more matches
IAccessibleValue
cal value like progress bars and spin boxes. this interface lets you access the value and its upper and lower bounds. ...
...ace lets you access the value and its upper and lower bounds. method overview [propget] hresult currentvalue([out] variant currentvalue ); [propget] hresult maximumvalue([out] variant maximumvalue ); [propget] hresult minimumvalue([out] variant minimumvalue ); hresult setcurrentvalue([in] variant value ); methods currentvalue() re
turns the value of this object as a number. the exact re
turn type is implementation dependent. typical types are long and double. [propget] hresult currentvalue( [out] variant currentvalue ); parameters currentvalue re
turns the current value represented by this object. see the section about. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. maximumvalue() re
turns the maximal value that can be represented by this object. th...
...ntation dependent. typical types are long and double. [propget] hresult currentvalue( [out] variant currentvalue ); parameters currentvalue re
turns the current value represented by this object. see the section about. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. maximumvalue() re
turns the maximal value that can be represented by this object. the type of the re
turned value is implementation dependent. it does not have to be the same type as that re
turned by method currentvalue(). [propget] hresult maximumvalue( [out] variant maximumvalue ); parameters maximumvalue re
turns the maximal value in an implementation dependent type. if this object has no upper bound then an empty object is re
turned. see the section about. re
turn value s_ok. minimumvalue() ret...
...And 3 more matches
mozIThirdPartyUtil
sthirdpartyuri(in nsiuri afirsturi, in nsiuri aseconduri); boolean isthirdpartywindow(in nsidomwindow awindow, [optional] in nsiuri auri); methods isthirdpartychannel() determine whether the given channel and its content window hierarchy is third party. this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpartycookie' property set, then: if auri is null, re
turn false. otherwise, find the uri of the channel, determine whether it is foreign with respect to auri, and re
turn. find the uri of the channel and determine whether it is third party with respect to the uri of the channel. if so, re
turn. obtain the bottommost nsidomwindow, and its same-type parent if it exists, from the channel's notification callbacks. then: if the parent is the same as the bot...
...s foreign with respect to auri, and re
turn. find the uri of the channel and determine whether it is third party with respect to the uri of the channel. if so, re
turn. obtain the bottommost nsidomwindow, and its same-type parent if it exists, from the channel's notification callbacks. then: if the parent is the same as the bottommost window, and the channel has the load_document_uri flag set, re
turn false. this represents the case where a toplevel load is occurring and the window's uri has not yet been updated. (we have already checked that auri is not foreign with respect to the channel uri.) otherwise, re
turn the result of isthirdpartywindow() with arguments of the channel's bottommost window and the channel uri, respectively. therefore, both the channel's uri and each level in the wind...
.../mail.google.com/", achannel has a uri of "http://google.com/", and its parent is the topmost content window with a uri of "http://mozilla.com", the result will be true. boolean isthirdpartychannel( in nsichannel achannel, in nsiuri auri optional ); parameters achannel the channel associated with the load. auri optional a uri to test against. if null, the uri of the channel will be used. re
turn value true if auri is third party with respect to the channel uri or any of the uris associated with the same-type window hierarchy of the channel. isthirdpartyuri() determine whether two uris are third party with respect to each other. this is determined by computing the base domain for both uris. if they can be determined, and the base domains match, the request is defined as first party. if i...
...And 3 more matches
nsIAccessible
cessible.getaccessiblebelow() to get left, right, top or below placed accessible methods getkeybindings provides array of localized string of global keyboard accelerator for the given action index supported by accessible. getstate provides a bit fields of accessible states which describe boolean properties of accessible. ...
...he given action index supported by accessible. getstate provides a bit fields of accessible states which describe boolean properties of accessible. groupposition this method re
turns grouping information. used for tree items, list items, tab panel labels, radio buttons, etc. also used for collectons of non-text objects. getchildatpoint this method re
turns an accessible child which contains the coordinate at (x, y) in screen pixels. ...
...ribe boolean properties of accessible. groupposition this method re
turns grouping information. used for tree items, list items, tab panel labels, radio buttons, etc. also used for collectons of non-text objects. getchildatpoint this method re
turns an accessible child which contains the coordinate at (x, y) in screen pixels. getchildat this method re
turns nth accessible child using zero-based index or last child if index than less than zero. getaccessibletoright this method re
turns an accessible node geometrically to the right of this one. ...
...And 3 more matches
nsIBinaryInputStream
th), retval] out pruint8 abytes); void readbytes(in pruint32 alength, [size_is(alength), retval] out string astring); acstring readcstring(); double readdouble(); float readfloat(); astring readstring(); void setinputstream(in nsiinputstream ainputstream); methods read8() reads from the stream. pruint8 read8(); parameters none. re
turn value an 8-bit integer read from the stream. read16() reads from the stream. pruint16 read16(); parameters none. re
turn value a 16-bit integer read from the stream. read32() reads from the stream. pruint32 read32(); parameters none. re
turn value a 32-bit integer read from the stream. read64() reads from the stream. warning: this method is available from javascript; however jav...
...int16 read16(); parameters none. re
turn value a 16-bit integer read from the stream. read32() reads from the stream. pruint32 read32(); parameters none. re
turn value a 32-bit integer read from the stream. read64() reads from the stream. warning: this method is available from javascript; however javascript does not support 64-bit integers. pruint64 read64(); parameters none. re
turn value a 64-bit integer read from the stream. readarraybuffer() read opaque bytes from the stream, storing the results in an arraybuffer. unsigned long readarraybuffer(in pruint32 alength, in jsval aarraybuffer); parameters alength the number of bytes that should be read. aarraybuffer the arraybuffer in which to store the results. ...
... readbytearray() reads an opaque byte array from the stream, storing the results as an array of pruint8s. ...
...And 3 more matches
nsIBrowserSearchService
void removeengine(in nsisearchengine engine); void restoredefaultengines(); attributes attribute type description currentengine nsisearchengine the currently active search engine. may be null if there are no visible search engines. defaultengine nsisearchengine the default search engine. re
turns the first visible engine if the default engine is hidden. may be null if there are no visible search engines. read only. originaldefaultengine nsisearchengine the original default engine. this differs from the "defaultengine" attribute in that it always re
turns a given build's default engine, regardless of whether it is hidden. read only. methods addengine()...
... optional: a unique shortcut that can be used to retrieve the search engine. description optional: a description of the search engine. method the http request method used when submitting a search query. must be a case insensitive value of either "get" or "post". url the url to which search queries should be sent. must not be null. getdefaultengines() re
turns an array of all default search engines. this includes all loaded engines that aren't in the user's profile directory (ns_app_user_search_dir). void getdefaultengines( [optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines ); parameters enginecount the number of default search engines. engines an array of the d...
...includes all loaded engines that aren't in the user's profile directory (ns_app_user_search_dir). void getdefaultengines( [optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines ); parameters enginecount the number of default search engines. engines an array of the default nsisearchengines. ...
...And 3 more matches
nsICategoryManager
ategory being modified. ("protocol") aentry the name of the category entry being modified. ("http") avalue the value for the category entry. ("moz.httprulez.1") apersist no longer supported. category entries never persist across application sessions. you must pass false for this parameter. areplace a flag indicating whether or not to overwrite the value of an existing category entry. re
turn value the previous value for the given category entry (if any). exceptions thrown ns_error_invalid_arg this error is re
turned if areplace is false and the category entry already has a value, or if apersist is true. deletecategory() delete a category and all entries. note: if the category does not exist, then this method does nothing. void deletecategory( in string acategory ); para...
...persist ); parameters acategory the name of the category being modified. ("protocol") aentry the name of the category entry being deleted. ("http") apersist ignored. category entries never persist across sessions. you should always pass false for this parameter. enumeratecategories() enumerate all existing categories. nsisimpleenumerator enumeratecategories(); parameters none. re
turn value a simple enumerator, each result qis to nsisupportscstring. enumeratecategory() enumerate the entries in a category. nsisimpleenumerator enumeratecategory( in string acategory ); parameters acategory the category to be enumerated. re
turn value a simple enumerator, each result qis to nsisupportscstring. getcategoryentry() get the value for the given category's entry. string...
...this pointer must be released using nsimemory.free() when it is no longer needed. exceptions thrown ns_error_not_available indicates that either the category or entry is undefined. ...
...And 3 more matches
nsICryptoHash
ash algorithm 256 sha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes the hash object and produces the actual hash data. note: this method may be called any time after " .. manch("init") .. " is called. this call resets the object. acstring finish( in prbool aascii ); parameters aascii if true then the re
turned value is a base-64 encoded string. if false, then the re
turned value is binary data. re
turn value this method re
turns a hash of the data that was read by this object. this can be either binary data or a base-64 encoded string. exceptions thrown ns_error_not_initialized indicates that init() or initwithstring() has not been called. init() initialize the hashing object. this method may...
...var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); // s now contains your hash in hex this gives 5eb63bbbe01eeed093cb22bb8f5acdc3 for the hash value. this example, while simple, shows most of t...
...var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); // s now contains your hash in hex this gives 5eb63bbbe01eeed093cb22bb8f5acdc3 for the hash value. this example, while simple, shows most of the functionality of the interface. the first thing to note is that when you call th...
...And 3 more matches
nsIDOMElement
idomattr newattr) nsidomattr setattributenodens(in nsidomattr newattr) void setattributens(in domstring namespaceuri, in domstring qualifiedname, in domstring value) attributes attribute type description tagname domstring the element tag name. read only. methods getattribute() get an attribute value. domstring getattribute( in domstring name ); parameters name attribute name re
turn value a domstring containing the attribute value. getattributenode() get an attribute node. nsidomattr getattributenode( in domstring name ); parameters name attribute name re
turn value a nsidomattr corresponding to the attribute. getattributenodens() get an attribute node in a given namespace. nsidomattr getattributenodens( in domstring namespaceuri, in domstring localname ); parameter...
...ibutenode() get an attribute node. nsidomattr getattributenode( in domstring name ); parameters name attribute name re
turn value a nsidomattr corresponding to the attribute. getattributenodens() get an attribute node in a given namespace. nsidomattr getattributenodens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name re
turn value a nsidomattr corresponding to the attribute. getattributens() get an attribute value in a given namespace. domstring getattributens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name re
turn value a domstring containing the attribute value. getelementsbytagname() get all descendants of a tag name. nsidomnodelist getelem...
... get an attribute value in a given namespace. domstring getattributens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname attribute name re
turn value a domstring containing the attribute value. getelementsbytagname() get all descendants of a tag name. nsidomnodelist getelementsbytagname( in domstring name ); parameters name tag name re
turn value a nsidomnodelist containg all the descendants of this tag name. getelementsbytagnamens() get all descendants of a tag name in a given namespace. nsidomnodelist getelementsbytagnamens( in domstring namespaceuri, in domstring localname ); parameters namespaceuri namespace uri localname tag name re
turn value a nsidomnodelist containg all the descendants of this tag name. hasattribute() ...
...And 3 more matches
nsIExternalProtocolService
ation handlers in either the nsihandlerservice datastore or registered with the os. boolean externalprotocolhandlerexists( in string aprotocolscheme ); parameters aprotocolscheme the scheme from a url: http, ftp, mailto, and so on. note: aprotocolscheme should not include a trailing colon, which is part of the uri syntax, not part of the scheme itself. that is, pass "mailto" not "mailto:". re
turn value true if we have a handler and false otherwise. getapplicationdescription() gets a human-readable description for the application responsible for handling a specific protocol. astring getapplicationdescription( in autf8string ascheme ); parameters ascheme the scheme to look up. for example, "mms". re
turn value this code makes little sense and needs to be cleaned up. -nickolay <pre> // f...
...")) { // handler for http:// urls exists } else { // suppress external-load warning for standard browser schemes pref("network.protocol-handler.external.tlcxp", true); pref("network.protocol-handler.app.tlcxp, "lzx"); } </pre> getprotocolhandlerinfo() retrieve the handler for the given protocol. ...
...getprotocolhandlerinfofromos() given a scheme, looks up the protocol info from the os. this should be overridden by each os's implementation. ...
...And 3 more matches
nsILocalFileMac
silocalfile adoctoload, in boolean alaunchinbackground); void opendocwithapp(in nsilocalfile aapptoopenwith, in boolean alaunchinbackground); void setfiletypeandcreatorfromextension(in string aextension); obsolete since gecko 1.9.2 void setfiletypeandcreatorfrommimetype(in string amimetype); obsolete since gecko 1.9.2 attributes attribute type description bundledisplayname astring re
turns the display name of the application bundle (usually the human readable name of the application) read only. bundleidentifier autf8string re
turns the identifier of the bundle. read only. filecreator ostype native code only! filesizewithresfork print64 re
turns the combined size of both the data fork and the resource fork (if present) rather than just the size of the data fork as re
turned by...
...d only. filetype ostype file type and creator attributes. native code only! constants constant value description current_process_creator 0x8000000 use with setfiletype() to specify the signature of current process. obsolete since gecko 2.0 methods native code only!getcfurl note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, re
turns the target of the alias. if followlinks is false, re
turns the unresolved alias file. note: supported only for xp_macosx. cfurlref getcfurl(); parameters none. re
turn value the cfurlref of the file object. the caller is responsible for calling cfrelease() on it. native code only!getfsref note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true...
...e target of the alias. if followlinks is false, re
turns the unresolved alias file. note: supported only for xp_macosx. cfurlref getcfurl(); parameters none. re
turn value the cfurlref of the file object. the caller is responsible for calling cfrelease() on it. native code only!getfsref note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, re
turns the target of the alias. if followlinks is false, re
turns the unresolved alias file. note: supported only for xp_macosx. fsref getfsref(); parameters none. re
turn value the fsref of the file object. native code only!getfsspec note: observes the state of the followlinks attribute. if the file object is an alias and followlinks is true, re
turns the target of the alias. if followlinks is false, re...
...And 3 more matches
nsINavHistoryQueryOptions
"folders with annotation x"). expandqueries boolean when set, allows items with "place:" uris to appear as containers, with the container's contents filled in from the stored query. if not set, these will appear as normal items. doesn't do anything if excludequeries is set. defaults to false. note that this has no effect on folder links, which are place: uris re
turned by nsinavbookmarkservice's getfolderuri method. these are always expanded and will appear as bookmark folders. includehidden boolean most items in history are marked "hidden." only toplevel pages that the user sees in the url bar are not hidden. hidden things include the content of iframes and all images on web pages. normally, you don't want these things. if ...
...t of iframes and all images on web pages. normally, you don't want these things. if you do, set this flag and you'll get all items, even hidden ones. does nothing for bookmark queries. defaults to false. maxresults long this is the maximum number of results that you want. the query is exeucted, the results are sorted, and then the top maxresults results are taken and re
turned. set to "0" (the default) to get all results. this does not work in conjunction with sorting by title. this is because sorting by title requires us to sort after using locale-sensetive sorting (as opposed to letting the database do it for us). instead, we get the result ordered by date, pick the maxresult most recent ones, and then sort by title. querytype s...
...as_full_visit 2 this is identical to result_type_visit except that individual result nodes will have type "fullvisit". this is used for the attributes that are not commonly accessed to save space in the common case (the lists can be very long). note: supported only for query_type_history. results_as_date_query 3 re
turns nsinavhistoryqueryresultnode nodes for each predefined date range where we had visits. note: supported only for query_type_history. results_as_site_query 4 re
turns nsinavhistoryqueryresultnode nodes for each site where we have visits. note: supported only for query_type_history. results_as_da...
...And 3 more matches
nsISHistoryListener
n interface you can implement to receive notifications about activities that occur in session history, and optionally cancel them. inherits from: nsisupports last changed in gecko 1.7 a session history listener is notified when pages are added to, removed from, and loaded from session history. the listener can prevent any action (except adding a new session history entry) from happening by re
turning false from the corresponding callback method. a session history listener can be registered on a particular nsishistory instance via the nsishistory.addshistorylistener() method. method overview boolean onhistorygoback(in nsiuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in long aindex, in nsiuri agotouri); void onhistorynewentry(in nsiuri ...
... boolean onhistorypurge(in long anumentries); boolean onhistoryreload(in nsiuri areloaduri, in unsigned long areloadflags); methods onhistorygoback() called when navigating to a previous session history entry, for example due to an nsiwebnavigation.goback() call. boolean onhistorygoback( in nsiuri abackuri ); parameters abackuri the uri of the session history entry being navigated to. ...
...onhistorygotoindex() called when navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called. ...
...And 3 more matches
nsISelection
read only. focusoffset long the offset within the (text) node where the selection ends. read only. iscollapsed boolean indicates ...
...rentnode); void selectionlanguagechange(in boolean langrtl); domstring tostring(); attributes attribute type description anchornode nsidomnode re
turns the node in which the selection begins. read only. anchoroffset long the offset within the (text) node where the selection begins. read only. focusnode nsidomnode re
turns the node in which the selection ends. read only. focusoffset long the offset within the (text) node where the selection ends. read only. iscollapsed boolean indicates if the selection is collapsed() or not. read only. rangecount long re
turns the number of ranges in the selection. read only. methods addrange() adds a nsidomrange to the current se...
... blink there. void collapsetoend(); parameters none collapsetostart() collapses the whole selection to a single point at the start of the current selection (regardless of direction). if content is focused and editable, the caret will blink there. void collapsetostart(); containsnode() indicates whether the nsidomnode is part of the selection. ...
...And 3 more matches
nsISupports proxies
e 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. ...
... 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 of that stack frame. accessing it might even cause a crash. ...
...on-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 re
turn immediately and you will lose all re
turn information. ns_ok will be re
turned 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 of that stack frame. accessing it might even cause a crash. for example: myfoo->bar(&x) ... stack frame goes away ... bar(print32 *x) { ...
...And 3 more matches
nsITransactionList
nsisupports last changed in gecko 1.7 method overview nsitransactionlist getchildlistforitem(in long aindex); nsitransaction getitem(in long aindex); long getnumchildrenforitem(in long aindex); boolean itemisbatch(in long aindex); attributes attribute type description numitems long the number of transactions contained in this list. read only. ...
...ldlistforitem(in long aindex); nsitransaction getitem(in long aindex); long getnumchildrenforitem(in long aindex); boolean itemisbatch(in long aindex); attributes attribute type description numitems long the number of transactions contained in this list. read only. methods getchildlistforitem() re
turns the list of children associated with the item at aindex. implementations may re
turn null if there are no children, or an empty list. ...
...index); long getnumchildrenforitem(in long aindex); boolean itemisbatch(in long aindex); attributes attribute type description numitems long the number of transactions contained in this list. read only. methods getchildlistforitem() re
turns the list of children associated with the item at aindex. implementations may re
turn null if there are no children, or an empty list. the list re
turned is addref'd so it is up to the caller to release the transaction when it is done. ...
...And 3 more matches
nsITransactionManager
r of items on the undo stack. read only. methods addlistener() adds a listener to the transaction manager's notification list. listeners are notified whenever a transaction is done, undone, or redone. the listener's nsitransactionlistener.addref() method is called. void addlistener( in nsitransactionlistener alistener ); parameters alistener the nsitransactionlistener to add. beginbatch()
turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's dotransaction() method to be aggregated together until endbatch() is called. this mode allows an application to execute and group together several independent transactions so they can be undone with a single call to undotransaction(). void beginbatch(); parameters none. clear() clears the und...
...tion.dotransaction() method, then pushes it on the undo stack. this method calls the transaction's nsitransaction.addref() method. the transaction's nsitransaction.release() method will be called when the undo or redo stack is pruned or when the transaction manager is destroyed. void dotransaction( in nsitransaction atransaction ); parameters atransaction the nsitransaction to do. ...
...nsitransaction.addref() method. the transaction's nsitransaction.release() method will be called when the undo or redo stack is pruned or when the transaction manager is destroyed. void dotransaction( in nsitransaction atransaction ); parameters atransaction the nsitransaction to do. endbatch()
turns off the transaction manager's batch mode. void endbatch(); parameters none. getredolist() re
turns the list of nsitransaction on the redo stack. note that the transaction at the top of the redo stack will actually be at the index n-1 in the list, where n is the number of items in the list. nsitransactionlist getredolist(); parameters none. re
turn value a list of nsitransaction on the redo stack. getundolist() re
turns the list of nsitransaction on the undo stack. note that the transaction at ...
...And 3 more matches
nsIURIFixup
lag_none 0 no fixup flags. fixup_flag_allow_keyword_lookup 1 allow the fixup to use a keyword lookup service to complete the uri. the fixup object implementer should honour this flag and only perform any lengthy keyword (or search) operation if it is set. fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to
turn foo into www.foo.com. fixup_flag_use_utf8 4 use utf-8 to encode the uri instead of the platform character set. fixup_flag_fix_scheme_typos 8 fix common scheme typos. methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar. nsiuri createexposableuri( in nsiuri a...
... use utf-8 to encode the uri instead of the platform character set. fixup_flag_fix_scheme_typos 8 fix common scheme typos. methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar. nsiuri createexposableuri( in nsiuri auri ); parameters auri the uri to be converted. ...
... keywordtouri() converts the specified keyword string into a uri. ...
...And 3 more matches
nsIXmlRpcClient
null if the server was unreachable or not yet contacted. responsestring readon...
...stener listener, in nsisupports ctxt, in string methodname, in nsisupports arguments, in pruint32 count); attributes attribute type description serverurl readonly nsiurl the url of the xml-rpc server inprogress readonly boolean whether or not a call is in progress fault readonly nsixmlrpcfault the most recent xml-rpc fault from re
turned from this server. null if the last call didn't re
turn an xml-rpc fault. ...
...uint32 count); attributes attribute type description serverurl readonly nsiurl the url of the xml-rpc server inprogress readonly boolean whether or not a call is in progress fault readonly nsixmlrpcfault the most recent xml-rpc fault from re
turned from this server. null if the last call didn't re
turn an xml-rpc fault. result readonly nsisupports the most recent xml-rpc call result re
turned from this server. null if the last call didn't re
turn a valid result. responsestatus readonly unsigned long the most recent http status code re
turned from this server. null if the server was unreachable or not yet contacted. responsestring readonly unsigned long the most recent http status code re
turned from this server. null if the server was unreachable or not yet contacted. constants ...
...And 3 more matches
Xray vision
ghly malleable language. scripts running in web pages can add extra properties to dom objects (also known as expando properties) and even redefine standard dom objects to do something unexpected. if chrome code relies on such modified objects, it can be tricked into doing things it shouldn't. for example: window.confirm() is a dom api that's supposed to ask the user to confirm an action, and re
turn a boolean depending on whether they clicked "ok" or "cancel". a web page could redefine it to re
turn true: window.confirm = function() { re
turn true; } any privileged code calling this function and expecting its result to represent user confirmation would be deceived. this would be very naive, of course, but there are more subtle ways in which accessing content objects from chrome can cause s...
... problem: the main concern xrays solve is with untrusted web content manipulating objects, and web content is usually working with dom objects. ...
... components.utils.waivexrays(gbrowser.contentwindow).date.getfullyear(); // -> 1000 however, there are some situations in which privileged code will access javascript objects that are not themselves dom objects and are not properties of dom objects. for example: the detail property of a customevent fired by content could be a javascript object or date as well as a string or a primitive the re
turn value of evalinsandbox() and any properties attached to the sandbox object may be pure javascript objects also, the webidl specifications are starting to use javascript types such as date and promise: since webidl definition is the basis of dom xrays, not having xrays for these javascript types starts to seem arbitrary. so, in gecko 31 and 32 we've added xray support for most javascript built-...
...And 3 more matches
Creating a gloda message query
aintname to be used (e.g. query.subjectmatches(searchstring) for message subject (compare fundattr.js line 145 ). create a collection from the query your listener is notified as messages are added to the collection as the database query completes. you may also see new messages show up if new messages are indexed that meet the constraints. ...
...each message is a glodamessage, whose database-row attributes are implemented/defined in gloda's datamodel.js. however, many attributes are dynamically contributed by built-in...
...message id. this is a locally unique identifier. folder: the folder the message is found in, as represented by a glodafolder instance. conversation: the conversation the message belongs to, as represented by a glodaconversation instance. somewhat magic attributes: headermessageid: the contents of the message-id header of the message. you probably should not be using this. ...
...And 3 more matches
nsIMsgCloudFileProvider
turl acstring readonly: a chrome url for an xhtml page displayed within the filelink preferences dialog, used for displaying and setting provider-specific settings once the account has already been set up. this url should not point to external web content. fileuploadsizelimit long readonly: the upper size limit in bytes for a file to be uploaded. if this value is not known, re
turns -1. remainingfilespace long long readonly: the remaining storage space available for this account in bytes. if this value is not known, re
turns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, re
turns -1. lasterror acstring readonly: the last error message received from the server. ...
...is not known, re
turns -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 re
turned when it appears that there is no active network connection. autherr 0x8055001e re
turned when authorizing has failed. uploaderr 0x8055311a re
turned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055311b re
turned when uploading has failed because the user has exceeded their storage quota. uploadexceedsfilelimit 0...
...ars that there is no active network connection. autherr 0x8055001e re
turned when authorizing has failed. uploaderr 0x8055311a re
turned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055311b re
turned when uploading has failed because the user has exceeded their storage quota. uploadexceedsfilelimit 0x8055311c re
turned when uploading has failed because the file being uploaded is larger than the file size limit. uploadcanceled 0x8055311d re
turned when uploading has stopped because it was cancelled by the user. methods init() initializes an nsimsgcloudfileprovider to be associated with a particular account. this should probably be called immediately after instantiation. void init(in st...
...And 3 more matches
Library
the library object represents a native library loaded by the ctypes open() method. its methods let you declare symbols exported by the library, and to manage the library. method overview close(); cdata declare(name, [abi, ], re
turntype[, argtype1, ...]); methods close() closes the library. you need to call this once you're done using the library. close(); parameters none. declare() declares an api from the native library, allowing it to be used from javascript. ...
...see abi constants. ...
...he name of the symbol exported by the native library that is to be declared as usable from javascript abi the abi used by the exported function; this will be ctypes.default_abi for most libraries, except for windows libraries, which will be ctypes.winapi_abi or ctypes.stdcall_abi. see abi constants. you don't need to provide this for exported data; it's only needed for function declarations. ...
...And 3 more matches
StructType
structtype represents c structures. syntax re
turns a ctype object describing a new structure data type. this data type provides the ability to define and manipulate values of the c struct type. note: at this time, there isn't a way to denote a packed structure (that is, one created in c using #pragma pack). ctype structtype( name[, fields] ); parameters name the name of the structure. must be a string. fields optional an array of field descriptors, describing all the entries in the structure. if this isn't specified, the structure is considered opaque and you can't access its contents directly. you can call the resulting type's define() method to assign it a non-opaque type later. ...
...e the name of the structure. must be a string. fields optional an array of field descriptors, describing all the entries in the structure. if this isn't specified, the structure is considered opaque and you can't access its contents directly. you can call the resulting type's define() method to assign it a non-opaque type later. see opaque structures for further explanation and an example. re
turn value a ctype object describing the newly created struct data type. exceptions thrown typeerror the name is not a string, or one or more of the fields does not have a defined size. rangeerror the size of the structure, in bytes, cannot be represented both as a size_t and as a javascript number. describing fields the fields array is comprised of field descriptors, one for each field in ...
... property type description name string the type's name. read only. for primitive types, this is just the name of the corresponding c type. for structure and opaque pointer types, this is simply the string that was passed to the constructor. for other function, pointer, and array types, this should be a valid c type expression. ptr ctype re
turns a ctype representing the data type "pointer to this type". this is the result of calling ctypes.pointertype(the_type). read only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. method overview define(fields) methods inherited from ctype ctype array...
...And 3 more matches
ctypes
the ctypes object contains methods and predefined data types used to create and manage a library. method overview ctype arraytype(type[, length]); cdata cast(data, type); ctype functiontype(abi, re
turntype[, argtype1, ...]); cdata int64(n); string libraryname(name); library open(libspec); ctype pointertype(typespec); ctype structtype(name[, fields]); cdata uint64(n); properties property type description errno number the value of the latest system error. similar to errno in libc, available on all platforms. cannot be set. winlasterror number|undefined the value of the latest windows error. similar to getlasterror under windows, available only for windows. ca...
... type on the platform. double a double-precision floating point value that behaves like the double type on the platform. character types character types are 8-bit values that behave like their c counterparts. they're similar to the int8_t and uint8_t types, except conversion is handled differently. for example, ctypes.char.array(30)(str) converts the string str to utf-8 and re
turns a new cdata object of array type. type description char a character type that behaves like the char c type on the platform. signed_char a signed character that behaves like the char type on the platform. unsigned_char an unsigned character that behaves like the unsigned char type on the platform. types whose size varies depending o...
...escription jschar a 16-bit unsigned character. this is different from uint16_t in that c jschar values are automatically converted into 1-character javascript strings. these are unicode characters. special c types these types represent c types that have special meanings. type description void_t the special c type void. this can only be used as a re
turn value type. note: you must use void_t, not void, since void is a keyword in javascript. voidptr_t the c type void *. this is a pointer to an indeterminate type of data. large integer types because javascript doesn't support large (64-bit) integers, js-ctypes provides two data types allowing access to 64-bit integer data. type description int64 ...
...And 3 more matches
Version, UI, and Status Information - Plugins
rsion, and operating system in a user_agent field. if you want to gather usage statistics or just find out the version of your plug-in's host browser, this information can help you. the plug-in calls the npn_useragent method to retrieve the contents of the user_agent field. const char* npn_useragent(npp instance); the instance parameter represents the current plug-in instance. this function re
turns a string that contains the user_agent field of the browser. getting the current version your plug-in should make sure, possibly during initialization, that the version of the plug-in api it is using is compatible with the version the browser is using. to do so, it must find the major and minor version numbers, which are determined when the plug-in and navigator are compiled, and compare them. ...
...es to the major version. changes to the major version numbers probably indicate incompatibility. the plug-in calls the npn_version method to check for changes in major and minor plug-in api version numbers. it gets the values from the plug-in rather than from the browser. void npn_version(int *plugin_major, int *plugin_minor, int *netscape_major, int *netscape_minor); this function re
turns the plug-in version number in plugin_major, the plug-in point release number in plugin_minor, the browser version number in netscape_major, and the browser point release number in netscape_minor. this code declares variables to hold the version numbers and calls npn_version to re
turn the major and minor version numbers for the browser and the plug-in api. int plugin_major, plugin_minor, netsca...
...indowless method finds out whether the current version of the api supports windowless plug-ins. this method for detecting support is only useful on ms windows and mac os x. it starts by using npn_version to get the version numbers. it then uses the netscape_minor version number to find out if the windowless feature, represented by the npvers_has_windowless constant, is supported. if the method re
turns true, a windowless plug-in can confidently proceed. if false is re
turned, windowless plug-ins will not work, and the developer must provide alternatives. bool has_windowless() { int plugin_major, plugin_minor; int netscape_major, netscape_minor; /* find the version numbers. */ npn_version(&plugin_major, &plugin_minor, &netscape_major, &netscape_minor); /* use the netscape...
...And 3 more matches
Debugger.Source - Firefox Developer Tools
t of a block of webassembly code, its properties provide the serialized text as a string. currently only entire modules evaluated via new webassembly.module are represented. spidermonkey constructs exactly one debugger.source for each underlying webassembly module per debugger instance. please note at the time of this writing, support for webassembly is very preliminary. many properties below re
turn placeholder values. convention for descriptions of properties and methods below, if the behavior of the property or method differs between the instance referring to javascript source or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to javascript source” and “if the instance refers to webassembly code”, respectively. if the be...
...nctiondeclaration, or functionexpression productions in the ecmascript standard. if the instance refers to webassembly code, the serialized text representation. the format is yet to be specified in the webassembly standard. currently, the text is an s-expression based syntax. the text generation is disabled if the debugger has the allowwasmbinarysource property set, the "[wasm]" value will be re
turned in this case. binary if the instance refers to webassembly code and the debugger has the allowwasmbinarysource property set, a uint8array that contains the webassembly bytecode. url if the instance refers to javascript source, the filename or url from which this script’s code was loaded. for scripts created by eval or the function constructor, this may be a synthesized filename, start...
...arkup text. the url may be passed to the worker web worker constructor, or the web worker importscripts function. the url may be the name of a xpcom javascript module or subscript. (note that code passed to eval, the function constructor, or a similar function isnot considered to be loaded from a url; the url accessor on debugger.source instances for such sources should re
turn undefined.) if the instance refers to webassembly code, the url of the script that called new webassembly.module with the string "> wasm" appended. sourcemapurl if the instance refers to javascript source, if this source was produced by a minimizer or translated from some other language, and we know the url of a source map document relating the source positions in this source to the corre...
...And 3 more matches
Page inspector keyboard shortcuts - Firefox Developer Tools
ve to first node in the tree. home home home move to last node in the tree. end end end expand currently selected node right arrow right arrow right arrow collapse currently selected node left arrow left arrow left arrow (when a node is selected) move inside the node so you can start stepping through attributes. ...
...eft arrow (when a node is selected) move inside the node so you can start stepping through attributes. ...
...ributes of a node shift + tab shift + tab shift + tab (when an attribute is selected) start editing the attribute enter re
turn enter hide/show the selected node h h h focus on the search box in the html pane ctrl + f cmd + f ctrl + f edit as html f2 f2 f2 stop editing html f2 / ctrl +enter f2 / cmd + re
turn f2 / ctrl + enter copy the selected node's outer html ctrl + c cmd + c ctrl + c scroll the selected node into view s s s find the next match in the markup, when searching is active enter re
turn enter find the previous match in the markup, when searching is active shift + enter shift + re
turn shift + enter breadcrumb...
...And 3 more matches
The JavaScript input interpreter - Firefox Developer Tools
e" icon at the right hand side of the single-line entry field, or press ctrl+b (windows/linux) or cmd+b (macos). the multi-line editing pane opens on the left side the of web console. you can enter multiple lines of javascript by default in this mode, pressing enter after each one. to execute the snippet that is currently in the editing pane, click the run button or press ctrl+enter (or cmd+re
turn on macos). the snippet is echoed under the input prompt (in the right-side pane), followed by the result. you can also select a range of lines in the editing pane, and run just the code on those lines. starting in firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an...
...s displayed in the console. repeatedly typing f9 on windows and linux ( ctrl+r on mac) cycles backwards through the matches. once you have initiated the reverse search, you can use shift + f9 on windows or linux ( ctrl+s on mac) to search forward in the list of matches. you can also use the ⋀ and ⋁ icons in the expression search bar. when you find the expression you want, press enter (re
turn) to execute the statement. working with iframes if a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. there are three ways to select an iframe using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame)...
...h no arguments: cd(); for example, suppose we have a document that embeds an iframe: <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <iframe id="frame1" src="static/frame/my-frame1.html"></iframe> </body> </html> the iframe defines a new function: <!doctype html> <html> <head> <meta charset="utf-8"> <script> function whoareyou() { re
turn "i'm frame1"; } </script> </head> <body> </body> </html> you can switch context to the iframe like this: cd("#frame1"); now you'll see that the global window's document is the iframe: and you can call the function defined in the iframe: helper commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easi...
...And 3 more matches
Basic animations - Web APIs
mgw > canvasxsize) { // image width larger than canvas clearx = imgw; } else { clearx = canvasxsize; } if (imgh > canvasysize) { // image height larger than canvas cleary = imgh; } else { cleary = canvasysize; } // get canvas context ctx = document.getelementbyid('canvas').getcontext('2d'); // set refresh rate re
turn setinterval(draw, speed); } function draw() { ctx.clearrect(0, 0, clearx, cleary); // clear the canvas // if image is <= canvas size if (imgw <= canvasxsize) { // reset, start from beginning if (x > canvasxsize) { x = -imgw + x; } // draw additional image1 if (x > 0) { ctx.drawimage(img, -imgw + x, y, imgw, imgh); ...
...innerheight / 2 }; window.onmousemove = function(e) { m.x = e.clientx; m.y = e.clienty; } function gc() { var s = "0123456789abcdef"; var c = "#"; for (var i = 0; i < 6; i++) { c += s[math.ceil(math.random() * 15)] } re
turn c } var a = []; window.onload = function myfunction() { cn = document.getelementbyid('cw'); c = cn.getcontext('2d'); for (var i = 0; i < 10; i++) { var r = 30; var x = math.random() * (innerwidth - 2 * r) + r; var y = math.random() * (innerheight - 2 * r...
...>div:hover { opacity: 1 } .touch { background: #8bc34a } .off { background: #f44336 } .hide { opacity: 0 } </style> </html> javascript function tmz() { var e = new date(t), i = new date, n = math.abs(i.getminutes() - e.getminutes()), o = math.abs(i.getseconds() - e.getseconds()); re
turn n + " : " + o } function coll(t, e) { re
turn t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y } function snake() { this.w = 15, this.h = 15, this.dx = 1, this.dy = 1, this.xf = 1, this.yf = 1, this.sn = []; for (var t = { x: w / 2, y: h / 2 }, e = 0; e < 5; e++) this.sn.push(object.assign({}, t)), t.
...And 3 more matches
DOMParser - Web APIs
you can perform the opposite operation—converting a dom tree into xml or html source—using the xmlserializer interface. in the case of an html document, you can also replace portions of the dom with new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties. ...
...an also replace portions of the dom with new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties. these properties can also be read to fetch html fragments corresponding to the corresponding dom subtree. syntax let domparser = new domparser() methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) re
turn either document or xmldocument depending on the mimetype argument. parameters this method has 2 parameters (both required): string the domstring to be parsed. it must contain either html, xml, xhtml+xml, or svg document. mimetype a domstring. this string determines a class of the the method's re
turn value. the possible values are the following: mimetype doc.constructo...
... parsing svg or html the domparser can also be used to parse an svg document (firefox...
...And 3 more matches
DocumentOrShadowRoot - Web APIs
the documentorshadowroot mixin of the shadow dom api provides apis that are shared between documents and shadow roots. the following features are included in both document and shadowroot. properties documentorshadowroot.activeelementread only re
turns the element within the shadow tree that has focus. documentorshadowroot.fullscreenelementread only re
turns the element that's currently in full screen mode for this document. ...
...ocuments and shadow roots. the following features are included in both document and shadowroot. properties documentorshadowroot.activeelementread only re
turns the element within the shadow tree that has focus. documentorshadowroot.fullscreenelementread only re
turns the element that's currently in full screen mode for this document. documentorshadowroot.pointerlockelement read only re
turns the element set as the target for mouse events while the pointer is locked. it re
turns null if lock is pending, the pointer is unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only re
turns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods documentorshadowroot.caretpositionfrompoint()...
...e element set as the target for mouse events while the pointer is locked. it re
turns null if lock is pending, the pointer is unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only re
turns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods documentorshadowroot.caretpositionfrompoint() re
turns a caretposition object containing the dom node containing the caret, and caret's character offset within that node. documentorshadowroot.elementfrompoint() re
turns the topmost element at the specified coordinates. ...
...And 3 more matches
Element.getBoundingClientRect() - Web APIs
the result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. ...
...the result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. ...
...the size of an element and its position relative to the viewport. the element's size is equal to its width/height + padding + border-width in the case that the standard box model is being used, or width/height only if box-sizing: border-box has been set on it. syntax domrect = element.getboundingclientrect(); value the re
turned value is a domrect object which is the union of the rectangles re
turned by getclientrects() for the element, i.e., the css border-boxes associated with the element. the result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. properties other than width and height are relative to the top-left of the viewport. empty border-boxes are ...
...And 3 more matches
HTMLCanvasElement - Web APIs
canvasprintstate interface. the callback can get the context to draw to from the printstate object and must then call done() on it when finished. the purpose of mozprintcallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. see this blog post. methods inherits methods from its parent, htmlelement. ...
...hen finished. the purpose of mozprintcallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. see this blog post. methods inherits methods from its parent, htmlelement. htmlcanvaselement.capturestream() re
turns a canvascapturemediastream that is a real-time video capture of the surface of the canvas. htmlcanvaselement.getcontext() re
turns a drawing context on the canvas, or null if the context id is not supported. a drawing context lets you draw on the canvas. ...
... post. methods inherits methods from its parent, htmlelement. htmlcanvaselement.capturestream() re
turns a canvascapturemediastream that is a real-time video capture of the surface of the canvas. htmlcanvaselement.getcontext() re
turns a drawing context on the canvas, or null if the context id is not supported. a drawing context lets you draw on the canvas. calling getcontext with "2d" re
turns a canvasrenderingcontext2d object, whereas calling it with "webgl" (or "experimental-webgl") re
turns a webglrenderingcontext object. this context is only available on browsers that implement webgl. ...
...And 3 more matches
HTMLDialogElement.close() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. ...
... examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. ...
... examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method. ...
...And 3 more matches
IDBDatabaseSync - Web APIs
ed database. name readonly domstring the name of the connected database. objectstores readonly domstringlist the names of the object stores that exist in the connected database. version readonly domstring the version of the connected database. has the null value when the database is first created. methods createobjectstore() creates and re
turns a new object store with the given name in the connected database. idbobjectstoresync createobjectstore( in domstring name, in domstring keypath, in optional boolean autoincrement ) raises (idbdatabaseexception); parameters name the name of a new object store. keypath the key path used by the new object store. if a null path is specified, then the object store does not have a key...
... domstring keypath, in optional boolean autoincrement ) raises (idbdatabaseexception); parameters name the name of a new object store. keypath the key path used by the new object store. if a null path is specified, then the object store does not have a key path, and uses out-of-line keys. autoincrement if true, the object store uses a key generator; if false, it does not use one. re
turns idbobjectstoresync an object to access the newly created object store. exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openobjectstore() opens the object store with the given name in the connected database using the sp...
...dy exists in the connected database. openobjectstore() opens the object store with the given name in the connected database using the specified mode. idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short mode ) raises (idbdatabaseexception); parameters name the name of the object store to open. mode the mode that is used to access the object store. re
turns idbobjectstoresync an object to access the opened object store. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if an object store with the given name (based on case-sensitive comparison) already exists in the connected database. removeobjectstore() destroys an object store with the given name, as well as all indexes that reference th...
...And 3 more matches
IDBIndexSync - Web APIs
unique readonly boolean if true, a key can have only one value within the index; if false, a key can have duplicate values. methods add() stores the given value into this index, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters re
turns exceptions this method can raise a idbdatabaseexception with the following code: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the val...
...onding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. get() retrieves the value from this index for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. re
turns any the retrieved value from the index. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. getobject() retrieves and re
turns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameter...
... exceptions this method can raise a idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. ...
...And 3 more matches
KeyboardEvent.key - Web APIs
if the keyboardevent represents the press of a dead key, the key value must be "dead". ...
... if the keyboardevent represents the press of a dead key, the key value must be "dead". ...
... if the keyboardevent represents the press of a dead key, the key value must be "dead". ...
...And 3 more matches
MediaStream.getTrackById() - Web APIs
example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. ...
... example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. ...
... example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. ...
...And 3 more matches
MediaStream - Web APIs
sists of several tracks such as video or audio tracks. each track is specified as an instance of mediastreamtrack.you can obtain a mediastream object either by using the constructor or by calling mediadevices.getusermedia(). some user agents subclass this interface to provide more precise information or functionality, like in canvascapturemediastream. ...
... mediastream.ended read only a boolean value set to true if the end of the stream has been reached. ...
... an eventhandler containing the action to perform when a removetrack event is fired when a mediastreamtrack object is removed from it. methods this interface inherits methods from its parent, eventtarget. mediastream.addtrack() stores a copy of the mediastreamtrack given as argument. if the track has already been added to the mediastream object, nothing happens. ...
...And 3 more matches
MouseEvent - Web APIs
though the mouseevent.initmouseevent() method is kept for backward compatibility, creating of a mouseevent object should be done using the mouseevent() constructor. several more specific events are based on mouseevent, including wheelevent and dragevent. ...
...12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mouseevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mouseevent() creates a mouseevent object. properties this interface also inherits properties of its parents, uievent and event. mouseevent.altkey read only re
turns true if the alt key was down when the mouse event was fired. mouseevent.button read only the button number that was pressed (if applicable) when the mouse event was fired. mouseevent.buttons read only the buttons being depressed (if any) when the mouse event was fired. mouseevent.clientx read only the x coordinate of the mouse pointer in local (dom content) coordinates. mouseevent.cli...
...sed (if applicable) when the mouse event was fired. mouseevent.buttons read only the buttons being depressed (if any) when the mouse event was fired. mouseevent.clientx read only the x coordinate of the mouse pointer in local (dom content) coordinates. mouseevent.clienty read only the y coordinate of the mouse pointer in local (dom content) coordinates. mouseevent.ctrlkey read only re
turns true if the control key was down when the mouse event was fired. mouseevent.metakey read only re
turns true if the meta key was down when the mouse event was fired. mouseevent.movementx read only the x coordinate of the mouse pointer relative to the position of the last mousemove event. mouseevent.movementy read only the y coordinate of the mouse pointer relative to the position of the l...
...And 3 more matches
Node.isConnected - Web APIs
the isconnected read-only property of the node interface re
turns a boolean indicating whether the node is connected (directly or indirectly) to the context object, for example the document object in the case of the normal dom, or the shadowroot in the case of a shadow dom. syntax var isitconnected = nodeobjectinstance.isconnected re
turn value a boolean that is true if the node is connected to its relevant context object, and false if not. ...
...le the document object in the case of the normal dom, or the shadowroot in the case of a shadow dom. syntax var isitconnected = nodeobjectinstance.isconnected re
turn value a boolean that is true if the node is connected to its relevant context object, and false if not. ...
...se of a shadow dom. syntax var isitconnected = nodeobjectinstance.isconnected re
turn value a boolean that is true if the node is connected to its relevant context object, and false if not. ...
...And 3 more matches
RTCDataChannel - Web APIs
which specifies the type of javascript object which should be used to represent binary data received on the rtcdatachannel. values allowed by the websocket.binarytype property are also permitted here: "blob" if blob objects are being used or "arraybuffer" if arraybuffer objects are being used. ...
... only the read-only rtcdatachannel property bufferedamount re
turns the number of bytes of data currently queued to be sent over the data channel.bufferedamountlowthreshold the rtcdatachannel property bufferedamountlowthreshold is used to specify the number of bytes of buffered outgoing data that is considered "low." the default value is 0.id read only the read-only rtcdatachannel property id re
turns an id number (between 0 and 65,534) which uniquely identifies the rtcdatachannel.label read only the read-only rtcdatachannel property label re
turns a domstring containing a name describing the data channel. ...
...read only the read-only rtcdatachannel property id re
turns an id number (between 0 and 65,534) which uniquely identifies the rtcdatachannel.label read only the read-only rtcdatachannel property label re
turns a domstring containing a name describing the data channel. ...
...And 3 more matches
RTCIceTransport - Web APIs
component read only the ice component being used by the transport. the value is one of the strings from the rtcicetransport enumerated type: "rtp" or "rtsp". gatheringstate read only a domstring indicating which gathering state the ice agent is currently in. the value is one of those included in the rtcicegathererstate enumerated type: "new", "gathering", or "complete". role read only re
turns a domstring whose value is one of the members of the rtcicerole enumerated type: "controlling" or "controlled"; this indicates whether the ice agent is the one that makes the final decision as to the candidate pair to use or not. state read only a domstring indicating what the current state of the ice agent is. the value of state can be used to determine whether the ice agent has made an init...
... to determine whether the ice agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("completed"), or in an error state ("failed"), among other states. see the rtcicetransportstate enumerated type for a complete list of states. methods also includes methods from eventtarget, the parent interface. ...
...ncludes methods from eventtarget, the parent interface. getlocalcandidates() re
turns an array of rtcicecandidate objects, each describing one of the ice candidates that have been gathered so far for the local device. these are the same candidates which have already been sent to the remote peer by sending an icecandidate event to the rtcpeerconnection for transmission. getlocalparameters() re
turns a rtciceparameters object describing the ice parameters established by a call to the rtcpeerconnection.setlocaldescription() method. re
turns null if parameters have not yet been received. ...
...And 3 more matches
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). ...
... exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). ...
...ablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). ...
...And 3 more matches
Request.cache - Web APIs
e cache read-only property of the request interface contains the cache mode of the request. it controls how the request will interact with the browser's http cache. syntax var currentcachemode = request.cache; value a requestcache value. the available values are: default — the browser looks for a matching request in its http cache. if there is a match and it is fresh, it will be re
turned from the cache. if there is a match but it is stale, the browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be re
turned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no match, the browser will make a normal request, and will update the cache ...
...ser fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. no-cache — the browser looks for a matching request in its http cache. if there is a match, fresh or stale, the browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be re
turned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. force-cache — the browser looks for a matching request in its http cache. if there is a match, fresh or stale, it will be re
turned from the cache. if ther...
... if there is no match, the browser will respond with a 504 gateway timeout status. the "only-if-cached" mode can only be used if the request's mode is "same-origin". ...
...And 3 more matches
Request - Web APIs
the request interface of the fetch api represents a resource request. you can create a new request object using the request() constructor, but you are more likely to encounter a request object being re
turned as the result of another api operation, such as a service worker fetchevent.request. constructor request() creates a new request object. properties request.cache read only contains the cache mode of the request (e.g., default, reload, no-cache). ...
...t object. properties request.cache read only contains the cache mode of the request (e.g., default, reload, no-cache). request.context read only contains the context of the request (e.g., audio, image, iframe, etc.) request.credentials read only contains the credentials of the request (e.g., omit, same-origin, include). the default is same-origin. request.destination read only re
turns a string from the requestdestination enum describing the request's destination. this is a string indicating the type of content being requested. request.headers read only contains the associated headers object of the request. request.integrity read only contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). request.method read ...
...he following properties: body read only a simple getter used to expose a readablestream of the body contents. bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods request.clone() creates a copy of the current request object. ...
...And 3 more matches
Response - Web APIs
constructor response() creates a new response object. properties response.headers read only the headers object associated with the response. ...
... body interface properties response implements body, so it also has the following properties available to it: body.body read only a simple getter exposing a readablestream of the body contents. body.bodyused read only stores a boolean that declares whether the body has been used in a response yet. methods response.clone() creates a clone of a response object. response.error() re
turns a new response object associated with a network error. response.redirect() creates a new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it re
turns a promise that resolves with an arraybuffer. body.blob() takes a response stream a...
...ed with a network error. response.redirect() creates a new response with a different url. body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion. it re
turns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. it re
turns a promise that resolves with a blob. body.formdata() takes a response stream and reads it to completion. ...
...And 3 more matches
SVGSVGElement - Web APIs
maxwaitmilliseconds) and follow the changes with a method call similar to: unsuspendredraw(suspendhandleid) note that multiple suspendredraw() calls can be used at once, and that each such method call is treated independently of the other suspendredraw() method calls. svgsvgelement.unsuspendredraw() cancels a specified suspendredraw() by providing a unique suspend handle id that was re
turned by a previous suspendredraw() call. svgsvgelement.unsuspendredrawall() cancels all currently active suspendredraw() method calls. this method is most useful at the very end of a set of svg dom calls to ensure that all pending suspendredraw() method calls have been cancelled. svgsvgelement.forceredraw() in rendering environments supporting interactivity, forces the user agent to immediat...
...esponding to this <svg> element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused. svgsvgelement.unpauseanimations() unsuspends (i.e., unpauses) currently running animations that are defined within the svg document fragment, causing the animation clock to continue from the time at which it was suspended. svgsvgelement.animationspaused() re
turns true if this svg document fragment is in a paused state. svgsvgelement.getcurrenttime() re
turns the current time in seconds relative to the start time for the current svg document fragment. if getcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then 0 is re
turned. svgsvgelem...
...ent, establishing a new current time. if setcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun. ...
...And 3 more matches
SVGTextContentElement - Web APIs
dlength reflecting the textlength attribute of the given element. svgtextcontentelement.lengthadjust read only an svganimatedenumeration reflecting the lengthadjust attribute of the given element. the numeric type values represent one of the constant values above. methods this interface also inherits methods from its parent, svggraphicselement. ...
... values represent one of the constant values above. methods this interface also inherits methods from its parent, svggraphicselement. svgtextcontentelement.getnumberofchars() re
turns a long representing the total number of addressable characters available for rendering within the current element, regardless of whether they will be rendered. svgtextcontentelement.getcomputedtextlength() re
turns a float representing the computed length for the text within the element. svgtextcontentelement.getsubstringlength() re
turns a float representing the computed length of the formatted text advance distance for a substring of text within the element. note that this method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the css 'letter-spacing' and 'w...
...esenting the computed length of the formatted text advance distance for a substring of text within the element. note that this method only accounts for the widths of the glyphs in the substring and any extra spacing inserted by the css 'letter-spacing' and 'word-spacing' properties. visual spacing adjustments made by the 'x' attribute is ignored. svgtextcontentelement.getstartpositionofchar() re
turns a dompoint representing the position of a typographic character after text layout has been performed. note: in svg 1.1 this method re
turned an svgpoint. svgtextcontentelement.getendpositionofchar() re
turns a dompoint representing the trailing position of a typographic character after text layout has been performed. note: in svg 1.1 this method re
turned an svgpoint. svgtextcontentelement...
...And 3 more matches
ServiceWorkerRegistration - Web APIs
d that of the serviceworkerregistration objects that represent them within the lifetime of their corresponding service worker clients. the browser maintains a persistent list of active serviceworkerregistration objects. note: this feature is available in web workers. properties also implements properties from its parent interface, eventtarget. serviceworkerregistration.scope read only re
turns a unique identifier for a service worker registration. this must be on the same origin as the document that registers the serviceworker. serviceworkerregistration.installing read only re
turns a service worker whose state is installing. this is initially set to null. serviceworkerregistration.waiting read only re
turns a service worker whose state is installed. this is initially set to null.
...ration. this must be on the same origin as the document that registers the serviceworker. serviceworkerregistration.installing read only re
turns a service worker whose state is installing. this is initially set to null. serviceworkerregistration.waiting read only re
turns a service worker whose state is installed. this is initially set to null. serviceworkerregistration.active read only re
turns a service worker whose state is activated. this is initially set to null. ...
...itially set to null. serviceworkerregistration.active read only re
turns a service worker whose state is activated. this is initially set to null. an active worker will control a serviceworkerclient if the client's url falls within the scope of the registration (the scope option set when serviceworkercontainer.register is first called.) serviceworkerregistration.navigationpreload read only re
turns the instance of navigationpreloadmanager associated with the current service worker registration. serviceworkerregistration.pushmanager read only re
turns a reference to the pushmanager interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. ...
...And 3 more matches
SubtleCrypto.decrypt() - Web APIs
syntax const result = crypto.subtle.decrypt(algorithm, key, data); parameters algorithm is an object specifying the algorithm to be used, and any extra parameters as required. ...
...rams object. to use aes-ctr, pass an aesctrparams object. to use aes-cbc, pass an aescbcparams object. to use aes-gcm, pass an aesgcmparams object. key is a cryptokey containing the key to be used for decryption. if using rsa-oaep, this is the privatekey property of the cryptokeypair object. data is a buffersource containing the data to be decrypted (also known as ciphertext). re
turn value result is a promise that fulfills with an arraybuffer containing the plaintext. exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operati...
....g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). supported algorithms the decrypt() method supports the same algorithms as the encrypt() method. examples note: you can try the working examples on github. rsa-oaep this code decrypts ciphertext using rsa-oaep. see the complete code on github. ...
...And 3 more matches
SubtleCrypto.verify() - Web APIs
syntax const result = crypto.subtle.verify(algorithm, key, signature, data); parameters algorithm is a domstring or object defining the algorithm to use, and for some algorithm choices, some extra parameters. ...
... hmac, pass the string "hmac" or an object of the form { "name": "hmac" }. key is a cryptokey containing the key that will be used to verify the signature. it is the secret key for a symmetric algorithm and the public key for a public-key system. signature is a arraybuffer containing the signature to verify. data is a arraybuffer containing the data whose signature is to be verified. re
turn value result is a promise that fulfills with a boolean: true if the signature is valid, false otherwise. exceptions the promise is rejected when the following exception is encountered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. s...
... out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); re
turn 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. */ async function verifymessage(publickey) { const signaturevalue = document.queryselector(".rsassa-pkcs1 .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded...
...And 3 more matches
UIEvent.layerX - Web APIs
syntax var xpos = event.layerx xpos is an integer value in pixels for the x-coordinate of the mouse pointer, when the mouse event fired. ...
... syntax var xpos = event.layerx xpos is an integer value in pixels for the x-coordinate of the mouse pointer, when the mouse event fired. ...
... syntax var xpos = event.layerx xpos is an integer value in pixels for the x-coordinate of the mouse pointer, when the mouse event fired. ...
...And 3 more matches
UIEvent.layerY - Web APIs
syntax var ypos = event.layery; ypos is an integer value in pixels for the y-coordinate of the mouse pointer, when the mouse event fired. ...
... syntax var ypos = event.layery; ypos is an integer value in pixels for the y-coordinate of the mouse pointer, when the mouse event fired. ...
... syntax var ypos = event.layery; ypos is an integer value in pixels for the y-coordinate of the mouse pointer, when the mouse event fired. ...
...And 3 more matches
Using the User Timing API - Web APIs
an application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark() method is used to create a performance mark. the method takes one argument, the name of the mark, as shown in the following example. function create_marks(ev) { if (performance.mark === undefined) { log("create marks: performance.mark not supported", 0); re
turn; } else { log("create marks", 0); // create several performance marks including two with the same name performance.mark("mark-1"); do_work(50000); performance.mark("mark-2"); do_work(50000); performance.mark("mark-2"); var marks = ["mark-1", "mark-2", "mark-2"]; for (var i=0; i < marks.length; i++) log("... created mark = " + marks[i], 0); } retrieving performance marks ...
... has three methods to retrieve marks. the following examples shows how to use each of these methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype) ) to retrieve one or more marks. function display_marks(ev) { if (performance.getentries === undefined) { log("display marks: performance.getentries not supported", 0); re
turn; } log("display marks", 0); // display each mark using getentries() var entries = performance.getentries(); var j=0; for (var i=0; i < entries.length; i++) { if (entries[i].entrytype == "mark") { if (j == 0) { log("= getentries()", 0); j++ } log("... [" + i + "] = " + entries[i].name, 0); } } // display each mark using getentriesbytype() entries = performan...
...ven to this method, only the mark(s) with that name will be removed. however, if no argument is given, then all performance entries of type "mark" will be removed from the performance timeline. the following example demostrates both uses of this method. function clear_marks(obj) { if (performance.clearmarks === undefined) { log("clear marks: performance.clearmarks not supported", 0); re
turn; } log("clear marks", 0); if (typeof obj == "string") { log("... cleared '" + obj + "' mark(s)", 0); performance.clearmarks(obj); } else { // no argument specified so clear all marks log("... cleared all marks", 0); performance.clearmarks(); } } performance measures a measure performance entry type is named by the application and its timestamp is placed between t...
...And 3 more matches
VTTCue - Web APIs
param starttime the time, in seconds and fractions of a second, that describes the beginning of the range of the media data to which the cue applies. ...
...and fractions of a second, that describes the end of the range of the media data to which the cue applies. text the raw text of the cue, and rules for its interpretation. properties this interface also inherits properties from texttrackcue. vttcue.region a vttregion object describing the video's sub-region that the cue will be drawn onto, or null if none is assigned. ...
...ata to which the cue applies. text the raw text of the cue, and rules for its interpretation. properties this interface also inherits properties from texttrackcue. vttcue.region a vttregion object describing the video's sub-region that the cue will be drawn onto, or null if none is assigned. vttcue.vertical re
turns an enum representing the cue writing direction. ...
...And 3 more matches
WebGLRenderingContext.getParameter() - Web APIs
the webglrenderingcontext.getparameter() method of the webgl api re
turns a value for the passed parameter name. syntax any gl.getparameter(pname); parameters pname a glenum specifying which parameter value to re
turn. see below for possible values. re
turn value depends on the parameter. parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext. ...
...arameter() method of the webgl api re
turns a value for the passed parameter name. syntax any gl.getparameter(pname); parameters pname a glenum specifying which parameter value to re
turn. see below for possible values. re
turn value depends on the parameter. parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext. ...
... when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_...
...And 3 more matches
Using DTMF with WebRTC - Web APIs
dtrack() is available on the rtcpeerconnection, we add each of the stream's audio tracks, one by one, to the connection using rtcpeerconnection.addtrack(). otherwise we call rtcpeerconnection.addstream() to add the stream to the call as a single unit. next we look to see if the rtcpeerconnection.getsenders() method is implemented. if it is, we call it on callerpc and get the first entry in the re
turned list of senders; this is the rtcrtpsender responsible for transmitting data for the first audio track on the call (which is the track we'll send dtmf over). we then obtain the rtcrtpsender's dtmf property, which is an rtcdtmfsender object that can send dtmf on the connection, from the caller to the receiver. if getsenders() isn't available, we instead call rtcpeerconnection.createdtmfsender() ...
...e screen which tone just finished playing. in a more advanced application, you might update the user interface, for example, to indicate which note is currently playing. on the other hand, if the tone buffer is empty, our example is designed to disconnect the call. this is done by stopping each stream on both the caller and the receiver by iterating over each rtcpeerconnection's track list (as re
turned by its gettracks() method) and calling each track's stop() method. once both the caller's and the receiver's media tracks are all stopped, we pause the <audio> element and set its srcobject to null. this detaches the audio stream from the <audio> element. then, finally, each rtcpeerconnection is closed by calling its close() method. adding candidates to the caller when the caller's rtcpeerc...
...th the caller and the receiver, so handlecallernegotiationneeded() is able to quickly construct the connection by chaining the required calls together for both the caller and receiver, as shown below. ...
...And 3 more matches
WorkerGlobalScope - Web APIs
ormation usually conveyed by window objects — in this case event handlers, the console or the associated workernavigator object. each workerglobalscope has its own event loop. this interface is usually specialized by each worker type: dedicatedworkerglobalscope for dedicated workers, sharedworkerglobalscope for shared workers, and serviceworkerglobalscope for serviceworker. the self property re
turns the specialized scope for each context. properties this interface inherits properties from the eventtarget interface and windoworworkerglobalscope and windoweventhandlers mixins. standard properties workerglobalscope.navigator read only re
turns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adap...
... this interface inherits properties from the eventtarget interface and windoworworkerglobalscope and windoweventhandlers mixins. standard properties workerglobalscope.navigator read only re
turns the workernavigator associated with the worker. it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.self read only re
turns a reference to the workerglobalscope itself. most of the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope or serviceworkerglobalscope. workerglobalscope.location read only re
turns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. non-standard prope...
...the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope or serviceworkerglobalscope. workerglobalscope.location read only re
turns the workerlocation associated with the worker. it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. non-standard properties workerglobalscope.performance read only re
turns the performance associated with the worker. it is a regular performance object, except that only a subset of its property and methods are available to workers. ...
...And 3 more matches
WritableStream - Web APIs
writablestream.locked read only a boolean indicating whether the writablestream is locked to a writer. methods writablestream.abort() aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. writablestream.close() closes the stream. writablestream.getwriter() re
turns a new instance of writablestreamdefaultwriter and locks the stream to that instance. while the stream is locked, no other writer can be acquired until this one is released. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queueing strategy. it then calls a function called sendmes...
...iter can be acquired until this one is released. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queueing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const...
...d streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { re
turn defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.lo...
...And 3 more matches
WritableStreamDefaultWriter - Web APIs
the writablestreamdefaultwriter interface of the the streams api is the object re
turned by writablestream.getwriter() and once created locks the writer to the writablestream ensuring that no other streams can write to the underlying sink. constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance. properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. re
turns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. ...
...aultwriter() creates a new writablestreamdefaultwriter object instance. properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. re
turns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. writablestreamdefaultwriter.desiredsizeread only re
turns the desired size required to fill the stream's internal queue. writablestreamdefaultwriter.readyread only re
turns a promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. methods writablestreamdefaultwriter.abort() aborts the stream, signaling that the producer can...
...eases the writer's lock on the corresponding stream. after the lock is released, the writer is no longer active. if the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. ...
...And 3 more matches
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
this information can be used when creating a new xrwebgllayer to configure the xrwebgllayerinit property framebufferscalefactor in the options specified when calling the xrwebgllayer() constructor. see the usage notes and examples for details. if the scaling factor is 1.0, then the frame buffer pixels and the native display pixels are the same size. ...
...er than the native resolution of the display, resulting in the frame buffer's contents being scaled down for display to the xr device. this can happen for display environments which use superscaling or anti-aliasing techniques to improve perceived image quality. ...
...sulting in the frame buffer's contents being scaled down for display to the xr device. this can happen for display environments which use superscaling or anti-aliasing techniques to improve perceived image quality. syntax let nativescaling = xrwebgllayer.getnativeframebufferscalefactor(session); parameters session the xrsession for which to re
turn the native framebuffer scaling factor. re
turn value a floating-point value which, when multiplied by the xrsession's recommended framebuffer dimensions, results in the xr device's native frame buffer resolution. if the session has ended, this function re
turns 0.0. usage notes the scaling factor re
turned by this function will be 1.0 if the native resolution of the xr device and the resolution of the xr device match. in any case, multiplyin...
...And 3 more matches
Rich-Text Editing in Mozilla - Developer guides
note: this document is out-of-date; you are advised to consult the more up-to-date document available at making content editable. mozilla 1.3 introduces an implementation of microsoft® internet explorer's designmode feature. the rich-text editing support in mozilla 1.3 supports the designmode feature which
turns html documents into rich-text editors. starting in firefox 3, mozilla also supports internet explorer's contenteditable attribute which allows any element to become editable or non-editable (the latter for when preventing change to fixed elements in an editable environment). setting up rich-text editing rich-text editing is initialized by setting the designmode property of a document to "on", such as the document inside an iframe. once designmode has been set to "on", the...
...contentdocument, while ie requires iframeelement.document. devedge provides a javascript helper class, xbdesignmode, which is a wrapper for the designmode feature which hides the differences between ie and mozilla. event handling disabled a further difference for mozilla is that once a document is switched to designmode, all events on that particular document are disabled. once designmode is
turned off however (as this now seems possible in mozilla 1.5) the events become active again. more information can be found in the rich text editing section of migrate apps from internet explorer to mozilla. examples please note: the example files are still being migrated from another site. they are not available at this time. --fumble 18:13, 24 apr 2005 (pdt) example 1 the first example is an h...
...diting area, as well as elements for basic editing commands such as bold/italics/text color. figure 3 : setting up rich-text editing html: <body onload="load()"> javascript: function load(){ getiframedocument("editorwindow").designmode = "on"; } function getiframedocument(aid){ // if contentdocument exists, w3c compliant (mozilla) if (document.getelementbyid(aid).contentdocument){ re
turn document.getelementbyid(aid).contentdocument; } else { // ie re
turn document.frames[aid].document; } } the example contains a doricheditcommand function that makes it easier to execute commands on the iframe's document and keeps the html code clean. the function executed the requested command using execcommand() and then sets focus back to the editable document, as clicking on a but...
...And 3 more matches
Feature-Policy - HTTP
bient-light-sensor controls whether the current document is allowed to gather information about the amount of light in the environment around the device through the ambientlightsensor interface. autoplay controls whether the current document is allowed to autoplay media requested through the htmlmediaelement interface. when this policy is disabled and there were no user gestures, the promise re
turned by htmlmediaelement.play() will reject with a domexception. the autoplay attribute on <audio> and <video> elements will be ignored. battery controls whether the use of the battery status api is allowed. when this policy is disabled, the promise re
turned by navigator.getbattery() will reject with a notallowederror domexception. camera controls whether the current document is allowed to use v...
...he autoplay attribute on <audio> and <video> elements will be ignored. battery controls whether the use of the battery status api is allowed. when this policy is disabled, the promise re
turned by navigator.getbattery() will reject with a notallowederror domexception. camera controls whether the current document is allowed to use video input devices. when this policy is disabled, the promise re
turned by getusermedia() will reject with a notallowederror domexception. display-capture controls whether or not the current document is permitted to use the getdisplaymedia() method to capture screen contents. when this policy is disabled, the promise re
turned by getdisplaymedia() will reject with a notallowederror if permission is not obtained to capture the display's contents. document-domain ...
...isplay's contents. document-domain controls whether the current document is allowed to set document.domain. when this policy is disabled, attempting to set document.domain will fail and cause a securityerror domexception to be be thrown. encrypted-media controls whether the current document is allowed to use the encrypted media extensions api (eme). when this policy is disabled, the promise re
turned by navigator.requestmediakeysystemaccess() will reject with a domexception. execution-while-not-rendered controls whether tasks should execute in frames while they're not being rendered (e.g. if an iframe is hidden or display: none). execution-while-out-of-viewport controls whether tasks should execute in frames while they're outside of the visible viewport. fullscreen controls whether...
...And 3 more matches
Enumerability and ownership of properties - JavaScript
the most efficient algorithm for all cases, but useful for a quick demonstration. ...
...odyouwant(obj).indexof(prop) > -1 iteration can occur by simplepropertyretriever.thegetmethodyouwant(obj).foreach(function (value, prop) {}); (or use filter(), map(), etc.) var simplepropertyretriever = { getownenumerables: function(obj) { re
turn this._getpropertynames(obj, true, false, this._enumerable); // or could use for..in filtered with hasownproperty or just this: re
turn object.keys(obj); }, getownnonenumerables: function(obj) { re
turn this._getpropertynames(obj, true, false, this._notenumerable); }, getownenumerablesandnonenumerables: function(obj) { re
turn this._getpropertynames(obj, true, false, this._enumerableandnotenumerable); // or just use: re
turn object.getownpropertynames(obj); }, getprototypeenumerables: ...
... getownnonenumerables: function(obj) { re
turn this._getpropertynames(obj, true, false, this._notenumerable); }, getownenumerablesandnonenumerables: function(obj) { re
turn this._getpropertynames(obj, true, false, this._enumerableandnotenumerable); // or just use: re
turn object.getownpropertynames(obj); }, getprototypeenumerables: function(obj) { re
turn this._getpropertynames(obj, false, true, this._enumerable); }, getprototypenonenumerables: function(obj) { re
turn this._getpropertynames(obj, false, true, this._notenumerable); }, getprototypeenumerablesandnonenumerables: function(obj) { re
turn this._getpropertynames(obj, false, true, this._enumerableandnotenumerable); }, getownandprototypeenumerables: func...
...And 3 more matches
Loops and iteration - JavaScript
nditionexpression is true, the loop statements execute. if the value of condition is false, the for loop terminates. (if the condition expression is omitted entirely, the condition is assumed to be true.) the statement executes. to execute multiple statements, use a block statement ({ ... }) to group those statements. if present, the update expression incrementexpression is executed. control re
turns to step 2. example in the example below, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that allows multiple selections). the for statement declares the variable i and initializes it to 0. it checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i ...
... a do...while statement looks as follows: do statement while (condition); statement is ...
... while statement a while statement executes its statements as long as a specified condition evaluates to true. a while statement looks as follows: while (condition) statement if the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop. the condition test occurs before statement in the loop is executed. if the condition re
turns true, statement is executed and the condition is tested again. if the condition re
turns false, execution stops, and control is passed to the statement following while. to execute multiple statements, use a block statement ({ ... }) to group those statements. example 1 the following while loop iterates as long as n is less than 3: let n = 0; let x = 0; while (n < 3) { n++; x += n; } wit...
...And 3 more matches
JavaScript modules - JavaScript
this guide have basically the same structure; the above should start getting pretty familiar. the modules directory's two modules are described below: canvas.js — contains functions related to setting up the canvas: create() — creates a canvas with a specified width and height inside a wrapper <div> with a specified id, which is itself appended inside a specified parent element. re
turns an object containing the canvas's 2d context and the wrapper's id. createreportlist() — creates an unordered list appended inside a specified wrapper element, which can be used to output report data into. re
turns the list's id. square.js — contains: name — a constant containing the string 'square'. draw() — draws a square on a specified canvas, with a specified size, po...
... reportarea() — writes a square's area to a specific report list, given its length. ...
...orting module features the first thing you do to get access to module features is export them. this is done using the export statement. the easiest way to use it is to place it in front of any items you want exported out of the module, for example: export const name = 'square'; export function draw(ctx, length, x, y, color) { ctx.fillstyle = color; ctx.fillrect(x, y, length, length); re
turn { length: length, x: x, y: y, color: color }; } you can export functions, var, let, const, and — as we'll see later — classes. they need to be top-level items; you can't use export inside a function, for example. a more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file, followed by a comma-separa...
...And 3 more matches
TypeError: "x" is not a constructor - JavaScript
pe for cars. you want this type of object to be called car, and you want it to have properties for make, model, and year. ...
...r; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when re
turning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it. ...
...tely-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it. ...
...And 3 more matches
TypeError: "x" is not a function - JavaScript
not a function the correct function name is getelementbyid: let x = document.getelementbyid('foo'); function called on the wrong object for certain methods, you have to provide a (callback) function and it will work on specific objects only. in this example, array.prototype.map() is used, which will work with array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(function(num) { re
turn num * 2; }); // typeerror: obj.map is not a function use an array instead: let numbers = [1, 4, 9]; numbers.map(function(num) { re
turn num * 2; }); // array [2, 8, 18] function shares a name with a pre-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exis...
... [1, 4, 9]; numbers.map(function(num) { re
turn num * 2; }); // array [2, 8, 18] function shares a name with a pre-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exist. ...
...2, 8, 18] function shares a name with a pre-existing property sometimes when making a class, you may have a property and a function with the same name. upon calling the function, the compiler thinks that the function ceases to exist. ...
...And 3 more matches
The arguments object - JavaScript
to convert arguments to a real array: let args = array.from(arguments); // or let args = [...arguments]; the arguments object is useful for functions called with more arguments than they are formally declared to accept. this technique is useful for functions that can be passed a variable number of arguments, such as math.min(). this example function accepts any number of string arguments and re
turns the longest one: function longeststring() { var longest = ''; for (var i=0; i < arguments.length; i++) { if (arguments[i].length > longest.length) { longest = arguments[i]; } } re
turn longest; } you can use arguments.length to count how many arguments the function was called with. if you instead want to count how many parameters a function is declared to accept, inspect ...
...< arguments.length; i++) { if (arguments[i].length > longest.length) { longest = arguments[i]; } } re
turn longest; } you can use arguments.length to count how many arguments the function was called with. if you instead want to count how many parameters a function is declared to accept, inspect that function's length property. using typeof with arguments the typeof operator re
turns 'object' when used with arguments console.log(typeof arguments); // 'object' the type of individual arguments can be determined by indexing arguments: console.log(typeof arguments[0]); // re
turns the type of the first argument properties arguments.callee reference to the currently executing function that the arguments belong to. forbidden in strict mode. arguments.length the number of...
... examples defining a function that concatenates several strings this example defines a function that concatenates several strings. ...
...And 3 more matches
Array.prototype.find() - JavaScript
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. if you need the index of the found element in the array, use findindex(). if you need to find the index of a value, use array.prototype.indexof(). (it’s similar to findindex(), but checks each element for equality with the value instead of using a testing function.) if you need to find if a value exists in an array, use array.prototype.includes(). ...
...tax arr.find(callback(element[, index[, array]])[, thisarg]) parameters callback function to execute on each value in the array, taking 3 arguments: element the current element in the array. index optional the index (position) of the current element in the array. array optional the array that find was called on. thisarg optional object to use as this inside callback. re
turn value the value of the first element in the array that satisfies the provided testing function. otherwise, undefined is re
turned. description the find method executes the callback function once for each index of the array until the callback re
turns a truthy value. if so, find immediately re
turns the value of that element. otherwise, find re
turns undefined. callback is invoked for every index ...
...rg was supplied, let t be thisarg; else let t be undefined. var thisarg = arguments[1]; // 5. let k be 0. var k = 0; // 6. repeat, while k < len while (k < len) { // a. let pk be ! tostring(k). // b. let kvalue be ? get(o, pk). // c. let testresult be toboolean(? call(predicate, t, « kvalue, k, o »)). // d. ...
...And 3 more matches
Array.prototype.forEach() - JavaScript
alue [, index [, array]])[, thisarg]) parameters callback function to execute on each element. it accepts between one and three arguments: currentvalue the current element being processed in the array. index optional the index currentvalue in the array. array optional the array foreach() was called upon. thisarg optional value to use as this when executing callback. re
turn value undefined. description foreach() calls a provided callback function once for each element in an array in ascending order. it is not invoked for index properties that have been deleted or are uninitialized. (for sparse arrays, see example below.) callback is invoked with three arguments: the value of the element the index of the element the array object being traversed if a thisar...
...e as passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. if elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (see this example, below.) foreach() executes the callback function once for each array element; unlike map() or reduce() it always re
turns the value undefined and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach() loop other than by throwing an exception. if you need such behavior, the foreach() method is the wrong tool. early termination may be accomplished ...
...her than by throwing an exception. if you need such behavior, the foreach() method is the wrong tool. ...
...And 3 more matches
Array.prototype.slice() - JavaScript
the original array will not be modified. 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 arr.slice([start[, end]]) parameters start optional zero-based index at which to start extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. if start is undefined, slice starts from the index 0. ...
...ll request. syntax arr.slice([start[, end]]) parameters start optional zero-based index at which to start extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. if start is undefined, slice starts from the index 0. if start is greater than the index range of the sequence, an empty array is re
turned. end optional zero-based index before which to end extraction. slice extracts up to but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if ...
...nts indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (arr.length). if end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length). re
turn value a new array containing the extracted elements. description slice does not alter the original array. it re
turns a shallow copy of elements from the original array. elements of the original array are copied into the re
turned array as follows: for object references (and not the actual object), slice copies object references into the new array. both the original and new array refer to the...
...And 3 more matches
Date.prototype.getYear() - JavaScript
the getyear() method re
turns the year in the specified date according to local time. because getyear() does not re
turn full years ("year 2000 problem"), it is no longer used and has been replaced by the getfullyear() method. syntax dateobj.getyear() re
turn value a number representing the year of the given date, according to local time, minus 1900. description for years greater than or equal to 2000, the value re
turned by getyear() is 100 or greater. for example, if the year is 2026, getyear() re
turns 126. for years between and including 1900 and 1999, the value re
turned by getyear() is between 0 and 99. for example, if the year is 1976, getyear() re
turns 76. for years less than 1900, the value re
turned by getyear() is less than 0. ...
...qual to 2000, the value re
turned by getyear() is 100 or greater. for example, if the year is 2026, getyear() re
turns 126. for years between and including 1900 and 1999, the value re
turned by getyear() is between 0 and 99. for example, if the year is 1976, getyear() re
turns 76. for years less than 1900, the value re
turned by getyear() is less than 0. for example, if the year is 1800, getyear() re
turns -100. to take into account years before and after 2000, you should use getfullyear() instead of getyear() so that the year is specified in full. backward compatibility behavior in javascript 1.2 and earlier the getyear() method re
turns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value re
turned by getyear() is the year minus 1900. for example, if t...
...t years before and after 2000, you should use getfullyear() instead of getyear() so that the year is specified in full. backward compatibility behavior in javascript 1.2 and earlier the getyear() method re
turns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value re
turned by getyear() is the year minus 1900. for example, if the year is 1976, the value re
turned is 76. for years less than 1900 or greater than 1999, the value re
turned by getyear() is the four-digit year. for example, if the year is 1856, the value re
turned is 1856. if the year is 2026, the value re
turned is 2026. examples years between 1900 and 1999 the second statement assigns the value 95 to the variable year. var xmas = new date('december 25, 1995 23:15:00'); var year = xmas.ge...
...And 3 more matches
Date.prototype.toISOString() - JavaScript
polyfill this method was standardized in ecma-262 5th edition. ...
...-mm-ddthh:mm:ss.sssz or ±yyyyyy-mm-ddthh:mm:ss.sssz, respectively). the timezone is always zero utc offset, as denoted by the suffix "z". 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 dateobj.toisostring() re
turn value a string representing the given date in the iso 8601 format according to universal time. polyfill this method was standardized in ecma-262 5th edition. engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.prototype.toisostring) { (function() { function pad(number) { if (number < 10) { ...
... a string representing the given date in the iso 8601 format according to universal time. polyfill this method was standardized in ecma-262 5th edition. ...
...And 3 more matches
Date.prototype.toLocaleDateString() - JavaScript
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. ...
...m/mdn/interactive-examples and send us a pull request. syntax dateobj.tolocaledatestring([locales [, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...And 3 more matches
Date.prototype.toLocaleTimeString() - JavaScript
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. ...
...om/mdn/interactive-examples and send us a pull request. syntax dateobj.tolocaletimestring([locales[, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...And 3 more matches
Function.prototype.apply() - JavaScript
, and primitive values will be boxed. this argument is required. argsarray optional an array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. starting with ecmascript 5 these arguments can be a generic array-like object instead of an array. see below for browser compatibility information. re
turn value the result of calling the function with the specified this value and arguments. description note: while the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. note: when the first argument is undefined or null a similar outcome can be achieved using the a...
... of arguments, you can also push multiple elements at once. but, if you pass an array to push, it will actually add that array as a single element, instead of adding the elements individually. so you end up with an array inside an array. what if that is not what you want? concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and re
turns a new array. but you wanted to append to the existing array... so what now? write a loop? surely not? apply to the rescue! const array = ['a', 'b']; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] using apply and built-in functions clever usage of apply allows you to use built-in functions for some tasks that would probably have ot...
... in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. function.prototype.construct = function(aargs) { let one...
...And 3 more matches
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the intl.datetimeformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by datetimeformat formatters. syntax datetimeformat.formattoparts(date) parameters date optional the date to format. re
turn value an array of objects containing the formatted date in parts. description the formattoparts() method is useful for custom formatting of date strings. it re
turns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. the structure the formattoparts() method re
turns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'monday' } ] possible types are the following: day the string used for the day, for example "17". dayperiod ...
...lseconddigits: 3, hour12: true, timezone: 'utc' }); formatter.format(date); // "monday, 12/17/2012, 3:00:42.000 am" however, in many user interfaces there is a desire to customize the formatting of this string. ...
...{ type: 'dayperiod', value: 'am' } ] now the information is available separately and it can be formatted and concatenated again in a customized way. for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce(). var datestring = formatter.formattoparts(date).map(({type, value}) => { switch (type) { case 'dayperiod': re
turn `<b>${value}</b>`; default : re
turn value; } }).reduce((string, part) => string + part); this will make the day period bold, when using the formattoparts() method. console.log(formatter.format(date)); // "monday, 12/17/2012, 3:00:42.000 am" console.log(datestring); // "monday, 12/17/2012, 3:00:42.000 <b>am</b>" named years and mixed calendars in some cases, calendars use named years. ...
...And 3 more matches
Math.trunc() - JavaScript
description unlike the other three math methods: math.floor(), math.ceil() and math.round(), the way math.trunc() works is very simple. it truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. ...
... description unlike the other three math methods: math.floor(), math.ceil() and math.round(), the way math.trunc() works is very simple. it truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number. ...
... no matter whether the argument is a positive or negative number. the argument passed to this method will be converted to number type implicitly. because trunc() is a static method of math, you always use it as math.trunc(), rather than as a method of a math object you created (math is not a constructor). ...
...And 3 more matches
Number - JavaScript
use. (javascript now has a bigint type, but it was not designed to replace number for everyday uses. 37 is still a number, not a bigint.) number may also be expressed in literal forms like 0b101, 0o13, 0x0a. learn more on numeric lexical grammar here. description when used as a function, number(value) converts a string or other value to the number type. if the value can't be converted, it re
turns nan. literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true function syntax number('123') // re
turns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a new number value. static properties number.epsilon the smallest interval between two representable numbers. number.m...
... number.max_value the largest positive representable number. number.min_safe_integer the minimum safe integer in javascript (-(253 - 1)). number.min_value the smallest positive representable number—that is, the positive number closest to zero (without actually being zero). number.nan special "not a number" value. number.negative_infinity special value representing negative infinity. re
turned on overflow. number.positive_infinity special value representing infinity. re
turned on overflow. number.prototype allows the addition of properties to the number object. static methods number.isnan() determine whether the passed value is nan. number.isfinite() determine whether the passed value is a finite number. number.isinteger() determine whether the passed value is an integer...
...whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). number.parsefloat(string) this is the same as the global parsefloat() function. number.parseint(string, [radix]) this is the same as the global parseint() function. ...
...And 3 more matches
Object.prototype.__lookupGetter__() - JavaScript
__lookupgetter__ can be used to obtain a reference to the getter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof(). ...
...__lookupgetter__ can be used to obtain a reference to the getter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof(). ...
...__lookupgetter__ can be used to obtain a reference to the getter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof(). ...
...And 3 more matches
Object.assign() - JavaScript
the object.assign() method copies all enumerable own properties from one or more source objects to a target object. it re
turns the target object. 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 object.assign(target, ...sources) parameters target the target object — what to apply the sources’ properties to, which is re
turned after it is modified. sources the source object(s) — objects containing the properties you want to apply. re
turn value the target object. description properties in the target object are overwritten by properties in the sources if they have the same key. later sources' pr...
... if the source value is a reference to an object, it only copies the reference value. function...
...y. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1, exception is thrown here. console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied. console.log(target.baz); // undefined, the third source will not be copied either. copying accessors const obj = { foo: 1, get bar() { re
turn 2; } }; let copy = object.assign({}, obj); console.log(copy); // { foo: 1, bar: 2 } // the value of copy.bar is obj.bar's getter's re
turn value. // this is an assign function that copies full descriptors function completeassign(target, ...sources) { sources.foreach(source => { let descriptors = object.keys(source).reduce((descriptors, key) => { descriptors[key] = object.getownprop...
...And 3 more matches
Object.prototype.constructor - JavaScript
note that the value of this property is a reference to the function itself, not a string containing the function's name. the value is only read-only for primitive values such as 1, true, and "test". description all objects (with the exception of objects created with object.create(null)) will have a constructor property. objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the fundamental object constructor type for that object. ...
...-constructor with further calling it with new and prototype-inherits chain. function parent() { /* ... */ } parent.prototype.parentmethod = function parentmethod() {} function child() { parent.call(this) // make sure everything is initialized properly } child.prototype = object.create(parent.prototype) // re-define child prototype to parent prototype child.prototype.constructor = child // re
turn original constructor to child but when do we need to perform the last line here? unfortunately, the answer is: it depends. let's try to define the cases in which re-assignment of the original constructor will play a major role, and when it will be one superfluous line of code. take the following case: the object has the create() method to create itself. function parent() { /* ... */ } functio...
...ent of the original constructor will play a major role, and when it will be one superfluous line of code. take the following case: the object has the create() method to create itself. function parent() { /* ... */ } function createdconstructor() { parent.call(this) } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.create = function create() { re
turn new this.constructor() } new createdconstructor().create().create() // typeerror undefined is not a function since constructor === parent in the example above the exception will be shown since the constructor links to parent. to avoid this, just assign the necessary constructor you are going to use. function parent() { /* ... */ } function createdconstructor() { /* ... */ } createdconstructo...
...And 3 more matches
Object.prototype.hasOwnProperty() - JavaScript
description all descendents of object inherit the hasownproperty method. ...
...ed property as its own property (as opposed to inheriting it). 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 obj.hasownproperty(prop) parameters prop the string name or symbol of the property to test. re
turn value a boolean indicating whether or not the object has the specified property as own property. description all descendents of object inherit the hasownproperty method. this method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. if an ob...
... description all descendents of object inherit the hasownproperty method. this method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. if an object is an array, hasownproperty method can check whether an index exists. ...
...And 3 more matches
Promise() constructor - JavaScript
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 "fulfilled" or "rejected" by terminating with an invocation of either the resolutionfunc or the rejectionfunc, respectively. the executor has no meaningful re
turn 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 v...
...nfunc upon error. the signatures of these two functions are simple, they accept a single parameter of any type. of course, the actual names of these functions can be whatever is desired, i.e. they are named as the parameters of executor. each function is used by simply calling it when appropriate. resolutionfunc(value) // call on fulfilled rejectionfunc(reason) // call on rejected the re
turned value can be another promise object, in which case the promise gets dynamically inserted into the chain. re
turn value promiseobj when called via new, the promise constructor re
turns a promise object. the promise object will become "resolved" when either of the functions resolutionfunc or rejectionfunc are invoked. note that if you call resolutionfunc or rejectionfunc and pass another p...
...ved", 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. the first of these functions (resolve) is called when the asynchronous task completes successfully and re
turns the results of the task as a value. the second (reject) is called when the task fails, and re
turns the reason for failure, which is typically an error object. const myfirstpromise = new promise((resolve, reject) => { // do something asynchronous which eventually calls either: // // resolve(somevalue) // fulfilled // or // reject("failure reason") // rejected }); making f...
...And 3 more matches
Promise.prototype.catch() - JavaScript
it behaves the same as calling promise.prototype.then(undefined, onrejected) (in fact, calling obj.catch(onrejected) internally calls obj.then(undefined, onrejected)). this means that you have to provide an onrejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}). 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 p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. ...
...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 p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. this function has one argument: reason the rejection reason. the promise re
turned by catch() is rejected if onrejected throws an error or re
turns a promise which is itself rejected; otherwise, it is resolved. re
turn value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler. re
turns the value of that call, which is a promise. note the examples below are throwing instances of ...
...ormation like stack traces. ...
...And 3 more matches
RegExp.prototype[@@matchAll]() - JavaScript
'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing the behavior of matchall() in regexp subclasses. ...
... 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing the behavior of matchall() in regexp subclasses. ...
.... 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 regexp[symbol.matchall](str) parameters str a string that is a target of the match. re
turn value an iterator. description this method is called internally in string.prototype.matchall(). for example, the following two examples re
turn same result. 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing the behavior of matchall() in regexp subclasses. examples direct call this method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.m...
...And 3 more matches
String.fromCharCode() - JavaScript
the static string.fromcharcode() method re
turns a string created from the specified sequence of utf-16 code units. 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 string.fromcharcode(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units. the range is between 0 and 65535 (0xffff). numbers greater than 0xffff are truncated. no validity checks are performed. re
turn value a string of length n consisting of the n specified utf-16 code units. description this method re
turns a string and not a string object. because fromcharcode() is a static method of string, y...
...a code unit). however, this set of characters, known as the base multilingual plane (bmp), is only 1/17th of the total addressable unicode code points. ...
...ementary characters. in utf-16, supplementary characters are represented by two 16-bit code units, known as surrogates, that were reserved for this purpose. a valid combination of two surrogates used to represent a supplementary character is known as a surrogate pair. because fromcharcode() only works with 16-bit values (same as the \u escape sequence), a surrogate pair is required in order to re
turn a supplementary character. for example, both string.fromcharcode(0xd83c, 0xdf03) and \ud83c\udf03 re
turn code point u+1f303 "night with stars". while there is a mathematical relationship between the supplementary code point value (e.g. 0x1f303) and both surrogate values that represent it (e.g., 0xd83c and 0xdf03), it does require an extra step to either calculate or look up the surrogate pair va...
...And 3 more matches
String.prototype.lastIndexOf() - JavaScript
fromindex optional the index of the last character in the string to be considered as the beginning of a match. the default value is +infinity. ...
... fromindex optional the index of the last character in the string to be considered as the beginning of a match. the default value is +infinity. ...
...ource 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 str.lastindexof(searchvalue[, fromindex]) parameters searchvalue a string representing the value to search for. if searchvalue is an empty string, then fromindex is re
turned. fromindex optional the index of the last character in the string to be considered as the beginning of a match. the default value is +infinity. if fromindex >= str.length, the whole string is searched. if fromindex < 0, the behavior will be the same as if it would be 0. re
turn value the index of the last occurrence of searchvalue; -1 if not found. description characters in a string are ...
...And 3 more matches
String.prototype.substr() - JavaScript
description substr() extracts length characters from a str, counting from the start index. ...
...x and extending for a given number of characters afterwards. 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 str.substr(start[, length]) parameters start the index of the first character to include in the re
turned substring. length optional. the number of characters to extract. re
turn value a new string containing the specified part of the given string. description substr() extracts length characters from a str, counting from the start index. if start is a positive number, the index starts counting at the start of the string. its value is capped at str.length. if start is a negative number, th...
...d as 0. polyfill microsoft's jscript does not support negative values for the start index. ...
...And 3 more matches
TypedArray.prototype.findIndex() - JavaScript
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 typedarray.findindex(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. ...
...allback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array findindex was called upon. thisarg optional. object to use as this when executing callback. re
turn value an index in the array if an element passes the test; otherwise, -1. description the findindex method executes the callback function once for each element present in the typed array until it finds one where callback re
turns a true value. if such an element is found, findindex immediately re
turns the index of that element. otherwise, findindex re
turns -1. callback is invoked only for index...
... function if ( ! ...
...And 3 more matches
isNaN() - JavaScript
the isnan() function determines whether a value is nan or not. note, coercion inside the isnan function has interesting rules; you may alternatively want to use number.isnan(), as defined in ecmascript 2015. syntax isnan(value) parameters value the value to be tested. re
turn value true if the given value is nan; otherwise, false. description the necessity of an isnan function unlike all other possible values in javascript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is nan or not, because both nan == nan and nan === nan evaluate to false. hence, the necessity of an isnan function. origin of nan values nan values are generated when arithmetic operations result in undefined or unrepresentable values. such values do not necessar...
...s been confusing. when the argument to the isnan function is not of type number, the value is first coerced to a number. the resulting value is then tested to determine whether it is nan. thus for non-numbers that when coerced to numeric type result in a valid non-nan numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" re
turned value may be unexpected; the empty string, for example, is surely "not a number." the confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as ieee-754 floating-point values. the function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an ieee-754 'not a number' value?" ecmascript 2015 conta...
...umber". alternatively, in the absence of number.isnan, the expression (x != x) is a more reliable way to test whether variable x is nan or not, as the result is not subject to the false positives that make isnan unreliable. ...
...And 3 more matches
Conditional (ternary) operator - JavaScript
ny of these, the result of the conditional expression will be the result of executing the expression expriffalse. ...
...me = person ? person.name : `stranger` re
turn `howdy, ${name}` } console.log(greeting({name: `alice`})); // "howdy, alice" console.log(greeting(null)); // "howdy, stranger" conditional chains the ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain: function example(…) { re
turn condition1 ? value1 : condition2 ? value2 : condition3 ? ...
... ...
...And 3 more matches
Logical NOT (!) - JavaScript
the logical not (!) operator (logical complement, negation) takes truth to falsity and vice versa. it is typically used with boolean (logical) values. when used with non-boolean values, it re
turns false if its single operand can be converted to true; otherwise, re
turns true. 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 !expr description re
turns false if its single operand can be converted to true; otherwise, re
turns true. if a value can be converted to true, the value is so-called truthy. if a value can be converted to false, the value is so-called falsy. examples of expressions that can be converted...
... a value can be converted to true, the value is so-called truthy. if a value can be converted to false, the value is so-called falsy. examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined. ...
...verted to false, the value is so-called falsy. examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined. even though the ! operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its re
turn value can always be converted to a boolean primitive. ...
...And 3 more matches
Operator precedence - JavaScript
ntheses change the order left-associativity (left-to-right) means that it is processed as (a op1 b) op2 c, while right-associativity (right-to-left) means it is interpreted as a op1 (b op2 c). assignment operators are right-associative, so you can write: a = b = 5; // same as writing a = (b = 5); with the expected result that a and b get the value 5. this is because the assignment operator re
turns the value that is assigned. first, b is set to 5. then the a is also set to 5, the re
turn value of b = 5, aka right operand of the assignment. as another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. it is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity. ...
...nd of the assignment. as another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. it is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity. ...
...ty. code output function echo(name, num) { console.log("evaluating the " + name + " side"); re
turn num; } // notice the division operator (/) console.log(echo("left", 6) / echo("right", 2)); evaluating the left side evaluating the right side 3 function echo(name, num) { console.log("evaluating the " + name + " side"); re
turn num; } // notice the exponentiation operator (**) console.log(echo("left", 2) ** echo("right", 3)); evaluating the left side evaluating the right side 8 the difference in associativity comes into play when there are multiple operators of the same precedence. with only one operator or operators of different precedences, associativity doesn't affect the output, as seen in th...
...And 3 more matches
yield* - JavaScript
the yield* expression is used to delegate to another generator or iterable object. 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 yield* expression; expression the expression which re
turns an iterable object. description the yield* expression iterates over the operand and yields each value re
turned by it. the value of yield* expression itself is the value re
turned by that iterator when it's closed (i.e., when done is true). examples delegating to another generator in following code, values yielded by g1() are re
turned from next() calls just like those which are yielded by g2(). function* g1() {...
...: false} console.log(iterator.next()); // {value: "4", done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: 6, done: false} console.log(iterator.next()); // {value: undefined, done: true} the value of yield* expression itself yield* is an expression, not a statement—so it evaluates to a value. ...
...alue: "4", done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: 6, done: false} console.log(iterator.next()); // {value: undefined, done: true} the value of yield* expression itself yield* is an expression, not a statement—so it evaluates to a value. ...
...And 3 more matches
function* - JavaScript
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. you can also define generator functions using the generatorfunction constructor, or the function expression syntax. syntax function* name([param[, param[, ... param]]]) { statements } name the function name. param optional the name of a formal parameter for the function. ...
...ed 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. ...
...ll 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 re
turned instead. when the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be re
turned from the iterator or, with yield*, delegates to another generator function. the next() method re
turns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. calling the next() method with an argument will resume the generator function execution, replacing the yield expression where an execu...
...And 3 more matches
Web Components
from the rest of your code — and utilize them in your web apps. concepts and usage as developers, we all know that reusing code as much as possible is a good idea. this has traditionally not been so easy for custom markup structures — think of the complex html (and associated style and script) you've sometimes had to write to render custom ui controls, and how using them multiple times can
turn your page into a mess if you are not careful. web components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions. custom elements: a set of javascript apis that allow you to define custom elements and their beha...
...ow to define a reusable html structure using <template> and <slot> elements, and then use that structure inside your web components. reference custom elements customelementregistry contains functionality related to custom elements, most notably the customelementregistry.define() method used to register new custom elements so they can then be used in your document. window.customelements re
turns a reference to the customelementregistry object. life cycle callbacks special callback functions defined inside the custom element's class definition, which affect its behavior: connectedcallback: invoked when the custom element is first connected to the document's dom. disconnectedcallback: invoked when the custom element is disconnected from the document's dom. adoptedcallback: invok...
...tribute. shadow dom shadowroot represents the root node of a shadow dom subtree. documentorshadowroot a mixin defining features that are available across document and shadow roots. element extensions extensions to the element interface related to shadow dom: the element.attachshadow() method attaches a shadow dom tree to the specified element. ...
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
ed by content script console.log(window.contentscriptobject.greeting); // "hello from add-on" }, false); after firefox 30, you can still do this for primitive values, but can no longer do it for objects. instead, you need to use the global cloneinto() function to clone the object into the page script's scope. cloneinto() creates a structured clone of the object in the target context, and re
turns a reference to the clone. you can then assign that to a property of the target window, and the page script can access it. here's an example. the "main.js" opens the local file "page.html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), onready: attachscript }); function attachsc...
...url: self.data.url("page.html"), onready: attachscript }); function attachscript(tab) { tab.attach({ contentscriptfile: self.data.url("content-script.js") }); } the content script defines a function greetme() and exports it to the page script context. ...
... create objects in page script scope finally, a content script can use the createobjectin() function to create an object in the page script's scope. it can then c...
...And 2 more matches
passwords - Archive of obsolete content
ated service (for example, by logging into a web site). store credentials in the password manager. you can store different sorts of credentials, as outlined in the "credentials" section below. remove stored credentials from the password manager. credentials in this api, credentials are represented by objects. you create credential objects to pass into the api, and the api also re
turns credential objects to you. the sections below explain both the properties you should define on credential objects and the properties you can expect on credential objects re
turned by the api. all credential objects include username and password properties. different sorts of stored credentials include various additional properties, as outlined in this section. you can use the passwords api with...
...uld be: url: "http://www.example.com" realm: "exampleco login" oncomplete and onerror this api is explicitly asynchronous, so all its functions take two callback functions as additional options: oncomplete and onerror. 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 re
turn a list of matching credentials, its oncomplete option is mandatory. because the other functions don't re
turn a value in case of success their oncomplete options are optional. for all functions, onerror is optional. globals functions search(options) this function is used to retrieve a credential, or a list of credentials, stored in the password manager. you pass it any subset of the possible...
...'t re
turn a value in case of success their oncomplete options are optional. for all functions, onerror is optional. globals functions search(options) this function is used to retrieve a credential, or a list of credentials, stored in the password manager. you pass it any subset of the possible properties a credential can contain. credentials which match all the properties you supplied are re
turned as an argument to the oncomplete callback. ...
...And 2 more matches
url - Archive of obsolete content
arsed as data url. if is not a valid uri, this constructor will throw an exception. functions tofilename(url) attempts to convert the given url to a native file path. this function will automatically attempt to resolve non-file protocols, such as the resource: protocol, to their place on the file system. an exception is raised if the url can't be converted; otherwise, the native file path is re
turned as a string. parameters url : string the url, as a string, to be converted. re
turns string : the converted native file path as a string. fromfilename(path) converts the given native file path to a file: url. parameters path : string the native file path, as a string, to be converted. re
turns string : the converted url as a string. isvaliduri(uri) checks the validity of a uri. isva...
...ring the url, as a string, to be converted. re
turns string : the converted native file path as a string. fromfilename(path) converts the given native file path to a file: url. parameters path : string the native file path, as a string, to be converted. re
turns string : the converted url as a string. isvaliduri(uri) checks the validity of a uri. isvaliduri("http://mozilla.org") would re
turn true, whereas isvaliduri("mozilla.org") would re
turn false. parameters uri : string the uri, as a string, to be tested. re
turns boolean : a boolean indicating whether or not the uri is valid. gettld(url) re
turns the top-level domain for the given url: that is, the highest-level domain under which individual domains may be registered. uses getpublicsuffix() internally. var urls = require("...
... properties scheme the name of the protocol in the url, without the trailing ':'. compare with protocol. ...
...And 2 more matches
places/history - Archive of obsolete content
access the user's browsing history. usage this module exports a single function, search(), which synchronously re
turns 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 ...
...ns) queries can be performed on history entries by passing in one or more query options. each query option can take several properties, which are and'd together to make one complete query. for additional queries within the query, passing more query options in will or the total results. an options object may be specified to determine overall settings, like sorting and how many objects should be re
turned. parameters queries : object|array an object representing a query, or an array of objects representing queries. each query object can take several properties, which are queried against the history database. each property is and'd together, meaning that bookmarks must match each property within a query object. multiple query objects are then or'd together. options : object optional options:...
...esenting queries. each query object can take several properties, which are queried against the history database. each property is and'd together, meaning that bookmarks must match each property within a query object. multiple query objects are then or'd together. options : object optional options: name type count number the number of bookmark items to re
turn. if left undefined, no limit is set. sort string a string specifying how the results should be sorted. possible options are 'title', 'date', 'url', 'visitcount', 'keyword', 'dateadded' and 'lastmodified'. descending boolean a boolean specifying whether the results should be in descending order. by default, results are in ascending order. ...
...And 2 more matches
Dialogs and Prompts - Archive of obsolete content
e below). simple dialog code the following xul code defines a simple dialog with two buttons, ok and cancel (buttons="accept,cancel" attribute on dialog). <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." title="..." buttons="accept,cancel" ondialogaccept="re
turn onaccept();" ondialogcancel="re
turn oncancel();"> <script src="chrome://..."/> <!-- content --> </dialog> you need to implement onaccept and oncancel functions in your script. if they re
turn anything but false, the dialog will be closed. buttons in <dialog> predefined there are six button types you can use in the buttons attribute of dialog. they are: accept — ok button. cancel — ...
...). programmatic button access if you want to access the accept ("ok") and cancel buttons from script, use this: // disable the ok and cancel btns document.documentelement.getbutton("accept").disabled = true; document.documentelement.getbutton("cancel").disabled = true; links dialog.xml — xbl bindings for <dialog> and <dialogheader> elements. passing parameter to a dialog and getting re
turn values from it. passing arguments and displaying a dialog the following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and re
turn user-modified arguments to the caller. the code to open a dialog named mydialog.xul and pass it arguments: var params = {inn:{name:"foo", description:"bar", enabled:true}, out:null}; window.opendialog("chrome:...
... "chrome, dialog, modal, resizable=yes", params).focus(); if (params.out) { // user clicked ok. process changed arguments; e.g. write them to disk or whatever } else { // user clicked cancel. typically, nothing is done here. ...
...And 2 more matches
JavaScript Debugger Service - Archive of obsolete content
tes 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) { // your function here } }; // triggered when jsd.errorhook[onerror] re
turns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd. note that onerror is...
...rrorhook = components.interfaces.jsdierrorhook; var messagetype; if (flags & jsdierrorhook.report_error) messagetype = "error"; if (flags & jsdierrorhook.report_warning) messagetype = "warning"; if (flags & jsdierrorhook.report_exception) messagetype = "uncaught-exception"; if (flags & jsdierrorhook.report_strict) messagetype += "-strict"; dump(messagetype + "\n"); re
turn false; // trigger debughook // re
turn true; if you do not wish to trigger debughook } }; // note that debughook does not _always_ trigger when jsd.errorhook[onerror] re
turns false // it is not well-known why debughook sometimes fails to trigger jsd.debughook = { onexecute: function(frame, type, rv) { stacktrace = ""; for (var f = frame; f; f = f.callingframe) { stacktrace += f.scrip...
...note that the jsdifilter only applies to jsdiexecutionhooks, which are breakpointhook, debughook, debuggerhook, interrupthook and throwhook. ...
...And 2 more matches
QuerySelector - Archive of obsolete content
along the lines of other frameworks such as jquery or prototype, shortening the "queryselector" name can be convenient: function $ (selector, el) { if (!el) {el = document;} re
turn el.queryselector(selector); } function $$ (selector, el) { if (!el) {el = document;} re
turn el.queryselectorall(selector); // note: the re
turned object is a nodelist. ...
...shortening the "queryselector" name can be convenient: function $ (selector, el) { if (!el) {el = document;} re
turn el.queryselector(selector); } function $$ (selector, el) { if (!el) {el = document;} re
turn el.queryselectorall(selector); // note: the re
turned object is a nodelist. ...
...all(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by re
turning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html re
turn this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { re
turn this.queryselector(selector); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) ...
...And 2 more matches
Installing Extensions and Themes From Web Pages - Archive of obsolete content
best experience to users. web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { re
turn this.url; } } }; installtrigger.install(params); re
turn false; } //--> </script> <a href="http://www.example.com/foo.xpi" iconurl="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="re
turn install(event);">install extension!</a> let's go through this piece by piece. the html <a> is the install link. the href attribute contains a direc...
...t clicking on the link and choosing "save link as..." when the link is clicked it calls the function install passing the event object as the parameter. the install first creates a parameter block: var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { re
turn this.url; } }; this specifies the display name (foo) for use in the confirmation dialog, the url to the extension (which is the link href, recall), the icon url to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a tostring function which will allow this code to work with versions of firefox 0.8 and earlier. you could also use the...
...le contents (to protect against corrupted downloads), and a tostring function which will allow this code to work with versions of firefox 0.8 and earlier. you could also use the old style parameter block ({ "foo": aevent.target.href }) if you wanted - and didn't have an icon to use for the confirmation dialog. installtrigger.install is then called to install the item with the parameter block. re
turn false; this last part is the most important - the install function must re
turn false so that when the link is clicked, only the script is run, and the link href is not navigated to. if you omit this step, the user may see two installation dialogs—since you've effectively invoked two install requests, one from the installtrigger, one from trying to load the xpi file directly. available parame...
...And 2 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
when you run it, you should see a red bar, showing that it failed. implement in calc.js we need to flesh out calc.js. update it with the contents of listing 3. run test run the test again. you should...
...when you run it, you should see a red bar, showing that it failed. implement in calc.js we need to flesh out calc.js. update it with the contents of listing 3. run test run the test again. you should see a green bar showing that the test succeeded. implement the subt...
...k = new array(); } rpncalc.prototype = { init: function() { this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(func(a, b)); }, plus: function() { re
turn this._letfunc(this._plus); }, _plus: function(a, b) { re
turn a + b; }, pop: function() { re
turn this.stack.pop(); } } check for errors now you’re ready for your first test. when you run it, you should see a red bar, showing that it failed. implement in calc.js we need to flesh out calc.js. update it with the contents of listing 3. run test run the test again. you should see a green bar showing that the test succeeded. implement the subtraction operation now let’s add subtract...
...And 2 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
this...
...this scheme is highly flexible and can be made to work under most circumstances. css animation events this technique, which works on firefox 5+, has some particular advantages. ...
... for nodes matching the given css selector to become * available. * * @param {string} selector the css selector of nodes about which you * want to be notified. * @param {function(event)} callback the function which is to be called * when matching nodes become available. * @param {document} doc the document in which to watch for new nodes. * @optional @default document * * @re
turns {function} a function which may be called to unregister the * listener. */ if ('mozcsskeyframerule' in window || 'csskeyframerule' in window) { var watchnodes = function watchnodes(selector, callback, doc) { const event = watchnodes.prefix + (watchnodes._i++); const xhtml = 'http://www.w3.org/1999/xhtml'; doc = doc || document; let style = doc.createelemen...
...And 2 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
note this article is the version from 2003 with slight modifications (no images and no links to samples). it's here for reference. introduction when you click a link on a web page, your web browser makes a request to a web server which usually results in a new web page as a response. that new page may have links that take you to other pages, which may in
turn have more links, and so on. this model of web navigation is so common that most internet users do little else. but as the internet matures, this model has begun to show its age and its limitations. for web developers, for example, it provides less fine-grained control over the experience, and it can strain bandwidth and other resources. and for users it usually doesn't begin to approach the seamlessness and usability of good ap...
...l. in this case, the content that is updated on the page is a set of headlines for devedge articles. this example uses the actual xml datasources from devedge web site. this example also follows the same model with a data loader and data binder component. data loader component this component uses xmlhttprequest to load the xml data that represents the article headlines. xmlhttprequest interface re
turns the dom for the document that was passed. var x = new xmlremoterequest(); doc=x.getremotedocument(loaddata); note: the above code snippet shows an object being instanciated based on a class named xmlremoterequest. this class is just an abstraction layer that encapsulates the xmlhttprequest interface, and provides cross-browser support for recent ie versions and gecko-based browsers. the followin...
.../catalog-new_en.xml http://web.archive.org/web/20090218052509/http://devedge-temp.mozilla.org/central/xml/catalog-new_en.xml http://web.archive.org/web/20100913225355/http://devedge-temp.mozilla.org/central/css/catalog-new_en.xml http://web.archive.org/web/20090218052536/http://devedge-temp.mozilla.org/viewsource/catalog-new_en.xml data binder component this procedure traverses the dom that was re
turned via xmlhttprequest and generates markup based on the data provided in the dom nodes. when the markup is ready, it copies the markup into the container element, which is a div element. the following code snippet shows a simplified version of the logic that happens in the actual sample: // doc is the dom to the document re
turned articles=doc.getelementsbytagname("article"); for(i=0;i<articles.len...
...And 2 more matches
Autodial for Windows NT - Archive of obsolete content
002. introduction this document is intended to explain how the autodial helper feature implemented for bug 93002 works and why it works that way. a brief history of autodial on windows in the consumer versions of windows, (windows 95, windows 98, windows me) autodial for all applications is controlled from the control panel, in the internet options applet, under the tab connections. if you
turn on the autodial feature, windows will automatically dial whenever any application tries to access a network address that can't be reached. technically, this control panel applet (internet options) is part of internet explorer. it is not present in early versions of windows until internet explorer is installed. despite this fact, the feature is triggered by any application that uses networking. st...
...odial helper adds the address to the ras autodial address db. the next time this address is tried and can't be found, the autodial service will be triggered and dialup will commence. many windows xp users, especially windows xp home users, don't understand that microsoft has changed how autodial works. ...
...if an address can't be reached, we trigger the autodial features from inside mozilla. if a default dialup connection is configured, we use that one. if more than one dialup connection is configured, and none is selected as the default, we display a list of dialup connections and let the user choose one. ...
...And 2 more matches
Using Dehydra - Archive of obsolete content
d! see documentation for: process_type, input_end, print, .loc property example: using attributes to mark a class as "final" save the following code as final.cc: // this class should not be subclassed! ...
...ss as "final" save the following code as final.cc: // this class should not be subclassed! class __attribute__((user("final"))) myclass { }; // this subclass should be an error class subclass : public myclass { }; save the following analysis script final.js: /** * helper function: re
turns true if a class is marked with the "final" attribute. ...
...ibute__((user("final"))) myclass { }; // this subclass should be an error class subclass : public myclass { }; save the following analysis script final.js: /** * helper function: re
turns true if a class is marked with the "final" attribute. ...
...And 2 more matches
Exception logging in JavaScript - Archive of obsolete content
this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. ...
...this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. ...
... interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console. any exceptions that are generated by xpconnect -- that is, those exceptions whose result codes are defined in nsixpconnect.idl -- are always logged into the error console. the ns_nointerface error is never reported when re
turned by a javascript object's queryinterface() method on the nsisupports interface. the ns_nointerface error is never reported when re
turned by a javascript object's getinterface() method on the nsiinterfacerequestor interface. all other errors are reported when the last javascript frame on the stack re
turns to a c++ caller without handling the exception. that last point deserves clarification. c...
...And 2 more matches
DOM Interfaces - Archive of obsolete content
in domstring attrname, in domstring attrvalue); element getbindingparent(in node node); void loadbindingdocument(in domstring documenturl); }; methods getanonymousnodes the getanonymousnodes method retrieves the anonymous children of the specified element. parameters elt - the element to retrieve anonymous children for. re
turn value nodelist - the re
turn value of getanonymousnodes is a nodelist that represents the children of an element after insertion points from its own binding have been applied. this means that, depending on the details regarding the insertion points of the binding, it's possible that some non-anonymous nodes appear in the list. see "not so anonymous nodes" on mozilla.dev.platform for some dis...
...bute the getanonymouselementbyattribute methods retrieves an anonymous descendant with a specified attribute value. typically used with an (arbitrary) anonid attribute to retrieve a specific anonymous child in an xbl binding. parameters elt - the element to retrieve anonymous children for. attrname - the attribute name to look up. attrvalue - the attribute value to match. re
turn value element - the re
turn value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value. getbindingparent the getbindingparent method is used to obtain the bound element with the binding attached that is responsible for the generation of the specified anonymous node. this method enables an author to determine the scop...
...e bound element with the binding attached that is responsible for the generation of the specified anonymous node. this method enables an author to determine the scope of any content node. when content at the document-level scope is passed in as an argument, the property's value is null. parameters node - the node for which the bound element responsible for generation is desired. re
turn value element - the re
turn value of getbindingparent is the element responsible for the given anonymous node. loadbindingdocument the loadbindingdocument method can be used to synchronously obtain the specified binding document for use within a particular document (the one on which the loadbindingdocument method was invoked). the binding document can then be modified programmatical...
...And 2 more matches
Building accessible custom components in XUL - Archive of obsolete content
null : ...
...null : arsiblings[row + 1]; }...
...next) { next.focus(); } } function get_index_within_parent(current) { var arsiblings = current.parentnode.childnodes; for (var i = 0; i < arsiblings.length; i++) { if (arsiblings[i] == current) { re
turn i; } } re
turn -1; } function find_cell_up(current) { var row = get_index_within_parent(current); var arsiblings = current.parentnode.childnodes; re
turn row == 0 ? null : arsiblings[row - 1]; } function find_cell_down(current) { var row = get_index_within_parent(current); var arsiblings = current.parentnode.childnodes; re
turn row == arsiblings.length - 1 ? null : arsiblings[row + 1]; } function find_cell_left(current) { var row = get_index_within_parent(current); var column = get_index_within_parent(current.parentnode); ...
...And 2 more matches
Working With Directories - Archive of obsolete content
irectory several levels down is referenced. each call to nsifile.append() navigates to a further subdirectory. the result is a subdirectory three levels below the desktop directory. these directories do not need to exist yet, but they can be created using nsifile.create(). see creating directories below for information about this. note that nsifile.append() modifies the file object, rather than re
turning a new one. both files and directories are represented using the same kind of object so most of the functions available for nsifile will work for both. you can check if the object refers to a directory or a file by using nsifile.isdirectory(). this method re
turns true if a file object re
turned by nsiscriptableio.getfile() refers to a directory, and false otherwise. there is also a corresponding...
... directory do not exist, they will be created. thus, you do not have to create a series of directories individually, the set will all be created if needed. naturally, if the 'myfiles' directory already exists, it won't be recreated. iterating over the files in a directory the directory object's directoryentries (nsifile.attributes) attribute is used to get a list of the items in a directory. ...
...as the directoryentries (nsifile.attributes) property is an enumeration, you can iterate over the items by using nsisimpleenumerator.hasmoreelements() and nsisimpleenumerator.getnext(). ...
...And 2 more matches
findbar - Archive of obsolete content
if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_no...
... if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_normal is the defa...
...ueryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata close() re
turn type: no re
turn value closes the notification or findbar and removes it from its enclosing notificationbox or findbar. open( mode ) re
turn type: no re
turn value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links. ...
...And 2 more matches
Adding Properties to XBL-defined Elements - Archive of obsolete content
execute when the property is retrieved or modified. add each to the property element and set its value to a script which either gets or sets the value of the property. for example, you could assign a script to the value of onget to calculate the current time. whenever a script attempts to access the value of the property, the onget script will be called to retrieve the value. the script should re
turn the value that should be treated as the value of that property. the onset handler is similar but is called whenever a script attempts to assign a new value to the property. this script should store the value somewhere, or validate the value. for example, some properties might only be able to store numbers. attempting to assign alphabetic text to such a property should fail. <property name="size" ...
...uld be treated as the value of that property. the onset handler is similar but is called whenever a script attempts to assign a new value to the property. this script should store the value somewhere, or validate the value. for example, some properties might only be able to store numbers. attempting to assign alphabetic text to such a property should fail. <property name="size" onget="re
turn 77;" onset="alert('changed to:'+val);"/> this property will always re
turn 77 when retrieved. when set, an alert will be displayed which displays the value to assign to the property. the special variable val holds the value that the property should be assigned to. use this to validate it or store it. the following decribes what happens in a typical case: there are two elements, one call...
...assigned to. use this to validate it or store it. the following decribes what happens in a typical case: there are two elements, one called 'banana' and the other 'orange'. they each have a custom property called 'size'. when the following line of script is executed: banana.size = orange.size; the onget script is called for the size property of the orange. the script calculates the value and re
turns it. the onset handler of the size property of the banana is called. this script uses the value passed in the val variable and assigns it to the size property of the banana in some manner. note that unlike a field, a property does not hold a value. attempting to set a property that does not have an onset handler will generate an error. you will often use a separate field to hold the actual valu...
...And 2 more matches
Creating a Wizard - Archive of obsolete content
d on a wizardpage element to provide a sub-caption for that page. in the example above, it has been placed on the second page, but not the first page. handling page changes you will generally want to do something once the finish button is pressed. you can set an attribute onwizardfinish on the wizard element to accomplish this. ...
... want to do something once the finish button is pressed. you can set an attribute onwizardfinish on the wizard element to accomplish this. set it to a script which performs whatever task you want and then re
turns true. this script might be used to save the information that the user entered during the wizard. ...
...ser entered during the wizard. for example: <wizard id="example-window" title="select a dog wizard" onwizardfinish="re
turn savedoginfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> when the user clicks the finish button, the function savedoginfo() will be called, which would be defined in a script file to save the information that was entered. if the function re
turns true, the wizard closes. if it re
turns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example. there are also related onwizardback, onwizardnext and onwizardcancel attributes, which are called when the back, next and cancel buttons are pressed respectively. these functions are called regardless of which page is currently dis...
...And 2 more matches
Open and Save Dialogs - Archive of obsolete content
is a semicolon-seperated list of file masks. you can add more masks or fewer masks as needed. you can call appendfilter as many times as necessary to add additional filters. the order you add them determines their priority. typically, the first one added is selected by default. getting the selected file finally, you can show the dialog by calling the show() function. ...
... you can call appendfilter as many times as necessary to add additional filters. the order you add them determines their priority. typically, the first one added is selected by default. getting the selected file finally, you can show the dialog by calling the show() function. it takes no arguments but re
turns a status code that indicates what the user selected. note that the function does not re
turn until the user has selected a file. ...
... add additional filters. the order you add them determines their priority. typically, the first one added is selected by default. getting the selected file finally, you can show the dialog by calling the show() function. it takes no arguments but re
turns a status code that indicates what the user selected. note that the function does not re
turn until the user has selected a file. the function re
turns one of three constants: re
turnok - the user selected a file and pressed ok. ...
...And 2 more matches
XPCOM Interfaces - Archive of obsolete content
vides some component related functions. here, we get a component class from the classes property. the classes property is an array of all of the available components. to get a different component, just replace the contract id inside the square brackets with the contract id of the component you want to use. finally, an instance is created with the createinstance() function. you should check the re
turn value of createinstance() to ensure that it is not null, which would indicate that the component does not exist. however, at this point, we only have a reference to the file component itself. in order to call the functions of it we need to get one of its interfaces, in this case nsilocalfile. a second line of code needs to be added as follows: var afile = components.classes["@mozilla.org/file/l...
...face() on an object and the requested interface is not supported by an object, an exception is thrown. if you're not sure that an interface is supported by a component, you can use the instanceof operator to check: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); if (afile instanceof components.interfaces.nsilocalfile){ // do something } the instanceof operator re
turns true if afile implements the nsilocalfile interface. this also has the side effect of calling queryinterface(), so afile will be a valid nsilocalfile afterwards. calling the functions of an interface now that we have an object that refers to a component with the nsilocalfile interface, we can call the functions of nsilocalfile through it. the table below shows some of the properties and method...
...ctions of nsilocalfile through it. the table below shows some of the properties and methods of the nsilocalfile interface. initwithpath this method is used to initialize the path and filename for the nsilocalfile. the first parameter should be the file path, such as '/usr/local/mozilla'. leafname the filename without the directory part. filesize the size of the file. isdirectory() re
turns true if the nsilocalfile represents a directory. remove(recursive) deletes a file. if the recursive parameter is true, a directory and all of its files and subdirectories will also be deleted. copyto(directory,newname) copies a file to another directory, optionally renaming the file. the directory should be a nsilocalfile holding the directory to copy the file to. moveto(directory,newname...
...And 2 more matches
XUL Questions and Answers - Archive of obsolete content
more documentation on search plugins is available in the search plugins category. is localizing remote xul possible? loading remote dtds for xml documents is currenty not supported in xul. the following bugs were reported on this issue: bug 22942, bug 133698. is there an editor widget in xul that supports syntax highlighting? daniel glazman has been working on this for his projects. ...
...ey will have to implement one. are xul attributes integers? xul attributes such as left="100" or top="200", as well as corresponding properties, look as if they're integers but they are actually handled as strings. to convert them to integers use the parseint() javascript function. while the attributes are always strings per the dom specification, the properties will eventually be fixed to re
turn the value with the correct type. using the "icon" attribute on a button from xulplanet.com reference: this attribute should be used to set the usage for common buttons. some platforms display these buttons with a small icon indicating their usage. this should be used in place of the image attribute. possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, clo...
...ts.interfaces.nsiwebprogress.notify_state_window ); // remember to define the object, something like this: listobj = new object(); listobj.wpl = components.interfaces.nsiwebprogresslistener; listobj.queryinterface = function(aiid) { if (aiid.equals(listobj.wpl) || aiid.equals(components.interfaces.nsisupportsweakreference) || aiid.equals(components.interfaces.nsisupports)) re
turn this; throw components.results.ns_nointerface; } listobj.onstatechange = function(aprogress, arequest, aflag, astatus) { if (aflag & listobj.wpl.state_start) { // this fires when the load event is initiated } else { if (aflag & listobj.wpl.state_stop) { if ( aflag & listobj.wpl.state_is_window ) { // this fires when all load finish } if ( aflag & listob...
...And 2 more matches
notificationbox - Archive of obsolete content
if another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. keep in mind that this is all xul so using html elements for s...
...ription is an object with the following properties: accesskey - the accesskey to appear on the button callback - function to be called when the button is activated. this function is passed three arguments: the <notification> the button is associated with the button description as passed to appendnotification. the element which was the target of the button press event. if the re
turn value from this function is not true, then the notification is closed. the notification is also not closed if an error is thrown. label - the label to appear on the button popup - the id of a popup for the button. if null, the button is not a button popup (e.g. a menu). the type property must also be set to "menu", or "menu-button". isdefault - if true, this is the default button. there c...
... type property must also be set to "menu", or "menu-button". isdefault - if true, this is the default button. there can be only one default button. if no button has this set, the first button in the array is the default. type - a string. valid values are "menu-button" and "menu" which must be set if the button is to provide a popup via the popup property. getnotificationwithvalue( value ) re
turn type: notification element retrieve the notification with a particular value. the value is specified when adding the notification with appendnotification. if no matching value is found, re
turns null. removeallnotifications( immediate ) re
turn type: no re
turn value remove all notifications. if immediate is true, the messages are removed immediately. if immediate is false, the notifications a...
...And 2 more matches
stringbundle - Archive of obsolete content
strings type: nsisimpleenumerator an enumeration of all of the strings in the string bundle. the...
...ext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties applocale obsolete since gecko 1.9.1 type: nsilocale re
turns the xpcom object which holds information about the user's locale. this is an object which implements nsilocale. src type: url gets and sets the value of the src attribute. stringbundle type: nsistringbundle re
turns the xpcom string bundle object which implements nsistringbundle. strings type: nsisimpleenumerator an enumeration of all of the strings in the string bundle. the enumeration contains nsipropertyelement objects. ...
...alternatively, numbered indices of the format %n$s (e.g. ...
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
how to customizes toolbar button to coexist in a toolbar palette and status bar? option #3 install status buttons 1.0 <https://addons.mozilla.org/firefox/1272/> "lets you put toolbar buttons at either end of the status-bar. just drag them there from the toolbar customisation window, like you would when adding buttons to the toolbars." option #4 install toolbar control <http://webdesigns.ms11.net/chromeditp.html> asking for help with getting an extension to process windows messages. ...
...tp://svn.dojotoolkit.org/dojo/trunk/dojo.js see what it's trying to load and write out the script element by hand. could someone write an extension that would collapse the current sidebar in firefox? these are called "grippies" <https://addons.mozilla.org/firefox/2242/> this extension brings grippies back to firefox (and thunderbird!) is there any way to write a regular extension that re
turns a "dummy" object when an instance of "@mozilla.org/helperapplauncherdialog;1" is created? you can write a dummy xpcom component implementing the necessary interfaces and register it with the sane contract id. http://developer.mozilla.org/en/docs...pcom_component would anyone be able to suggest the best way to do source level debugging in a firefox extension? in the debug menu, uncheck excl...
...faces and register it with the sane contract id. http://developer.mozilla.org/en/docs...pcom_component would anyone be able to suggest the best way to do source level debugging in a firefox extension? in the debug menu, uncheck exclude browser files. use the debugger by typing in a command like this: /break chrome://myextension/content/myfile.js 123 then i suggest using flat chrome. if you
turn off the xul cache you don't even need to restart to see changes, simply open a new window. how can i backup some of the files before upgrade an extension and put them back afterward? do i need to write an installation script to achieve this? you shouldn't store data there, so there's nothing to backup. do not store files within the extension directory. the profile directory is ment to do s...
...And 2 more matches
NPAPI plugin reference - Archive of obsolete content
e plug-in api this chapter describes methods in the plug-in api that are provided by the browser; these allow call back to the browser to request information, tell the browser to repaint part of the window, and so forth. the names of all of these methods begin with npn_ to indicate that they are implemented by the browser and called by the plug-in. np_getmimedescription np_getmimedescription re
turns a supported mime type list for your plugin. it works on unix (linux) and macos. on windows you have to define supported mimetypes in the dll resource file. np_getvalue allows the browser to query the plug-in for information. np_initialize provides global initialization for a plug-in. np_port contains information required by the window field of an npwindow structure. np_shutdown provides ...
... npn_enumerate gets the names of the properties and methods of the specified npobject. npn_evaluate evaluates a script in the scope of the specified npobject. npn_forceredraw asks the plugin host to immediately (synchronously) repaint invalid areas. npn_getauthenticationinfo the function is called by plugins to get http authentication information from the browser. npn_getintidentifier re
turns an opaque identifier for the integer that is passed in. npn_getproperty gets the value of a property on the specified npobject. npn_getstringidentifier re
turns an opaque identifier for the string that is passed in. npn_getstringidentifiers re
turns an array of opaque identifiers for the names that are passed in. npn_geturl asks the browser to create a stream for the specified url. npn_ge...
...vides information to a plugin which is associated with a given url, for example the cookies or preferred proxy. npn_hasmethod determines whether or not the specified npobject has a particular method. npn_hasproperty determines whether or not the specified npobject has a particular property. npn_identifierisstring determines whether or not an identifier is a string. npn_intfromidentifier re
turns the integer value corresponding to the given integer identifier. npn_invalidaterect invalidates the specified portion of the plugin's drawing area, adding it to the region that needs to be redrawn when the plugin next repaints its contents. npn_invalidateregion invalidates the specified drawing region prior to repainting or refreshing a windowless plug-in. npn_invoke invokes a method on th...
...And 2 more matches
Iterator - Archive of obsolete content
non-standard. the iterator function is a spidermonkey-specific feature, and will be removed at some point. for future-facing usages, consider using for..of loops and the iterator protocol. the iterator function re
turns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. syntax iterator(object, [keyonly]) parameters object object to iterate over properties. keyonly if keyonly is truthy value, iterator.prototype.next re
turns property_name only. description re
turns iterator instance that iterates over object. iterator instance re
turns [property_name, property_value] array for each iteration if keyonly is falsy, otherwise, if keyonly is truthy, it re
turns property_name for each iteration. if object is the iterator instanc...
...it throws stopiteration if there are no more items. ...
...it throws stopiteration if there are no more items. ...
...And 2 more matches
JSException - Archive of obsolete content
constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception. getwrappedexceptiontype insta...
... netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception. getwrappedexceptiontype instance method getwrappedexceptiontype re
turns the int mapping of the type of the wrappedexception object. backward compatibility javascript 1.1 through 1.3 jsexception had three public constructors which optionally took a string argument, specifying the detail message or other information for the exception. the getwrappedexception method was not available. jsexception constructors, deprecated in javascript 1.4, constructs a jsexception...
...the file where the error occurred, if possible. lineno the line number of the file, if possible. source the string containing the javascript code being evaluated. tokenindex the index into the source string where the error occurred. getwrappedexception instance method getwrappedexception. ...
...And 2 more matches
3D collision detection - Game development
aabb checking whether an aabb intersects another aabb is similar to the point test. we just need to do one test per axis, using the boxes' boundaries. the diagram below shows the test we'd perform over the x-axis — basically...
...one test per axis, using the boxes' boundaries. the diagram below shows the test we'd perform over the x-axis — basically, do the ranges aminx–amaxx and bminx–bmaxx overlap? mathematically this would look like so: f(a,b)=(aminx<=bmaxx∧amaxx>=bminx)∧(aminy<=bmaxy∧amaxy>=bminy)∧(aminz<=bmaxz∧amaxz>=bminz)f(a,b) = and in javascript, we'd use this: function intersect(a, b) { re
turn (a.minx <= b.maxx && a.maxx >= b.minx) && (a.miny <= b.maxy && a.maxy >= b.miny) && (a.minz <= b.maxz && a.maxz >= b.minz); } bounding spheres using bounding spheres to detect collisions is a bit more complex than aabb, but still fairly quick to test. the main advantage of spheres is that they are invariant to rotation, so if the wrapped entity rotates, the bounding sphere wo...
...an easy optimization to avoid it consists of comparing the squared distance with the squared radius, so the optimized equation would instead involve distancesqr < sphere.radius * sphere.radius. sphere vs. sphere the sphere vs sphere test is similar to the point vs sphere test. what we nee...
...And 2 more matches
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
a programming language is said to have first-class functions when functions in that language are treated like any other variable. for example, in such a language, a function can be passed as an argument to other functions, can be re
turned by another function and can be assigned as a value to a variable. example | assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end. even if your function was named, you can use the variable name to invoke it. naming it will be helpful when debugging your code. but it won't affect the way we invoke it. example | pass a function as a...
...oo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end. even if your function was named, you can use the variable name to invoke it. naming it will be helpful when debugging your code. but it won't affect the way we invoke it. example | pass a function as an argument javascript function sayhello() { re
turn "hello, "; } function greeting(hellomessage, name) { console.log(hellomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() function as an argument to the greeting() function, this explains how we are treating the function as a value. the function that we pass as an argument to another function, is call...
...lomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() function as an argument to the greeting() function, this explains how we are treating the function as a value. the function that we pass as an argument to another function, is called a callback function. sayhello is a callback function. example | re
turn a function javascript function sayhello() { re
turn function() { console.log("hello!"); } } in this example; we need to re
turn a function from another function - we can re
turn a function because we treated function in javascript as a value. a function that re
turns a function is called a higher-order function. back to our example; now, we need to invoke sayhello function and its...
...And 2 more matches
Function - MDN Web Docs Glossary: Definitions of Web-related terms
a function in javascript is also an object. a function name is an identifier included as part of a function declaration or function expression. the function name's scope depends on whether the function name is a declaration or expression. ...
...function name: // function declaration function foo() {}; // named function expression (function bar() {}); // or using the ecmascript 2015 arrow notation const foo = () => {}; an inner function is a function inside another function (square in this case). ...
...ction declaration function foo() {}; // named function expression (function bar() {}); // or using the ecmascript 2015 arrow notation const foo = () => {}; an inner function is a function inside another function (square in this case). ...
...And 2 more matches
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
the same effect while leaving the server in the same state. in other words, an idempotent method should not have any side-effects (except for keeping statistics). implemented correctly, the get, head, put, and delete method are idempotent, but not the post method. all safe methods are also idempotent. to be idempotent, only the actual back-end state of the server is considered, the status code re
turned by each request may differ: the first call of a delete will likely re
turn a 200, while successive ones will likely re
turn a 404. another implication of delete being idempotent is that developers should not implement restful apis with a delete last entry functionality using the delete method. note that the idempotence of a method is not guaranteed by the server and some applications may incorre...
... technical knowledge description of common idempotent methods: get, head, put, delete, option...
... technical knowledge description of common idempotent methods: get, head, put, delete, options, trace description of common non-idempotent methods: post,patch, connect ...
...And 2 more matches
Drawing graphics - Learn web development
r path ctx.fill(); drawing lines let's draw an equilateral triangle on the canvas. first of all, add the following helper function to the bottom of your code. this converts degree values to radians, which is useful because whenever you need to provide an angle value in javascript, it will nearly always be in radians, but humans usually think in degrees. function degtorad(degrees) { re
turn degrees * math.pi / 180; }; next, start off your path by adding the following below your previous addition; here we set a color for our triangle, start drawing a path, and then move the pen to (50, 50) without drawing anything. that's where we'll start drawing our triangle. ctx.fillstyle = 'rgb(255, 0, 0)'; ctx.beginpath(); ctx.moveto(50, 50); now add the following lines at the bot...
... takes three parameters — a reference to the image you want to render, and the x and y coordinates of the image's top left corner. let's start by getting an image source to embed in our canvas. add the following lines to the bottom of your javascript: let image = new image(); image.src = 'firefox.png'; here we create a new htmlimageelement object using the image() constructor. the re
turned object is the same type as that which is re
turned when you grab a reference to an existing <img> element). we then set its src attribute to equal our firefox logo image. at this point, the browser starts loading the image. we could now try to embed the image using drawimage(), but we need to make sure the image file has been loaded first, otherwise the code will fail. we can achieve this ...
...as: ctx.translate(width/2, height/2); this causes the coordinate origin (0, 0) to be moved to the center of the canvas, rather than being at the top left corner. this is very useful in many situations, like this one, where we want our design to be drawn relative to the center of the canvas. ...
...And 2 more matches
Manipulating documents - Learn web development
with web pages. there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object. using methods available on this object you can do things like re
turn the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. the navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the ...
...user-agent) as it exists on the web. in javascript, this is represented by the navigator object. you can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc. the document (represented by the dom in browsers) is the actual page loaded into the window, and is represented in javascript by the document object. you can use this object to re
turn and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether. in this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides. the d...
...to them in an array-like object called a nodelist. there are older methods available for grabbing element references, such as: document.getelementbyid(), which selects an element with a given id attribute value, e.g. <p id="myid">my paragraph</p>. the id is passed to the function as a parameter, i.e. const elementref = document.getelementbyid('myid'). document.getelementsbytagname(), which re
turns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc. the element type is passed to the function as a parameter, i.e. const elementrefarray = document.getelementsbytagname('p'). these two work in older browsers than the modern methods like queryselector(), but are not as convenient. have a look and see what others you can find! creating an...
...And 2 more matches
Silly story generator - Learn web development
using doesn't have a separate javascript panel, feel free to put it inline in a <script> element inside the html page. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief you have been provided with some raw html/css and a few text strings and javascript functions; you need to write the necessary javascript to
turn this into a working program, which does the following: generates a silly story when the "generate random story" button is pressed. replaces the default name "bob" in the story with a custom name, only if a custom name is entered into the "enter custom name" text field before the generate button is pressed. converts the default us weight and temperature quantities and units in the story into ...
...and paste it into the top of the main.js file. this gives you three variables that store references to the "enter custom name" text field (customname), the "generate random story" button (randomize), and the <p> element at the bottom of the html body that the story will be copied into (story), respectively. in addition you've got a function called randomvaluefromarray() that takes an array, and re
turns one of the items stored inside the array at random. now look at the second section of the raw text file — "2. raw text strings". this contains text strings that will act as input into our program. we'd like you to contain these inside variables inside main.js: store the first, big long, string of text inside a variable called storytext. store the first set of three strings inside an ...
...nside variables inside main.js: store the first, big long, string of text inside a variable called storytext. store the first set of three strings inside an array called insertx. store the second set of three strings inside an array called inserty. store the third set of three strings inside an array called insertz. placing the event handler and incomplete function: now re
turn to the raw text file. copy the code found underneath the heading "3. event listener and partial function definition" and paste it into the bottom of your main.js file. this: adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run. adds a partially-completed result() function definiton to your code. for the rema...
...And 2 more matches
Storing the information you need — Variables - Learn web development
ly for single lines, but probably won't when you are writing multiple lines of code together. try to get into the habit of including it. you can test whether these values now exist in the execution environment by typing just the variable's name, e.g. myname; myage; they currently have no value; they are empty containers. when you enter the variable names, you should get a value of undefined re
turned. if they don't exist, you'll get an error message — try typing in scoobydoo; note: don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all — they are very different things. in the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. no value defined would mean that there is a box, but it has no ...
...as no value inside it. initializing a variable once you've declared a variable, you can initialize it with a value. you do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. for example: myname = 'chris'; myage = 37; try going back to the console now and typing in these lines. you should see the value you've assigned to the variable re
turned in the console to confirm it, in each case. again, you can re
turn your variable values by simply typing their name into the console — try these again: myname; myage; you can declare and initialize a variable at the same time, like this: let mydog = 'rover'; this is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines. the difference ...
...booleans are true/false values — they can have two values, true or false. these are generally used to test a condition, after which code is run as appropriate. so for example, a simple case would be: let iamalive = true; whereas in reality it would be used more like this: let test = 6 < 3; this is using the "less than" operator (<) to test whether 6 is less than 3. as you might expect, it re
turns false, because 6 is not less than 3! you will learn a lot more about such operators later on in the course. arrays an array is a single object that contains multiple values enclosed in square brackets and separated by commas. try entering the following lines into your console: let mynamearray = ['chris', 'bob', 'jim']; let mynumberarray = [10, 15, 40]; once these arrays are defined, you can ...
...And 2 more matches
Inheritance in JavaScript - Learn web development
s can become a problem, so we need to set this right. you can do so by going back to your source code and adding the following line at the bottom: object.defineproperty(teacher.prototype, 'constructor', { value: teacher, enumerable: false, // so that it does not appear in 'for in' loop writable: true }); now if you save and refresh, entering teacher.prototype.constructor should re
turn teacher(), as desired, plus we are now inheriting from person()! giving teacher() a new greeting() function to finish off our code, we need to define a new greeting() function on the teacher() constructor. the easiest way to do this is to define it on teacher()'s prototype — add the following at the bottom of your code: teacher.prototype.greeting = function() { let prefix; if (this.ge...
...'s a little catch. unlike old-school constructor functions where the new operator does the initialization of this to a newly-allocated object, this isn't automatically initialized for a class defined by the extends keyword, i.e the sub-classes. therefore running the above code will give an error: uncaught referenceerror: must call super constructor in derived class before accessing 'this' or re
turning from derived constructor for sub-classes, the this intialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending. here we are extending the person class — the teacher sub-class is an extension of the person class. so for teacher, the this initialization is done by the person constructor. ...
...of an attribute will be. using the teacher example, we may not know what subject the teacher will teach before we create them, or their subject may change between terms. we can handle such situations with getters and setters. let's enhance the teacher class with getters and setters. the class starts the same as it was the last time we looked at it. getters and setters work in pairs. a getter re
turns the current value of the variable and its corresponding setter changes the value of the variable to the one it defines. the modified teacher class looks like this: class teacher extends person { constructor(first, last, age, gender, interests, subject, grade) { super(first, last, age, gender, interests); // subject and grade are specific to teacher this._subject = subject; th...
...And 2 more matches
Object prototypes - Learn web development
person1's constructor — person() — name, age, gender, interests, bio, and greeting. you will however also see some other members — tostring, valueof, etc — these are defined on person1's prototype object's prototype object, which is object.prototype. what happens if you call a method on person1, which is actually defined on object.prototype? for example: person1.valueof() valueof() re
turns the value of the object it is called on. in this case, what happens is: the browser initially checks to see if the person1 object has a valueof() method available on it, as defined on its constructor, person(), and it doesn't. so the browser checks to see if the person1's prototype object has a valueof() method available on it. it doesn't, then the browser checks person1's prototype object's...
... create a new object instance. for example, try this in your previous example's javascript console: let person2 = object.create(person1); what create() actually does is to create a new object from a specified prototype object. here, person2 is being created using person1 as a prototype object. you can check this by entering the following in the console: person2.__proto__ this will re
turn the person1 object. the constructor property every constructor function has a prototype property whose value is an object containing a constructor property. this constructor property points to the original constructor function. as you will see in the next section, properties defined on the person.prototype property (or in general on a constructor function's prototype property, which is an obje...
... general on a constructor function's prototype property, which is an object, as mentioned in the above section) become available to all the instance objects created using the person() constructor. hence, the constructor property is also available to both person1 and person2 objects. for example, try these commands in the console: person1.constructor person2.constructor these should both re
turn the person() constructor, as it contains the original definition of these instances. a clever trick is that you can put parentheses onto the end of the constructor property (containing any required parameters) to create another object instance from that constructor. the constructor is a function after all, so can be invoked using parentheses; you just need to include the new keyword to specify...
...And 2 more matches
Framework main features - Learn web development
lebars will build html like this: <header> <h1>hello, world!</h1> </header> typescript typescript is a superset of javascript, meaning it extends javascript — all javascript code is valid typescript, but not the other way around. typescript is useful for the strictness it allows developers to enforce on their code. for instance, consider a function add(), which takes integers a and b and re
turns their sum. in javascript, that function could be written like this: function add(a, b) { re
turn a + b; } this code might be trivial for someone accustomed to javascript, but it could still be clearer. javascript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings — it just might not give you the result you'd exp...
...ccustomed to javascript, but it could still be clearer. javascript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings — it just might not give you the result you'd expect. what if we wanted to only allow numbers to be passed into this function? typescript makes that possible: function add(a: number, b: number) { re
turn a + b; } the : number written after each parameter here tells typescript that both a and b must be numbers. if we were to use this function and pass '2' into it as an argument, typescript would raise an error during compilation, and we would be forced to fix our mistake. we could write our own javascript that raises these errors for us, but it would make our source code significantly more verbos...
...t for their work. you might create an authorcredit component to go with each article. this component needs to display a portrait of the author and a short byline about them. in order to know what image to render, and what byline to print, authorcredit needs accept some props. a react representation of this authorcredit component might look something like this: function authorcredit(props) { re
turn ( <figure> <img src={props.src} alt={props.alt} /> <figcaption>{props.byline}</figcaption> </figure> ); } {props.src}, {props.alt}, and {props.byline} represent where our props will be inserted into the component. to render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component): <authorcredit ...
...And 2 more matches
Accessibility in React - Learn web development
us on an element until after the <todo /> component renders and react knows where our refs are. change the import statement of todo.js again to add useeffect: import react, { useeffect, useref, usestate } from "react"; useeffect() takes a function as an argument; this function is executed after the component renders. let's see this in action; put the following useeffect() call just above the re
turn statement in the body of todo(), and pass into it a function that logs the words "side effect" to your console: useeffect(() => { console.log("side effect"); }); to illustrate the difference between the main render process and code run inside useeffect(), add another log – put this one below the previous addition: console.log("main render"); now, open the app in your browser. you should s...
...d() } if (waseditingbefore && isnoteditingnow) { focusoneditbutton() } the react team had discussed ways to get a component’s previous state, and has provided an example custom hook we can use for the job. paste the following code near the top of todo.js, above your todo() function. function useprevious(value) { const ref = useref(); useeffect(() => { ref.current = value; }); re
turn ref.current; } now we'll define a wasediting constant beneath the hooks at the top of todo(). we want this constant to track the previous value of isediting, so we call useprevious with isediting as an argument: const wasediting = useprevious(isediting); with this constant, we can update our useeffect() hook to implement the pseudocode we discussed before — update it as follows: useeffect((...
...nearby. the list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left. creating our ref import the useref() and useeffect() hooks into app.js — you'll need them both below: import react, { usestate, useref, useeffect } from "react"; then declare a new ref inside the app() function. just above the re
turn statement is a good place: const listheadingref = useref(null); prepare the heading heading elements like our <h2> are not usually focusable. this isn't a problem — we can make any element programmatically focusable by adding the attribute tabindex="-1" to it. this means only focusable with javascript. you can't press tab to focus on an element with a tabindex of -1 the same way you could do...
...And 2 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
<button type="button" class="btn btn__danger"> delete <span class="visually-hidden">{todo.name}</span> </button> </div> </div> </li> {:else} <li>nothing to do here!</li> {/each} </ul> notice how we are using curly braces to embed javascript expressions in html attributes, like we did with the checked and id attributes of the checkbox. we've
turned our static markup into a dynamic template ready to display the tasks from our component's state. great! we are getting there. working with props with a hardcoded list of todos, our todos component is not very useful. to
turn our component into a general purpose to-do editor we should allow the parent of this component to pass in the list of todos to edit. this would allow us to save them to a...
... in todos.svelte, replace the existing let todos = ... block with export let todos = []. export let todos = [] this may feel a little weird at first. ...
...rdingly. let's use this in our addtodo() function — update it like so: function addtodo() { todos = [...todos, { id: newtodoid, name: newtodoname, completed: false }] newtodoname = '' } filtering todos by status finally for this article, let's implement the ability to filter our todos by status. we'll create a variable to hold the current filter, and a helper function that will re
turn the filtered todos. at the bottom of our <script> section add the following: let filter = 'all' const filtertodos = (filter, todos) => filter === 'active' ? todos.filter(t => !t.completed) : filter === 'completed' ? todos.filter(t => t.completed) : todos we use the filter variable to control the active filter: all, active, or completed. just assigning one of these values...
...And 2 more matches
Creating our first Vue component - Learn web development
the value of its own props. there are a lot of reasons for this. in part, components editing props can make debugging a challenge. if a value is passed to multiple children, it could be hard to track where the changes to that value were coming from. in addition, changing props can cause components to re-render. so mutating props in a component would trigger the component to rerender, which may in-
turn trigger the mutation again. to work around this, we can manage the done state using vue’s data property. the data property is where you can manage local state in a component, it lives inside the component object alongside the props property and has the following structure: data() { re
turn { key: value } } you'll note that the data property is a function. this is to keep the data valu...
...ata, as you may expect. we'll see an example of this shortly. note: because of the way that this works in arrow functions (binding to the parent’s context), you wouldn’t be able to access any of the necessary attributes from inside data if you used an arrow function. so don’t use an arrow function for the data property. so let's add a data property to our todoitem component. ...
.... so don’t use an arrow function for the data property. so let's add a data property to our todoitem component. this will re
turn an object containing a single property that we'll call isdone, whose value is this.done. update the component object like so: export default { props: { label: { required: true, type: string }, done: { default: false, type: boolean } }, data() { re
turn { isdone: this.done }; } }; vue does a little magic here — it binds all of your props directly to the component instance, so we don’t have to call this.props.done. it also binds other attributes (data, which you’ve already seen, and others like methods, computed, etc.) directly to the instance. this is, in part, to make them available to your template. the down-side to this is ...
...And 2 more matches
Setting up your own test automation environment - Learn web development
project folder, then enter the following command: node google_test you should see an instance of firefox automatically open up! google should automatically be loaded in a tab, "webdriver" should be entered in the search box, and the search button will be clicked. webdriver will then wait for 2 seconds; the document title is then accessed, and if it is "webdriver - google search", we will re
turn a message to claim the test is passed. webdriver will then close down the firefox instance and stop. testing in multiple browsers at once there is also nothing to stop you running the test on multiple browsers simultaneously. let's try this! create another new file inside your project directory called google_test_multiple.js. you can feel free to change the references to some of the other br...
...y fail. in our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); } else { console.log('test failed'); } }); }); the sleep() method accepts a value that specifies the time to wait in milliseconds — the method re
turns a promise that resolves at the end of that time, at which point the code inside the then() executes. in this case we get the title of the current page with the gettitle() method, then re
turn a pass or fail message depending on what its value is. we could add a sleep() method to our quick_test.js test too — try wrapping your last line of code in a block like this: driver.sleep(2000).then(func...
...inside your test directory) using the following command: mocha --no-timeouts you should include the --no-timeouts flag to make sure your tests don't end up failing because of mocha's arbitrary timeout (which is 3 seconds). note: saucelabs-sample-test-frameworks contains several useful examples showing how to set up different combinations of test/assertion tools. running remote tests it
turns out that running tests on remote servers isn't that much more difficult than running them locally. you just need to create your driver instance, but with a few more features specified, including the capabilities of the browser you want to test on, the address of the server, and the user credentials you need (if any) to access it. lambdatest getting selenium tests to run remotely on lambdatest ...
...And 2 more matches
Package management basics - Learn web development
ous article, dependencies can be installed globally or locally to your project. although there tend to be more pros for installing globally, the pros for installing locally are more important — such as code portability and version locking. for example, if your project relied on webpack with a certain configuration, you'd want to ensure that if you installed that project on another machine or re
turned to it much later on, the configuration would still work. if a different version of webpack was installed, it may not be compatible. to mitigate this dependencies are installed locally to a project. to see local dependencies really shine, all you need to do is try to download and run an existing project — if it works and all the dependencies work right out of the box, then you have local depe...
...ate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article). type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app. just press re
turn to accept the default parcel-experiment. version: the starting version number for the app: again, just press re
turn to accept the default 1.0.0. description: a quick description of the app's purpose. type in something really simple, like "a simple npm package to learn about using npm", then press re
turn. entry point: this will be the top-level javascript file of the app. the default index.js i...
...el-experiment. version: the starting version number for the app: again, just press re
turn to accept the default 1.0.0. description: a quick description of the app's purpose. type in something really simple, like "a simple npm package to learn about using npm", then press re
turn. entry point: this will be the top-level javascript file of the app. the default index.js is fine for now — press re
turn. test command, git repository, and keywords: press re
turn to leave each of these blank for now. author: the author of the project. type your own name, and press re
turn. license: the license to publish the package under: press re
turn to accept the default for now. press re
turn one more time to accept these settings. go into your parcel-experiment directory and you should now find you've got ...
...And 2 more matches
HTTP logging
(or upload to bugzilla if a developer has asked you for a log). note: the web console also offers the ability to peek at http transactions within firefox. http logging generally provides more detailed logging. using about:networking this is available starting with firefox 52. this is the best and easiest way to do http logging. at any point during while your browser is running, you can
turn logging on and off. this allows you to capture only the "interesting" part of the browser's behavior (i.e. your bug), which makes the http log much smaller and easier to analyze. launch the browser and get it into whatever state you need to be in just before your bug occurs. open a new tab and type in "about:networking" into the url bar. go to the "logging section" adjust the location of t...
...is if it's currently running, by using the quit option in the file menu. keep in mind that simply closing all windows does not quit firefox on mac os x (this is standard practice for mac applications). run the terminal application, which is located in the utilities subfolder in your startup disk's applications folder. copy and paste the following commands into the terminal window, hitting the re
turn key after each line. export moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 export moz_log_file=~/desktop/log.txt cd /applications/firefox.app/contents/macos ./firefox-bin (the instructions assume that you've installed firefox directly into your startup disk's applications folder. if you've put it elsewhere, change the path used on the third line ...
...ly to give us more information about your crash. logging only http request and response headers there are two ways to do this: replace moz_log=nshttp:5 with moz_log=nshttp:3 in the commands above. there's a handy extension for firefox called http header live that you can use to capture just the http request and response headers. this is a useful tool when you want to peek at http traffic. ...
...And 2 more matches
Commenting IDL for better documentation
utomated as much as possible in order to ensure that your interface gets properly documented. happily, following these recommendations will also help ensure your comments are extremely human-readable, too. don't worry! you don't need to write perfect documentation. that is why mozilla has a couple of writers on-staff as well as a horde of happy volunteers. we will take your comments and notes and
turn them into beautiful, easy to search and read documentation. but by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automatically. comment format doxygen supports several comment formats; for style and consistenc...
...ters will expand upon your documentation if necessary. keep in mind that people for whom english is not their native language will be reading your comments (as well as the generated documentation), so try to avoid slang and abbreviations when possible. if possible, avoid putting comments in the middle of the definitions of apis. if an interface is used as a parameter or as the type of the value re
turned by a method, please use the full name of the interface in the description of the method. this will help the tools generate proper links to help make the documentation easier to read and browse through. special commands you can use special commands in your doxygen comments; the ones listed below are interpreted by our tools. using these will help generate much higher quality documentation, fast...
...umentation, faster, with less human intervention required. command details @brief description please only use this to provide a brief description of the interface, keep it short and to the point. do not include more than one brief per interface. @param parameter description every parameter of a method should be documented, only use the parameter name, leave out things like [in]/[out]. @re
turns description if the method re
turns something then this should be included. @throws error description the error should be the actual name of the error constant, in all caps. @note description used to include a note styled paragraph. @remarks remark a remark paragraph to be included in the remarks section of the documentation. note: this is not yet supported by our documentation tool. using ...
...And 2 more matches
Displaying Places information using views
server. result.addobserver(myview.viewer); more practically, a variation of the code above might be internal to a method on your view. a caller would pass in a result or a query, and you would execute the query and add your view as an observing client using addobserver(). (that's how the load method of the built-in tree view works.) when you let your view observe the result, the result will in
turn set the result property on the given nsinavhistoryresultobserver. you should not set the result property explicitly. to disconnect a viewer from its result, call removeobserver(view) on your result. be careful about reference cycles. the viewer and the result both hold owning references to each other. for these objects to be freed during javascript garbage collection, you must clear this cycle b...
...e view: var view = new placestreeview(); view._getcelltext = view.getcelltext; view.getcelltext = function (arowindex, acol) { // handle our special columns. as with placestreeview, we'll recognize // them by their id's or anonid's. ...
...ol) { // handle our special columns. as with placestreeview, we'll recognize // them by their id's or anonid's. ...
...And 2 more matches
Communicating with frame scripts
w (e.g. an xpcom component), you can access the window of the browser that sent the message with message.target.ownerdocument.defaultview. ...
...us message, the frame script uses the global sendsyncmessage() function: // frame script sendsyncmessage("my-addon@me.org:my-e10s-extension-message"); when a chrome script receives a synchronous message, it should re
turn a value from its message listener: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { re
turn "value from chrome"; } this value is then presented to the frame script in the re
turn value of sendsyncmessage(). ...
...us message, it should re
turn a value from its message listener: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { re
turn "value from chrome"; } this value is then presented to the frame script in the re
turn value of sendsyncmessage(). ...
...And 2 more matches
Overview of Mozilla embedding APIs
collection of string classes which support both unicode and ascii strings. these classes provide a variety of string operations as well as dealing with the memory management issues of storing the underlying data. see the string guide for more details. nsweakptr this is an nscomptr which encapsulates xpcom weak reference support. see the nsiweakreference document for more information. public re
turn codes ns_succeeded ns_error_failure ns_error_not_implemented public functions the following functions are available from the xpcom dll. ns_initembedding this function initializes the gecko embedding support. this must be the first function call made into gecko. ns_termembedding this function shuts down gecko and cleans up any remaining resources... currently, once gecko has been s...
...ts down gecko and cleans up any remaining resources... currently, once gecko has been shutdown, it cannot be restarted in the same process space... this should change in the future. nsmemory nsmemory::alloc nsmemory::realloc nsmemory::free this helper class provides static accessors to the global nsmemory service. ns_getglobalcomponentmanager this function re
turns an instance of the component manager service. ns_convertasciitoucs2 this is a helper class which converts an ascii string into a ucs2 string. typically, instances of this class are stack allocated, and wrap ascii arguments which must be converted into ucs2. do_queryinterface this is a helper class which works in conjunction with nscomptr to perform a simplified call to nsisupports::query...
...et of callback interfaces it may choose to implement. below is a code snippet which an embedding application can use to create and initialize a webbrowser: nsresult rv; nscomptr<nsibasewindow> basewindow; nscomptr<nsiwebbrowser> webbrowser; // create a nswebbrowser instance... ...
...And 2 more matches
Embedding Tips
before it happens? implement the nsiuricontentlistener interface, and register it with the appropriate web browser object via the nsiwebbrowser::parenturicontentlistener attribute. watch for changes in nsiuricontentlistener::onstarturiopen(). you can abort the uri load at this point if you don't want it to proceed. if necessary you may also implement the nsiuricontentlistener::ispreferred(), re
turning pr_true to ensure you are always the preferred uri handler and are called no matter what the content type. how do i copy items to the clipboard? obtain the nsiclipboardcommands interface from the appropriate web browser object via nsiserviceprovider::getinterface (or the do_getinterface() helper method). how do i save a document or data to disk? query for the nsiwebbrowserpersist interface...
...formation. for example, if you wanted to check the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. ...
... to make this sample synchronous, i.e. wait for persistence to complete before re
turning. hint, add a native message processing loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the nsiwebbrowserprint::print() method supplying a print settings object (e.g. that re
turned from nsiwebbrowserprint::getglobalprintsettings) that you wish to print the page with. how do i print preview a page? query the web browser object for the nsiwebbrowserprint interface. call the nsiwebbrowserprint::printpreview() method supplying a print settings object (e.g. that re
turned from nsiwebbrowserprint::getglobalprintsettings()) that you wish to preview the page with. the nsiwebbro...
...And 2 more matches
IME handling guide
peech input systems on some platforms. if ime is available on focused elements, we call that state "enabled". if ime is not fully available(i.e., user cannot enable ime), we call this state "disabled". if ime is enabled but users use direct input mode (e.g., for inputting latin characters), we call it "ime is closed". otherwise, we call it "ime is open". (fyi: "open" is also called "active" or "
turned on". "closed" is also called "inactive" or "
turned off") so, this document is useful when you're try to fix a bug for text input in gecko. composition string and clauses typical japanese ime can input two or more words into a composition string. when a user converts from hiragana characters to chinese characters the composition string, japanese ime separates the composition string into multi...
.... for example, if widgetkeyboardevent should be dispatched when there is a composition is managed by this class in xp level. first of use, native ime handlers get the rights to use texteventdispatcher with a call of beginnativeinputtransaction(). then, startcomposition(), setpendingcomposition(), flushpendingcomposition(), commitcomposition(), etc. are available if beginnativeinputtransaction() re
turn true. these methods automatically manage composition state and dispatch widgetcompositionevent properly. this is also used by mozilla::textinputprocessor which can emulates (or implements) ime with chrome script. so, native ime handlers using this class means that the dispatching part is also tested by automated tests. mozilla::widgetcompositionevent internally, widgetcompositionevent represen...
...a part of composition is committed) in the future, we should fix this limitation. if we make editorbase not touch undo stack until composition is committed, some of the cases must be fixed. notifications to ime xp part of gecko uses nsiwidget::notifyime() for notifying widget of something useful to handle ime. note that some of them are notified only when nsiwidget::getimeupdatepreference() re
turns flags which request the notifications. notify_ime_of_text_change, notify_ime_of_selection_change, notify_ime_of_position_change and notify_ime_of_composition_event_handled are always sent by following order: notify_ime_of_text_change notify_ime_of_selection_change notify_ime_of_position_change notify_ime_of_composition_event_handled if sending one of above notifications causes higher pr...
...And 2 more matches
Infallible memory allocation
currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not. eventually, however, the generic memory allocators (malloc() and realloc()) will become infallible. ...
... currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not. eventually, however, the generic memory allocators (malloc() and realloc()) will become infallible. ...
...llocation be infallible? the term "infallible" means that your memory allocation request is guaranteed to succeed: your code can never see a failed request, and so doesn't need to check for failure. inside the allocation routine, the situation is different. under extreme memory conditions, it's possible that the allocation will fail; however, the allocation routine will not, in this scenario, re
turn to your code. instead, the application will terminate. this should be rare, because the memory management system will do everything it can to find the memory you've asked for. choosing a memory allocator as you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocatin...
...And 2 more matches
Introduction to Layout in Mozilla
@mozilla.org/content-viewer-factory/view;1?type=text/html all mime types mapped to the same class, nscontentdlf nsdocshell receives inbound content via nsdsuricontentlistener invokes nsidlf::createinstance, passes mime type to dlf nscontentdlf creates a nshtmldocument object, invokes startdocumentload. ...
...ontentlistener invokes nsidlf::createinstance, passes mime type to dlf nscontentdlf creates a nshtmldocument object, invokes startdocumentload. ...
...ering and fixup occurs here insertchildat, appendchildto, removechildat frame construction content sink uses nsidocument interface to notify of Δs in content model contentappended, contentinserted, contentremoved presshell is registered as document observer receives contentappended, etc. ...
...And 2 more matches
Add-on Repository
the add-on repository is responsible for finding available add-ons; it 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 re
turns 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 ti...
...n searchcallback callback) void searchaddons(in string searchterms, in integer maxresults, in searchcallback callback) properties property type description homepageurl string the url of the repository site's home page. issearching boolean true if a search is currently in progress; otherwise false. methods getrecommendedurl() re
turns the url that can be visited to see recommended add-ons. string getrecommendedurl(); parameters none. re
turn value an url indicating the repository's page of recommended add-ons. getsearchurl() re
turns an url of a web page that can be visited to see search results for the specified search terms. string getsearchurl( in string searchterms ); parameters searchterms search terms used ...
... cancelsearch() cancels the search in progress. does nothing if there is no search in progress. void cancelsearch(); parameters none. retrieverecommendedaddons() begins a search for recommended add-ons in the repository. ...
...And 2 more matches
Download
should be taken that partial data is removed before the reference to the download is discarded. this can be done using the removepartialdata() or the finalize() methods. methods start() starts the download for the first time, or restarts a download that failed or has been canceled. calling this method when the download has been completed successfully has no effect, and the method re
turns a resolved promise. if the download is in progress, the method re
turns the same promise as the previous call. if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately. note: if you need to start a new download from the same source, rather than restarting a failed or canceled one...
... 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 re
turns a resolved promise. you should check the properties of the download at the time the re
turned 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 re
turns a resolved promise. this behavior is designed for the case where the call to cancel happens asynchronou...
... 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 failed, this method has no effect, and it re
turns a resolved promise. if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then removes the partial data. after this method has been called, if the trytokeeppartialdata property is still true when the download is restarted, partial data will be retained during the new download attempt. promise removepartialdata(); ...
...And 2 more matches
FileUtils.jsm
e getfile( string key, array patharray, bool followlinks ); parameters key the nsidirectoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key. the last item in this array must be the leaf name of a file. followlinks optional true if links should be followed, false otherwise. re
turn value re
turns a nsifile object for the file specified. the file is not created if it does not exist, however all required directories along the way are. getdir() gets a directory at the specified hierarchy under a nsidirectoryservice key. nsifile getdir( string key, array patharray, bool shouldcreate, bool followlinks ); parameters key the nsidirectoryservice key to start from (...
...directoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key. shouldcreate optional true if the directory hierarchy specified in patharray should be created if it does not exist, false otherwise. followlinks optional true if links should be followed, false otherwise location specified. re
turn value re
turns a nsifile object for the location specified. if the directory requested does not exist, it is created, along with any parent directories that need to be created. note: if you want to use the full path to get to the directory you cannot use getdir. instead use the file constructor, so simply: var dir = new fileutils.file('c:\\blah\\blah'); if (dir.exists()) { //yes directory ex...
...tstream() opens a file output stream for writing. the stream is opened with the defer_open nsifileoutputstream.behavior flag constant this means the file is not actually opened until the first time it's accessed. nsifileoutputstream openfileoutputstream( nsifile file, int modeflags ); parameters file the file to write to. modeflags optional file open flags (see constants above) re
turn value re
turns nsifileoutputstream (the non-safe variant) to write to. openatomicfileoutputstream() opens an atomic file output stream for writing. note: 'safe' and 'atomic' file output streams will never append; they will always overwrite an existing file. starting in gecko 38.0, passing mode_append without mode_truncate will throw an exception. nsifileoutputstream openatomicfileoutputstr...
...And 2 more matches
Deferred
a deferred object is re
turned by the obsolete promise.defer() method to provide a new promise along with methods to change its state. starting from gecko 30, this object is obsolete and should not be used anymore. use the new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). ...
...hange its state. starting from gecko 30, this object is obsolete and should not be used anymore. use the new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). ...
...o 30, this object is obsolete and should not be used anymore. use the new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below). ...
...And 2 more matches
Refcount tracing and balancing
tive if more release()es than addref()s have happened at the site. to build the balance tree, run tools/rb/make-tree.pl, specifying the object of interest. for example: perl -w tools/rb/make-tree.pl --object 0x00253ab0 < my-leak.log this will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 dosomethingwithfooandre
turnittoo: bal=2 ns_newfoo: bal=1 let's pretend in our toy example that ns_newfoo() is a factory method that makes a new foo and re
turns it. dosomethingwithfooandre
turnittoo() is a method that munges the foo before re
turning it to main(), the main program. what this little tree is telling you is that you leak one refcount overall on object 0x00253ab0. but, more specifically, it shows you that...
...thingwithfooandre
turnittoo() is a method that munges the foo before re
turning it to main(), the main program. what this little tree is telling you is that you leak one refcount overall on object 0x00253ab0. but, more specifically, it shows you that: ns_newfoo() "leaks" a refcount. this is probably "okay" because it's a factory method that creates an addref()-ed object. dosomethingwithfooandre
turnittoo() leaks two refcounts. hmm...this probably isn't okay, especially because... main() is back down to leaking one refcount. so from this, we can deduce that main() is correctly releasing the refcount that it got on the object re
turned from dosomethingwithfooandre
turnittoo(), so the leak must be somewhere in that function. ...
...fooandre
turnittoo() leaks two refcounts. hmm...this probably isn't okay, especially because... main() is back down to leaking one refcount. so from this, we can deduce that main() is correctly releasing the refcount that it got on the object re
turned from dosomethingwithfooandre
turnittoo(), so the leak must be somewhere in that function. so now say we go fix the leak in dosomethingwithfooandre
turnittoo(), re-run our trace, grovel through the log by hand to find the object that corresponds to 0x00253ab0 in the new run, and run make-tree.pl. ...
...And 2 more matches
Nonblocking IO In NSPR
the file descriptor. creating a nonblocking socket only sockets can be made nonblocking. regular files always operate in blocking mode. this is not a serious constraint as one can assume that disk i/o never blocks. fundamentally, this constraint is due to the fact that nonblocking i/o and <tt>select()</tt> are only available to sockets on some platforms (e.g., winsock). in nspr, a new socket re
turned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</tt> is always created in blocking mode. one can make the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_non...
... 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 re
turned 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 re
turned 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. since <tt>pr_transmitfile()</tt> only operates in blocking mode, thi...
... from blocking io in nonblocking mode, the timeout argument for the io functions is ignored. <tt>pr_acceptread()</tt> and <tt>pr_transmitfile()</tt> only work on blocking sockets. they do not make sense in nonblocking mode. <tt>pr_write()</tt>, <tt>pr_send()</tt>, <tt>pr_writev()</tt> in blocking mode block until the entire buffer is sent. in nonblocking mode, they cannot block, so they may re
turn with just sending part of the buffer. pr_poll() or pr_select()? <tt>pr_select()</tt> is deprecated, now declared in <tt>private/pprio.h</tt>. use <tt>pr_poll()</tt> instead. the current implementation of <tt>pr_select()</tt> simply calls <tt>pr_poll()</tt>, so it is sure to have worse performance. also, native file descriptors (socket handles) cannot be added to <tt>pr_fd_set</tt>, i.e., the f...
...And 2 more matches
NSS Sample Code sample6
pt, you need the ciphertext and the id of the key that was used * to encrypt * * before running this example, create the nss database * certutil -n -d . * (enter "test" when prompted for password) */ #include "nss.h" #include "pk11pub.h" /* the key id can be any sequence of bytes. this example happens to use an * integer */ void genkey(int id); /* this callback is responsible for re
turning the password to the nss * key database. for example purposes, this function hardcodes the password. * in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; /* init...
... keyid[1]; ck_mechanism_type ciphermech; /* using ckm_aes_cbc_pad mechanism for example */ ciphermech = ckm_aes_cbc_pad; slot = pk11_getinternalkeyslot(); /* slot = pk11_getbestslot(ciphermech, null); didn't work. * error code: token is read-only. ?? */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); re
turn; } keyid[0] = id; keyiditem.type = sibuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* note: keysize must be 0 for fixed key-length algorithms like des. * since we're using aes in this example, we're specifying * one of the valid keysizes (16, 24, 32) */ key = pk11_tokenkeygen(slot, ciphermech, 0, 32 /*keysize*/, ...
...gth algorithms like des. ...
...And 2 more matches
PKCS #11 Module Specs
valid values are: configdir configuration directory where nss can store persistant state information (typically databases). secmod name of the secmod database (default = secmod.db). certprefix prefix for the cert database. keyprefix prefix for the key database. minpwlen minimum password length in bytes. manufacturerid override the default manufactureid value for the module re
turned in the ck_info, ck_slot_info, and ck_token_info structures with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropped). librarydescription override the default librarydescription value for the module re
turned in the ck_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, parti...
... truncated at 32 bytes (no null, partial utf8 characters dropped). librarydescription override the default librarydescription value for the module re
turned in the ck_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropped). cryptotokendescription override the default label value for the internal crypto token re
turned in the ck_token_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropped). dbtokendescription override the default label value for the internal db token re
turned in the ck_token_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropp...
... truncated at 32 bytes (no null, partial utf8 characters dropped). dbtokendescription override the default label value for the internal db token re
turned in the ck_token_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropped). fipstokendescription override the default label value for the internal fips token re
turned in the ck_token_info structure with an internationalize string (utf8). this value will be truncated at 32 bytes (no null, partial utf8 characters dropped). cryptoslotdescription override the default slotdescription value for the internal crypto token re
turned in the ck_slot_info structure with an internationalize string (utf8). this value will be truncated at 64 bytes (no null, partial utf8 ...
...And 2 more matches
NSS tools : modutil
ion number (pin). -chkfips verify whether the module is in the given fips mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, modutil re
turns an error message. -default modulename specify the security mechanisms for which the named module will be a default provider. the security mechanisms are specified with the -mechanisms argument. -delete modulename delete the named module. the default nss pkcs #11 module cannot be deleted. -disable modulename disable all slots on the named module. use the -slot argument to disable a spe...
...-------------------------------------------------------- 1. nss internal pkcs #11 module slots: 2 slots attached status: loaded slot: nss internal cryptographic services token: nss generic crypto services slot: nss user private key and certificate services token: nss certificate db ----------------------------------------------------------- passing a specific module name with the -list re
turns details information about the module itself, like supported cipher mechanisms, version numbers, serial numbers, and other information about the module and the token it is loaded on. for example: modutil -list "nss internal pkcs #11 module" -dbdir sql:/home/my/sharednssdb ----------------------------------------------------------- name: nss internal pkcs #11 module library file: **internal...
...(this information can be edited by loading new specs using the -rawadd command.) modutil -rawlist -dbdir sql:/home/my/sharednssdb name="nss internal pkcs #11 module" parameters="configdir=. certprefix= keyprefix= secmod=secmod.db flags=readonly " nss="trustorder=75 cipherorder=100 slotparams={0x00000001=[slotflags=rsa,rc4,rc2,des,...
...And 2 more matches
NSS tools : modutil
is in the given fips mode. true means to verify that the module is in fips mode, while false means to verify that the module is not in fips mode. -create create new certificate, key, and module databases. use the -dbdir directory argument to specify a directory. if any of these databases already exist in a specified directory, modutil re
turns an error message. -default modulename specify the security mechanisms for which the named module will be a default provider. the security mechanisms are specified with the -mechanisms argument. -delete modulename delete the named module. the default nss pkcs #11 module cannot be deleted. -disable modulename ...
... 1. nss internal pkcs #11 module slots: 2 slots attached status: loaded slot: nss internal cryptographic services token: nss generic crypto services slot: nss user private key and certificate services token: nss certificate db ----------------------------------------------------------- passing a specific module name with the -list re
turns details information about the module itself, like supported cipher mechanisms, version numbers, serial numbers, and other information about the module and the token it is loaded on. for example: modutil -list "nss internal pkcs #11 module" -dbdir sql:/home/my/sharednssdb ----------------------------------------------------------- name: nss internal pkcs #11 module library file: *...
...(this information can be edited by loading new specs using the -rawadd command.) modutil -rawlist -dbdir sql:/home/my/sharednssdb name="nss internal pkcs #11 module" parameters="configdir=. certprefix= keyprefix= secmod=secmod.db flags=readonly " nss="trustorder=75 cipherorder=100 slotparams={0x00000001=[slotflags=rsa,rc4,r...
...And 2 more matches
Pork Tools
outparamdel outparamdel converts functions to re
turn via re
turn value instead of an outparam. it takes a list of functions as input and rewrites the definition and call sites of those functions. <caption>rewrites performed</caption> nsresult getter(nsifoo **aresult) { *aresult = ... if (!*aresult) re
turn ns_error_failure; re
turn ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typically it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ... ...
... performed</caption> nsresult getter(nsifoo **aresult) { *aresult = ... if (!*aresult) re
turn ns_error_failure; re
turn ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typically it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ... ...
...sresult getter(nsifoo **aresult) { *aresult = ... if (!*aresult) re
turn ns_error_failure; re
turn ns_ok; } nsifoo* getter() { nsifoo *result = null; // aresult below is kept for complicated cases // typically it wont be needed and can be removed nsifoo **aresult = &result; // *aresult patterns are replaced with result result = ... ...
...And 2 more matches
Rhino shell
based on their urls according to java policy settings. this is available only if jvm implements java2 security model. predefined properties scripts executing in the shell have access to some additional properties of the top-level object. arguments the arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked. environment re
turns the current environment object. history displays the shell command history. help() executing the help function will print usage and help messages. defineclass(classname) define an extension using the java class named with the string argument classname. uses scriptableobject.defineclass() to define the extension. deserialize(filename) restore from the specified file an object previously w...
...ss named with the string argument classname. uses scriptableobject.defineclass() to define the extension. deserialize(filename) restore from the specified file an object previously written by a call to serialize. gc() runs the garbage collector. load([filename, ...]) load javascript source files named by string arguments. if multiple arguments are given, each file is read in and executed in
turn. loadclass(classname) load and execute the class named by the string argument classname. the class must be a class that implements the script interface, as will any script compiled by rhino javascript compiler. print([expr ...]) evaluate and print expressions. evaluates each expression, converts the result to a string, and prints it. readfile(path [, charactercoding]) read given file and co...
...ent is not given. readurl(url [, charactercoding]) open an input connection to the given string url, read all its bytes and convert them to a string using the specified character coding or default character coding if explicit coding argument is not given. runcommand(commandname, [arg, ...] [options]) execute the specified command with the given argument and options as a separate process and re
turn the exit status of the process. usage: runcommand(command) runcommand(command, arg1, ..., argn) runcommand(command, arg1, ..., argn, options) all except the last arguments to runcommand are converted to strings and denote command name and its arguments. if the last argument is a javascript object, it is an option object. otherwise it is converted to string denoting the last argument and optio...
...And 2 more matches
Exact Stack Rooting
" approach. a js::handlet is a pointer to a js::rootedt. a js::rootedt will automatically convert to a js::handlet. by using js::handlet in the interface instead of direct gcpointers, we ensure that the gcthing is already rooted on some previous stack frame, freeing us from having to worry about rooting the gcthing for the duration of the call. bool hello(jscontext *cx, handleobject foo) { re
turn hello(cx, foo); } ..... void otherfunction(jscontext *cx) { ... rootedobject obj(cx, ...); hello(cx, obj); ... } a secondary benefit: since all js functions take js::handlets, code that does not root cstack gcpointers correctly will be much less likely to compile. warning: js::handlet does not root objects itself! that is the job of js::rootedt. warning: never give a funct...
........ void otherfunction(jscontext *cx) { ... rootedobject obj(cx, ...); hello(cx, obj); ... } a secondary benefit: since all js functions take js::handlets, code that does not root cstack gcpointers correctly will be much less likely to compile. warning: js::handlet does not root objects itself! that is the job of js::rootedt. warning: never give a function a js::handlet re
turn type: this can easily lead to a js::handlet outliving its js::rootedt's lifetime. js::mutablehandle<t> typedef js::mutablehandle<t> js::mutablehandlet; -> mutablehandleobject, mutablehandlestring, etc. the purpose of js::mutablehandlet is to allow out-parameters for rooted gcthings. this class solves two problems: c++ only allows one level of user-defined implicit type conversion. when pa...
...his makes js::handlet and js::rootedt behave the same, allowing us to seamlessly weave js::handlets into the js api. the problem is that this requires us to overload operator->. if we have a method taking handle<value>*, then out->setobject(foo) will not work as expected. to solve these problems we have the js::mutablehandlet class. js::mutablehandlet is a js::handlet with a set method. bool re
turnfoo(jscontext *cx, mutablehandlestring out) { out.set(js_newstringcopyz(cx, "foo")); re
turn bool(out); } size_t getlengthfoo(jscontext *cx) { rootedstring s(cx); if (re
turnfoo(cx, &s)) re
turn js_getstringlength(s); re
turn size_t(-1); } all methods in the js-api that re
turn gcpointers have been changed to this out-param style. this prevents an entire class of bugs whe...
...And 2 more matches
Tracing JIT
ted pages and guardrecords allocated from the fragment's owning fragmento. a fragment initially holds no pages. as the compilation pipeline inserts lir instructions (lins values) into the fragment, it allocates pages to store the lir code. later, when the fragment is assembled, it will allocate pages for the native code (nins values) produced by the assembler. when the fragment is destroyed, it re
turns its pages to the fragmento for reuse. nanojit/assembler.* the nanojit/assembler.cpp and nanojit/assembler.h files define the class assembler, which transforms lins values into nins values. in other words, an assembler transforms lir code into native code. an assembler is also able to modify existing fragments of native code, by rewriting native jump instructions to jump to new locations. in th...
...ntinues interpreting bytecode, but with an important difference: each bytecode it interprets is also sent to the trace monitor and recorded in the monitor's trace recorder. recording mode is temporary -- ideally it only lasts as long as it takes to record a single iteration of a loop in the interpreter -- and can end in a number of ways. all transitions out of recording mode eventually involve re
turning to monitoring mode: if the recorder is asked to record a bytecode that it cannot, for various low-level reasons, faithfully record, the recorder may choose to abort the recording. aborting a recording is always an option in tracemonkey, and on abort the monitor simply discards the recorder and its fragment and re
turns to monitoring mode. the monitor also keeps track of how many times it has...
... pc and will not attempt recording it any longer. if the recorder completes recording at a backward branch back to the initial pc value that triggered recording mode, it is said to have successfully closed the loop. a closed loop is passed through the nanojit assembler and thereby compiled to native machine code. the associated fragment is placed in the monitor's fragment table and the monitor re
turns to monitoring mode, with a high likelihood of immediately transitioning to executing mode on the next bytecode interpreted. the compiled fragment of code re
turned to the monitor on successful loop-close is called a trace. if the recorder is asked to record a bytecode that implies a call to a native function elsewhere in spidermonkey -- some helper function written in c -- and that native happen...
...And 2 more matches
JS_EncodeCharacters
mber of bytes written to dst before the error occurred. description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. ...
...f8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is
turned on, the length of the encoded string may vary. to calculate the number of bytes needed, call js_encodecharacters twice, like this: /* determine how many bytes to allocate. */ size_t dstlen = 0; if (!js_encodecharacters(cx, src, srclen, null, &dstlen)) re
turn js_false; /* allocate. */ char *dst = (char *) js_malloc(cx, dstlen); if (dst == null) re
turn js_false; /* convert characters to bytes. */ js_encodecharacters(cx, src, srclen, dst, &dstlen); /* use the converted bytes for something. */ ... ...
... this happens if the destination is too small for the resulting string or if the source buffer isn't proper utf-16 because it contains unpaired surrogate values. ...
...And 2 more matches
JS_GetFunctionId
get a function's name as a jsstring. syntax jsstring * js_getfunctionid(jsfunction *fun); jsstring * js_getfunctiondisplayid(jsfunction *fun); // added in spidermonkey 17 name type description fun jsfunction * a javascript function. description js_getfunctionid re
turns the name of a function, fun, as a jsstring, or null if fun is unnamed. the re
turned string lives as long as fun, so you don't need to root a saved reference to it if fun is well-connected or rooted, and provided you bound the use of the saved reference by fun's lifetime. js_getfunctiondisplayid re
turns the display name of a function, fun. this is the defined name if one was given where the function was defined, or it could be an inferred name by the js engine in the case that t...
... saved reference to it if fun is well-connected or rooted, and provided you bound the use of the saved reference by fun's lifetime. js_getfunctiondisplayid re
turns the display name of a function, fun. this is the defined name if one was given where the function was defined, or it could be an inferred name by the js engine in the case that the function was defined to be anonymous. this can still re
turn nullptr if a useful display name could not be inferred. the same restrictions on rooting as those in js_getfunctionid apply. examples the name re
turned by js_getfunctiondisplayid is the same as re
turned by js_getfunctionid if the function explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source. if no smart name...
...rred. the same restrictions on rooting as those in js_getfunctionid apply. examples the name re
turned by js_getfunctiondisplayid is the same as re
turned by js_getfunctionid if the function explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source. if no smart name could be guessed for the function, then null is re
turned. the re
turned string is guaranteed to live as long as fun, so the application often does not need to root the string. ...
...And 2 more matches
JS_SetBranchCallback
replaced with js_setoperationcallback. ...
...quest. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). script jsscript the script that is running. this is guaranteed to be non-null, unless the jsoption_native_branch_callback option has been enabled for the context cx using js_setoptions(). ...
...ot need to call js_beginrequest()). script jsscript the script that is running. this is guaranteed to be non-null, unless the jsoption_native_branch_callback option has been enabled for the context cx using js_setoptions(). if the callback re
turns js_true, the js engine continues to execute the script. if the callback raises an exception using js_setpendingexception() and re
turns js_false, then the javascript engine propagates the exception to the script that was executing at the time. if the callback re
turns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error. the engine does not execute finally blocks in this case; this is the same behavior as any native method or callback. description js_s...
...And 2 more matches
JS_SetOptions
previously set options. syntax uint32 js_setoptions(jscontext *cx, uint32 options); name type description cx jscontext * a context on which to set options. options uint32 the new set of options. this is the logical or of zero or more flags described below. description js_setoptions sets the option flags of a given js context cx. ...
...int32 options); name type description cx jscontext * a context on which to set options. options uint32 the new set of options. this is the logical or of zero or more flags described below. description js_setoptions sets the option flags of a given js context cx. this function re
turns a uint32 value containing the previous values of the flags. ...
...xt * a context on which to set options. options uint32 the new set of options. this is the logical or of zero or more flags described below. description js_setoptions sets the option flags of a given js context cx. this function re
turns a uint32 value containing the previous values of the flags. ...
...And 2 more matches
Split object
outer objects implement the jsextendedclass.innerobject hook. but the association is not fixed. an outer object may be associated with different inner objects at different times. this feature is complicated. ...
...dow object for tab tb must persist as the user navigates from page to page in that tab. to the script in page a, the window must appear to be a single object that moves from page to page. but each web page must load with fresh globals. (the problem is even a bit subtler than this, since the reference may be direct or indirect. the script in a might have opened tb by calling window.open, which re
turns a direct reference to tb's window. more indirectly, suppose there's a javascript function defined in page b that refers to global variables in page b. if page a gets a reference to that function, then by calling it, it is indirectly accessing tab tb's window. the function object carries a reference to the window, via the scope chain. to further complicate matters, a and b are in the same securit...
...mment about fixing some kind of interaction between with an split objects. write that down, it'll be on the test.) split objects were the solution. the inner window object is different for each page a browser window visits. it serves as the "globals" object and provides the jsprincipals for scripts on that page. access to inner window properties is fast. the outer window object is the object re
turned by window.open. it represents the window or tab itself and survives as the user navigates in that window or tab. the window object's jsclass.resolve hook ensures that properties of the inner object are visible via the outer object, if the running code has the right principals to access them. this privilege check may be slow. see wikimo:gecko:splitwindow and bug 296639 for more discussion. see a...
...And 2 more matches
Using the Places annotation service
you can use the annotations service's hasannotation method to determine in advance if the page has the requested annotation. however, it is more efficient to just try to do the operation and catch the exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know ...
...s hasannotation method to determine in advance if the page has the requested annotation. however, it is more efficient to just try to do the operation and catch the exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know if the exception meant that the annotation did not exist or something else is broken. the getter functions re
turn only the value of the annotation (with the exception of the c++ getpageannotationbinary and getitemannotationbinary methods which re
turn the mimetype as well). four functions are provided to get this information: getpageannotationinfo(auri, aname, aflags, aexpiration, amimetype, atype) getitemannotationinfo(aitemid, aname, aflags, aexpiration, amimetype, atype) getpageannotationtype(auri, an...
...of the c++ getpageannotationbinary and getitemannotationbinary methods which re
turn the mimetype as well). ...
...And 2 more matches
Setting up the Gecko SDK
next is the module code, this code is the entry point into your dll/component. #include "nsi...
... next is the module code, this code is the entry point into your dll/component. #include "nsigenericfactory.h" #include "cspecialthing.h" ns_generic_factory_constructor(cspecialthing) static nsmodulec...
... next is the module code, this code is the entry point into your dll/component. ...
...And 2 more matches
Using XPCOM Components
in the source code you view in mxr, interfaces that have been frozen are marked at the top with @status frozen. the xpcom component viewer the xpcom component viewer is an add-on you can install in your browser (in sandbox, not available for now). alternatively, you can try xpcomviewer, a similar add-on. xpcom component viewer the left column shows the components - in this case a subset re
turned from a search on "gfx" as part of the contract id and the right column a list of the interfaces. when you open a component on the left, you can see the interfaces it implements along with a list of the methods provided by each interface. the xpcom component viewer can be extremely useful for this sort of gross interrogation, but again: it displays all of the components and interfaces in your b...
... easy to acecss xpcom components as javascript objects, but using xpcom components in c++ is not much more difficult. managing cookies from cpp duplicates code from getting the cookiemanager component in javascript, but in c++ instead of javascript. ...
...i added |pr_false| as a fourth para...
...And 2 more matches
Components.lastResult
in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. ...
... in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. ...
...he numeric nsresult code that was the result code of the last xpcom method called via xpconnect. introduction generally, components.lastresult is only useful for testing the result of xpcom methods that can re
turn interesting 'success' codes. this is because failure result codes get converted by xpconnect into exceptions that are thrown into the calling javascript method. most interfaces only re
turn one success code -- ns_ok -- so components.lastresult is rarely necessary. in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. this is because many 'components' properties and methods are themselves implemented using xpconnect a...
...And 2 more matches
NS_GetComponentManager
the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...And 2 more matches
NS_GetComponentRegistrar
the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...And 2 more matches
NS_GetMemoryManager
the interface pointer should be release'd when it is no longer needed. ...
...the interface pointer should be release'd when it is no longer needed. ...
...the interface pointer should be release'd when it is no longer needed. ...
...And 2 more matches
NS_GetServiceManager
the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. ...
...And 2 more matches
IAccessibleHypertext
documents. a typical implementation is to implement this interface on the smallest text object such as a paragraph of text. method overview [propget] hresult hyperlink([in] long index, [out] iaccessiblehyperlink hyperlink ); [propget] hresult hyperlinkindex([in] long charindex, [out] long hyperlinkindex ); [propget] hresult nhyperlinks([out] long hyperlinkcount ); methods hyperlink() re
turns the specified link. the re
turned iaccessiblehyperlink object encapsulates the hyperlink and provides several kinds of information describing it. [propget] hresult hyperlink( [in] long index, [out] iaccessiblehyperlink hyperlink ); parameters index this 0 based index specifies the hyperlink to re
turn. hyperlink if the given index is valid, that is it lies in the interval from 0 to the numbe...
...es the hyperlink and provides several kinds of information describing it. [propget] hresult hyperlink( [in] long index, [out] iaccessiblehyperlink hyperlink ); parameters index this 0 based index specifies the hyperlink to re
turn. hyperlink if the given index is valid, that is it lies in the interval from 0 to the number of links minus one, a reference to the specified hyperlink object is re
turned. if the index is invalid then a null pointer is re
turned. re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_ok. hyperlinkindex() re
turns the index of the hyperlink that is associated with this character index. this is the case when a link spans the given character index. [propget] hresult hyperlinkindex( [in] long charindex, [out] long hyperlinkindex ); parameters char...
...urned. re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_ok. hyperlinkindex() re
turns the index of the hyperlink that is associated with this character index. this is the case when a link spans the given character index. [propget] hresult hyperlinkindex( [in] long charindex, [out] long hyperlinkindex ); parameters charindex a 0 based index of the character for which to re
turn the link index. if iaccessibletext is used to represent the text containing the link, then the character index is only valid if it is greater than or equal to zero and lower than the number of characters in the text. hyperlinkindex the 0 based index of the hyperlink that is associated with this character index, or -1 if charindex is not on a link. ...
...And 2 more matches
mozIStorageService
n nsifile adatabasefile); methods backupdatabasefile() this method makes a backup of the specified file. the database should not be open, or you should ensure that no database activity is happening when you call this method. the filename provided is only used as a suggestion. if the filename is already taken, attempts will be made to ensure that it is unique. the actual backup file is re
turned, and the resulting filename can be obtained from that. nsifile backupdatabasefile( in nsifile adbfile, in astring abackupfilename, in nsifile abackupparentdirectory optional ); parameters adbfile the database file to back up. abackupfilename the filename to give to the new backup file. abackupparentdirectory optional the directory to put the bac...
...le, in astring abackupfilename, in nsifile abackupparentdirectory optional ); parameters adbfile the database file to back up. abackupfilename the filename to give to the new backup file. abackupparentdirectory optional the directory to put the backup into. if this is not specified, the backup is placed in the same directory as the original file. re
turn value an nsifile object representing the newly-created backup file. opendatabase() opens a database connection to the specified file. the specified file is created if it does not already exist. if this method throws ns_error_file_corrupted, it's recommended that you call mozistorageservice.backupdatabasefile() to back up the database so that user data is not lost (although we have no way of recov...
...rupt your database. if your database contains virtual tables (for example, for full-text indexes), you must use mozistorageservice.openunshareddatabase() to open it, since those tables are not compatible with a shared cache. if you use this method to open a database containing virtual tables, it will think the database is corrupted and throw ns_error_file_corrupted. note: the connection object re
turned by this function is not threadsafe. you must use it only from the thread you created it from. mozistorageconnection opendatabase( in nsifile adatabasefile ); parameters adatabasefile an nsifile indicating the database file to open. re
turn value a mozistorageconnection representing the connection to the opened database file. exceptions thrown ns_error_failure an...
...And 2 more matches
mozITXTToHTMLConv
hyperlinks for urls in the text. methods scantxt() scans the specified text, applying the requested conversions and outputting html. wstring scantxt( in wstring text, in unsigned long whattodo ); parameters text the original, plain text to scan and convert into html. whattodo a bit field composed of the conversion control attributes indicating what conversions to apply. re
turn value the html version of the specified string. scanhtml() scans the specified user-edited html, adding additional formatting that the user may not have known to do. this should correct html that isn't entirely standards-compliant. warning: don't use the kglyphsubstitution conversion type with this method, as doing so generates html that is non-standard. wstring scanhtml( in wstring text, ...
...hat isn't entirely standards-compliant. warning: don't use the kglyphsubstitution conversion type with this method, as doing so generates html that is non-standard. wstring scanhtml( in wstring text, in unsigned long whattodo ); parameters text the original, user-edited html. whattodo a bit field composed of the conversion control attributes indicating what conversions to apply. re
turn value a normalized version of the original html string. citeleveltxt() re
turns the "cite level" of the specified text; that is, it indicates how many levels of email reply quotes are used, when the text uses "quote" characters (such as ">") at the beginning of the line to indicate cite levels. unsigned long citeleveltxt( in wstring line, out unsigned long loglinestart ); parameters l...
...ndicate cite levels. unsigned long citeleveltxt( in wstring line, out unsigned long loglinestart ); parameters line the original line of text, which may begin with one or more cite characters such as ">". loglinestart on output, this parameter is set to indicate the offset into the string of the first non-cite character. you must set this value to zero before calling this method. re
turn value the cite level of the quote; that is, the number of text quote characters found at the beginning of the string. findurlinplaintext() re
turns the start and end offsets of the first url found in a substring. void findurlinplaintext( in wstring text, in long alength, in long apos, out long astartpos, out long aendpos ); parameters text the string to scan for the presence of...
...And 2 more matches
GetChildAt
exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
...exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
...exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
...And 2 more matches
nsIAutoCompleteInput
showimagecolumn boolean if true, a column is added to the popup, showing an additional image for each autocomplete result. textvalue astring the value of the text in the autocomplete text field. timeout unsigned long the number of milliseconds after a keystroke before a search begins. methods getsearchat() re
turns the name of one of the autocomplete search session objects. acstring getsearchat( in unsigned long index ); parameters index the index number of the search session object whose name is to be re
turned. re
turn value the name of the specified object. onsearchbegin() called when the search starts. void onsearchbegin(); parameters none. onsearchcomplete() called when the search en...
...selecttextrange() selects a range of text in the autocomplete text field. ...
...selecttextrange() selects a range of text in the autocomplete text field. ...
...And 2 more matches
nsICacheEntryDescriptor
d doomandfailpendingrequests( in nsresult status ); parameters status the access status. getmetadataelement() this method retrieves the meta data. meta data is a table of key/value string pairs. the strings do not have to conform to any particular charset, but they must be null terminated. string getmetadataelement( in string key ); parameters key the key for retrieving the meta data. re
turn value re
turns 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...
...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 re
turned 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. re
turn value re
turns blocking, unbuffered input stream. openoutputstream() this method opens blocking output stream to cache data. this will fail if the ca...
...ting from this offset into the cached data. an offset beyond the end of the stream has undefined consequences. re
turn value re
turns 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 re
turned 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. ...
...And 2 more matches
nsICacheService
ssions. entries created by a cache session are invisible to other cache sessions, unless the cache sessions are equivalent. nsicachesession createsession( in string clientid, in nscachestoragepolicy storagepolicy, in boolean streambased ); parameters clientid specifies the name of the client using the cache. ...
...t. nsicachesession createsession( in string clientid, in nscachestoragepolicy storagepolicy, in boolean streambased ); parameters clientid specifies the name of the client using the cache. storagepolicy limits the storage policy for all entries accessed via the re
turned session. as a result, devices excluded by the storage policy will not be searched when opening entries from the re
turned session. streambased indicates whether or not the data being cached can be represented as a stream. the storagepolicy must be consistent with the value of this field. for example, a non-stream-based cache entry can only have a storage policy of store_in_memory. re
turn value re
turns a new cache session. createtemporaryclientid() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3...
...ased cache entry can only have a storage policy of store_in_memory. re
turn value re
turns a new cache session. createtemporaryclientid() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)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. this method creates and re
turns a unique, temporary cache client id. this is used by the offline cache. the offline cache lets clients accumulate entries in a temporary client and merge them in as a group using nsiofflinecachesession.mergetemporaryclient(). ...
...And 2 more matches
nsIComponentRegistrar
e called from the main thread. void autounregister( in nsifile aspec ); parameters aspec this parameter indicates either a component file to be unregistered or a directory containing component files to be unregistered. if aspec is null, then the application component's directory as defined by ns_xpcom_component_dir will be unregistered. see nsdirectoryservice. cidtocontractid() this method re
turns the contractid corresponding to a given classid. string cidtocontractid( in nscidref aclass ); parameters aclass the classid to be queried. re
turn value the contractid corresponding to aclassid if one exists and is registered. contractidtocid() re
turns the classid for a given contractid, if one exists and is registered. nscidptr contractidtocid( in string acontractid ); parameters acont...
...n classid. string cidtocontractid( in nscidref aclass ); parameters aclass the classid to be queried. re
turn value the contractid corresponding to aclassid if one exists and is registered. contractidtocid() re
turns the classid for a given contractid, if one exists and is registered. nscidptr contractidtocid( in string acontractid ); parameters acontractid the contractid to be queried. re
turn value the classid corresponding to acontractid if one exists and is registered. enumeratecids() this method re
turns an enumerator over the list of registered classids. elements of the enumeration can be queryinterfaced for the nsisupportsid interface. ...
...elements of the enumeration can be queryinterfaced for the nsisupportscstring interface. ...
...And 2 more matches
nsIContentPrefService
ges. void addobserver( in astring aname, in nsicontentprefobserver aobserver ); parameters aname the name of the preference to observe. you may specify null to add a generic observer that is notified of all preference changes. aobserver the name of an object implementing nsicontentprefobserver that will receive notifications of changes to the preference's value. getpref() re
turns the value of a preference saved for a particular site. note: prior to gecko 2.0, the site could only be specified by nsiuri. now a string can be used as well. nsivariant getpref( in nsivariant agroup, in astring aname, in nsicontentprefcallback acallback optional ); parameters agroup the group for which to retrieve a preference; this may be specified as either a uri or as a st...
...s matching the hostname portion of the specified uri. specify null to get the preference from the global preference space; those preferences apply to all sites. aname the name of the preference whose value is to be retrieved. acallback an optional nsicontentprefcallback to receive the result. if desired, javascript callers can instead provide a function to call upon completion. re
turn value the preference's value is re
turned; this value may be a string, integer, boolean, or any other value. the result may be null (nsidatatype:vtype_empty) if the preference's value is either null, or undefined (nsidatatype:vtype_void) if there is no saved preference by the specified name. exceptions thrown ns_error_illegal_value if agroup is not a string, nsiuri, or null. or if aname i...
...ell. nsipropertybag2 getprefs( in nsivariant agroup ); parameters agroup the group whose preferences are to be retrieved; this may be specified as either a uri or as a string; in either case, the group consists of all sites matching the hostname portion of the specified uri. specify null to get the preferences from the global preference space; those preferences apply to all sites. ...
...And 2 more matches
nsIContentPrefService2
d once for each preference. if no such preferences exist, handleresult is not called at all. getcachedbydomainandname() synchronously retrieves from the in-memory cache the preference with the given domain and name. in addition to caching preference values, the cache also keeps track of preferences that are known not to exist. if the preference is known not to exist, the value attribute of the re
turned object will be undefined (nsidatatype.vtype_void()). if the preference is neither cached nor known not to exist, then null is re
turned, and get() must be called to determine whether the preference exists. nsicontentpref getcachedbydomainandname( in astring domain, in astring name, in nsiloadcontext context ); parameters domain the preference's domain. name th...
... cached nor known not to exist, then null is re
turned, and get() must be called to determine whether the preference exists. nsicontentpref getcachedbydomainandname( in astring domain, in astring name, in nsiloadcontext context ); parameters domain the preference's domain. name the preference's name. context the private-browsing context, if any. re
turn value the preference, or null if no such preference is known to exist. getcachedbysubdomainandname() synchronously retrieves from the in-memory cache all preferences with the given name whose domains are either the same as or subdomains of the given domain. the preferences are re
turned in an array through the out-parameter. if a preference for a particular subdomain is known not to exist, then an...
... be undefined. void getcachedbysubdomainandname( in astring domain, in astring name, in nsiloadcontext context, out unsigned long len, [retval,array,size_is(len)] out nsicontentpref prefs ); parameters domain the preferences' domain. name the preferences' name. context the private-browsing context, if any. ...
...And 2 more matches
nsIControllers
d long index); attributes attribute type description commanddispatcher nsidomxulcommanddispatcher obsolete since gecko 1.9 methods appendcontroller() adds a controller to the end of the list. void appendcontroller( in nsicontroller controller ); parameters controller a controller to be added to the list of controllers. exceptions thrown ns_error_out_of_memory getcontrollerat() re
turns the controller instance at the given position. nsicontroller getcontrollerat( in unsigned long index ); parameters index the position of the wanted controller. re
turn value the controller at the given position. exceptions thrown ns_error_failure the given index is out of range. getcontrollerbyid() re
turns a controller given by its order, rather than position, of insertion. nsicontroller g...
...ex the position of the wanted controller. re
turn value the controller at the given position. exceptions thrown ns_error_failure the given index is out of range. getcontrollerbyid() re
turns a controller given by its order, rather than position, of insertion. nsicontroller getcontrollerbyid( in unsigned long controllerid ); parameters controllerid the id (insertion order) of a controller. re
turn value the controller element that was inserted with that id. exceptions thrown ns_error_failure the id is greater than the number of controllers that have been inserted, or the controller has since been removed. getcontrollercount() re
turns the current number of controllers. unsigned long getcontrollercount(); parameters none. ...
...s controllerid the id (insertion order) of a controller. re
turn value the controller element that was inserted with that id. exceptions thrown ns_error_failure the id is greater than the number of controllers that have been inserted, or the controller has since been removed. getcontrollercount() re
turns the current number of controllers. unsigned long getcontrollercount(); parameters none. re
turn value the number of controllers currently in the list of controllers. getcontrollerforcommand() searches for a controller that supports the given command. nsicontroller getcontrollerforcommand( in string command ); parameters command the name of a command, e.g. ...
...And 2 more matches
nsICookieManager2
the cookie data. aissecure true if the cookie should only be sent over a secure connection. aishttponly true if the cookie should only be sent to, and can only be modified by, an http connection. aissession true if the cookie should exist for the current session only. aexpiry holds the expiration date, in seconds since the epoch. only relevant if aissession is false. cookieexists() re
turns whether or not a matching cookie already exists. boolean cookieexists( in nsicookie2 acookie ); parameters acookie the cookie to look for. re
turn value re
turns true if a cookie was found which matches the host, path, and name fields of acookie. countcookiesfromhost() re
turns the number of cookies that would be re
turned to a given host. this ignores the cookie flags isdomain, issec...
...omain cookies for "weather.yahoo.com" and "yahoo.com" would both be counted, while a cookie for "my.weather.yahoo.com" would not. unsigned long countcookiesfromhost( in autf8string ahost ); parameters ahost the host string to look for, such as "google.com". this should consist only of the host portion of the uri and should not contain a leading dot, port number, or other information. re
turn value the number of matching cookies found. findmatchingcookie() obsolete since gecko 1.9 (firefox 3) find whether a matching cookie already exists, and how many cookies a given host has already set. this is useful when e.g. prompting the user whether to accept a given cookie. boolean findmatchingcookie( in nsicookie2 acookie, out unsigned long acountfromhost ); ...
...xists, and how many cookies a given host has already set. this is useful when e.g. prompting the user whether to accept a given cookie. boolean findmatchingcookie( in nsicookie2 acookie, out unsigned long acountfromhost ); parameters acookie the cookie to look for. acountfromhost the number of cookies found whose hosts are the same as, or subdomains of, the host field of acookie. ...
...And 2 more matches
nsIDownloadManager
hether or not there are downloads that can be cleaned up (removed) that is downloads that have completed, have failed or have been canceled. read only. datasource nsirdfdatasource read only. obsolete since gecko 1.8 dbconnection mozistorageconnection the database connection to the downloads database. read only. defaultdownloadsdirectory nsilocalfile re
turns the platform default downloads directory. read only. listener nsidownloadprogresslistener the download manager's progress listener. obsolete since gecko 1.8 userdownloadsdirectory nsilocalfile re
turns the user configured downloads directory. the path is dependent on two user configurable prefs set in preferences: browser.download.folderlist defines the de...
... "generic file download" according to the .idl file. methods adddownload() creates an nsidownload and adds it to the list of activities being managed by the download manager. note: adding a download doesn't automatically begin the transfer. if you want to both add and start a download, you need to create an nsiwebbrowserpersist object, call this method, set the progresslistener to the re
turned 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 re
turned, 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, ...
...t equal to the target file). the file will be moved to the location indicated by atarget when the download is complete. this may be null. acancelable an object that can be used to abort the download. must not be null. aisprivate indicates whether this download should be considered private (ie. to be removed at the end of the private browsing session, cached in non-permanent storage, etc.) re
turn value the newly created download item with the passed-in properties. addlistener() adds a listener to the download manager. void addlistener( in nsidownloadprogresslistener alistener ); parameters alistener the nsidownloadprogresslistener object to receive status information from the download manager. canceldownload() cancels the download with the specified id if it's currently in-...
...And 2 more matches
nsIEnvironment
ame); boolean exists(in astring aname); methods set() set the value of an environment variable. void set( in astring aname, in astring avalue ); parameters aname the variable name to set. avalue the value to set. get() get the value of an environment variable. astring get( in astring aname ); parameters aname the variable name to retrieve. re
turn value re
turns the value of the env variable. an empty string will be re
turned when the env variable does not exist or when the value itself is an empty string - please use exists() to probe whether the env variable exists or not. exists() check the existence of an environment variable. this method checks whether an environment variable is present in the environment or not. note: * for unix/linux ...
...env variable does not exist or when the value itself is an empty string - please use exists() to probe whether the env variable exists or not. exists() check the existence of an environment variable. this method checks whether an environment variable is present in the environment or not. ...
...e use exists() to probe whether the env variable exists or not. exists() check the existence of an environment variable. this method checks whether an environment variable is present in the environment or not. note: * for unix/linux platforms we follow the unix definition: an environment variable exists when getenv() re
turns a non-null value. an environment variable does not exist when getenv() re
turns null. for non-unix/linux platforms we have to fall back to a "portable" definition (which is incorrect for unix/linux!!!!) which simply checks whether the string re
turned by get() is empty or not. boolean exists( in astring aname ); parameters aname the variable name to probe. re
turn value if the variable has been set, the value re
turned is pr_true. if the variable was not def...
...And 2 more matches
nsIFileProtocolHandler
ecfromfile(in nsifile file); nsiuri newfileuri(in nsifile afile); nsiuri readurlfile(in nsifile file); methods getfilefromurlspec() converts the url string into the corresponding nsifile if possible. a local file will be created if the url string begins with file://. nsifile getfilefromurlspec( in autf8string url ); parameters url the url string to convert. re
turn value a reference to a new nsifile object. geturlspecfromactualfile() converts the nsifile to the corresponding url string. should only be called on files which are not directories. otherwise identical to geturlspecfromfile(), but is usually more efficient. warning: this restriction may not be enforced at runtime! autf8string geturlspecfromactualfile( in nsifile file ); parameters file...
...ile object. geturlspecfromactualfile() converts the nsifile to the corresponding url string. should only be called on files which are not directories. otherwise identical to geturlspecfromfile(), but is usually more efficient. warning: this restriction may not be enforced at runtime! autf8string geturlspecfromactualfile( in nsifile file ); parameters file the nsifile to convert. re
turn value corresponding url string. the resulting string may contain url-escaped characters. geturlspecfromdir() converts the nsifile to the corresponding url string. should only be called on files which are directories. otherwise identical to geturlspecfromfile(), but is usually more efficient. warning: this restriction may not be enforced at runtime! autf8string geturlspecfromdir( in nsifile file...
... contain url-escaped characters. geturlspecfromdir() converts the nsifile to the corresponding url string. should only be called on files which are directories. otherwise identical to geturlspecfromfile(), but is usually more efficient. warning: this restriction may not be enforced at runtime! autf8string geturlspecfromdir( in nsifile file ); parameters file the nsifile to convert. re
turn value corresponding url string. the resulting string may contain url-escaped characters. geturlspecfromfile() converts the nsifile to the corresponding url string. if the nsifile is a local file, then the result will be a file:// url string. the resulting string may contain url-escaped characters. note: under some platforms this is a lossy conversion. note: callers should use geturlspecfromactu...
...And 2 more matches
nsIFocusManager
ot changed. updating the widget focus state is the responsibility of the caller. void focusplugin( in nsicontent aplugin ); parameters aplugin getfocusedelementforwindow() nsidomelement getfocusedelementforwindow( in nsidomwindow awindow, in prbool adeep, out nsidomwindow afocusedwindow ); parameters awindow if equal to the current value of focusedwindow, then the re
turned element will be the application-wide focused element (the value of focusedelement). the re
turn value will be null if no element is focused. adeep if true, then child frames are traversed and the re
turn value may be the element within a child descendant window that is focused. if false, then the re
turn value will be the frame element if the focus is in a child frame. afocusedwindow ...
... if true, then child frames are traversed and the re
turn value may be the element within a child descendant window that is focused. if false, then the re
turn value will be the frame element if the focus is in a child frame. afocusedwindow will be set to the currently focused descendant window of awindow, or to awindow if adeep is false. this will be set even if no element is focused. re
turn value the currently focused element within awindow. exceptions thrown ns_error_invalid_arg if awindow is null. getlastfocusmethod() pruint32 getlastfocusmethod( in nsidomwindow window ); parameters window if null, then the current focusedwindow will be used by default. ...
...this will either be 0, flag_bymouse or flag_bykey. movecarettofocus() moves the selection caret within awindow to the current focus. void movecarettofocus( in nsidomwindow awindow ); parameters awindow elementisfocusable() check if given element is focusable. ...
...And 2 more matches
nsIIDNService
converttodisplayidn() nor...
...converttodisplayidn() normalizes a hostname into utf-8 format if the hostname is in the idn whitelist. if the hostname isn't in the whitelist, it's converted into ace format. ...
...tf-8 format if the hostname is in the idn whitelist. if the hostname isn't in the whitelist, it's converted into ace format. the resulting string is useful for display purposes, and ensures that the encoding is consistent with nsiuri.gethost(). autf8string converttodisplayidn( in autf8string input, out boolean isascii ); parameters input the string to convert to display format. ...
...And 2 more matches
nsIINIParser
seamonkey 1.0) typically, you'll create an nsiiniparser object by calling nsiiniparserfactory.createiniparser(). also, if you need to write to an ini file, use nsiiniparserwriter. ...
...tf8stringenumerator getsections(); autf8string getstring(in autf8string asection, in autf8string akey); methods getkeys() re
turns an nsiutf8stringenumerator providing the keys available within the specified section of the ini file. nsiutf8stringenumerator getkeys( in autf8string asection ); parameters asection the name of the section whose keys you wish to enumerate. re
turn value an nsiutf8stringenumerator object that can be used to access the section's keys. getsections() re
turns an nsiutf8stringenumerator providing a list of the sections available within the ini file. nsiutf8stringenumerator getsections(); parameters none. ...
...erator getkeys( in autf8string asection ); parameters asection the name of the section whose keys you wish to enumerate. re
turn value an nsiutf8stringenumerator object that can be used to access the section's keys. getsections() re
turns an nsiutf8stringenumerator providing a list of the sections available within the ini file. nsiutf8stringenumerator getsections(); parameters none. re
turn value an nsiutf8stringenumerator object that can be used to access the sections in the ini file. getstring() re
turns the string value for the specified key within a particular section of the ini file. autf8string getstring( in autf8string asection, in autf8string akey ); parameters asection the section containing the key whose value is to be re
turned. akey the key for which ...
...And 2 more matches
nsIJumpListBuilder
. user may also pin items to jump lists, which take up additional slots. applications do not have control over the number of items allowed in jump lists; excess items added are dropped by the system. item insertion priority is defined as first to last added. users may remove items from jump lists after they are committed. the system tracks removed items between commits. a list of these items is re
turned by a call to initlistbuild(). nsijumplistbuilder does not filter entries added that have been removed since the last commit. to prevent repeatedly adding entires users have removed, applications are encouraged to track removed items internally. each list is made up of an array of nsiwinjumplistitems representing items such as shortcuts, links, and separators. see nsijumplistitem for information...
...oid abortlistbuild(); parameters none. addlisttobuild() adds a list and if required, a set of items for the list. boolean addlisttobuild( in short acattype, in nsiarray items, optional in astring catname optional ); parameters acattype the type of list to add. items optional an array of nsijumplistitem items to add to the list. catname optional for custom lists, the title of the list. re
turn value true if the operation completed successfully. exceptions thrown ns_error_unexpected on internal errors. ns_error_illegal_value if an item is added that was removed since the last commit. ns_error_invalid_arg if incorrect parameters are passed for a particular category or item type. commitlistbuild() commits the current jump list build to the taskbar. boolean commitlistbuild(); parameters...
...ue if the operation completed successfully. exceptions thrown ns_error_unexpected on internal errors. ns_error_illegal_value if an item is added that was removed since the last commit. ns_error_invalid_arg if incorrect parameters are passed for a particular category or item type. commitlistbuild() commits the current jump list build to the taskbar. boolean commitlistbuild(); parameters none. re
turn value true if the operation completed successfully. deleteactivelist() deletes any currently applied taskbar jump list for this application. common uses would be the enabling of a privacy mode and uninstallation. boolean deleteactivelist(); parameters none. re
turn value true if the operation completed successfully. exceptions thrown ns_error_unexpected on internal errors. initlistbuild() initi...
...And 2 more matches
nsILocaleService
etsystemlocale(); nsilocale newlocale(in astring alocale); nsilocale newlocaleobject(in nsilocaledefinition localedefinition); obsolete since gecko 1.9 methods getapplicationlocale() gets the user preference for locale from the operating system. note: this has nothing to do with the locale used for localization of the application (ui text strings and so on.). this method re
turns something similar to getsystemlocale. nsilocale getapplicationlocale(); parameters none. re
turn value the user's os setting for preferred locale. getlocalecomponentforuseragent() gets the user preference for locale from the operating system. note: this has nothing to do with any http user-agent. this method re
turns the same as getsystemlocale.getcategory("nsilocale_messages"). astring getlocale...
...cale getapplicationlocale(); parameters none. re
turn value the user's os setting for preferred locale. getlocalecomponentforuseragent() gets the user preference for locale from the operating system. note: this has nothing to do with any http user-agent. this method re
turns the same as getsystemlocale.getcategory("nsilocale_messages"). astring getlocalecomponentforuseragent(); parameters none. re
turn value the user's os setting for preferred locale in the format described in nsilocale. getlocalefromacceptlanguage() gets the most preferred locale from a list of locale preferences. ...
...newlocale() create a new nsilocale from a locale string. ...
...And 2 more matches
nsIMsgFolder
ream readonly offlinestoreinputstream nsiinputstream readonly retentionsettings nsimsgretentionsettings downloadsettings nsimsgdownloadsettings sortorder long used for order in the folder pane, folder pickers, etc. lastmessageloaded nsmsgkey unique id to the folder, it is not a globally unique identifier. will re
turn nsmsgkey_none if there was no last message loaded. note: does not persist across sessions. uri acstring readonly: old nsifolder properties and methods. name astring old nsifolder properties and methods. prettyname astring old nsifolder properties and methods. abbreviatedname astring readonly: old nsifolder properties and methods...
... old nsifolder properties and methods. abbreviatedname astring readonly: old nsifolder properties and methods. parent nsimsgfolder old nsifolder properties and methods. parentmsgfolder nsimsgfolder readonly: handy accessor when we want a msg folder. ...
... nsifolder properties and methods. parentmsgfolder nsimsgfolder readonly: handy accessor when we want a msg folder. dbtransferinfo nsidbfolderinfo subfolders nsisimpleenumerator readonly: re
turns an enumerator containing a list of nsimsgfolder items that are subfolders of the instance this is called on. hassubfolders boolean readonly: re
turns true if this folder has sub folders. messages nsisimpleenumerator readonly: re
turns a list of components.interfaces.nsimsgdbhdr. numsubfolders unsigned long readonly: re
turns the number of sub folders that this folder has. invfeditsearchscope boolean readonly customidentity nsimsgidentity readonly: this allows a folder to have a specia...
...And 2 more matches
nsINavHistoryContainerResultNode
s. 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() re
turns 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 attribute to match on. aitemid the item id to match on. arecursive if true, the search will recurse through all child containers of the current co...
...ails( 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 attribute to match on. aitemid the item id to match on. arecursive if true, the search will recurse through all child containers of the current container; if false, only direct children of the container are searched. ...
... match on. aitemid the item id to match on. arecursive if true, the search will recurse through all child containers of the current container; if false, only direct children of the container are searched. re
turn value an nsinavhistoryresultnode of a node matching the specified details or null if no match is found. exceptions thrown ns_error_not_available the container is not open. getchild() re
turns the child node at the specified index. nsinavhistoryresultnode getchild( in unsigned long aindex ); parameters aindex the index into the child list of the node to fetch. ...
...And 2 more matches
nsINavHistoryQuery
annotation name per query. if annotationisnot is true, we test for the non-existance of the specified annotation. testing for not annotation will do the same thing as a normal query and remove everything that doesn't have that annotation. asking for things that do have a given annotation is a little different. it also includes things that have never been visited. this allows place queries to be re
turned (which might include bookmark folders -- use the bookmark service's getfolderuri) as well as anything else that may have been tagged with an annotation. this will only work for results_as_uri since there will be no visits for these items. begintime prtime begin time range for results (inclusive). begintimereference long one of the constants time_relative_* which indicates how to interpret t...
...e will be no visits for these items. begintime prtime begin time range for results (inclusive). begintimereference long one of the constants time_relative_* which indicates how to interpret the corresponding begin time value. domain autf8string this is the host or domain name (controlled by domainishost). when domainishost, domain only does exact matching on host names. otherwise, it will re
turn anything whose host name ends in domain. this one is a little different than most. setting it to an empty string is a real query and will match any uri that has no host name (local files and such). set this to null (in c++ use setisvoid) if you don't want domain matching. domainishost boolean this controls the meaning of domain, and whether it is an exact match domainishost = true, or hierarch...
... maxvisits long set upper limits for how many times an item has been visited. the default value is "-1", and in that case all items are matched regardless of their visit count. minvisits long set lower limits for how many times an item has been visited. the default value is "-1", and in that case all items are matched regardless of their visit count. onlybookmarked boolean when set, re
turns only bookmarked items, when unset, re
turns anything. setting this is equivalent to listing all bookmark folders in the folders parameter. searchterms astring text search terms. tags nsivariant a list of tags to use for filtering query results. this attribute must be an array of strings. duplicate tags may be specified, but when reading the list, only unique tags are re
turned. when called a...
...And 2 more matches
nsIScriptableInputStream
ble access to a nsiinputstream instance. ...
...exceptions thrown ns_base_stream_closed if called after the stream has been closed. close() closes the stream. note: the close method may be called more than once, but subsequent calls are ignored. void close(); parameters none. init() wrap the given nsiinputstream with this nsiscriptableinputstream. ...
... wrap the given nsiinputstream with this nsiscriptableinputstream. note: the init method may be called more than once, allowing a nsiscriptableinputstream instance to be reused. void init( in nsiinputstream ainputstream ); parameters ainputstream the nsiinputstream to be wrapped. read() read data from the stream. warning: if the data contains a null byte, then this method will re
turn a truncated string. note: it is also important to consider how a language bindings may interpret the string data type. in particular, some bindings may convert the byte values into unicode code points, by assuming the byte values are encoded as iso-latin-1. this is the case for the javascript bindings. string read( in unsigned long acount ); parameters acount the maximum number of by...
...And 2 more matches
nsISecurityCheckedComponent
o perform certain actions that allow it to read information from the local system. for example, this capability allows code to set the value of <input type="file"> and access an arbitrary file on disk. standard web pages have no special capabilities. extensions can define their own capabilities and use this interface to only allow access to code trusted with that capability. the two special re
turn values of '"allaccess" or "noaccess" unconditionally allow or deny access to the operation. all code has the "allaccess" capability, and no code has the "noaccess" capability. this interface is used in mozilla by xpconnect and a handful of things that need special handing (xul controllers, the ui for the <video> tag, etc.). method overview string cancallmethod(in nsiidptr iid, in wstring meth...
...pconnect and a handful of things that need special handing (xul controllers, the ui for the <video> tag, etc.). method overview string cancallmethod(in nsiidptr iid, in wstring methodname); string cancreatewrapper(in nsiidptr iid); string cangetproperty(in nsiidptr iid, in wstring propertyname); string cansetproperty(in nsiidptr iid, in wstring propertyname); methods cancallmethod() re
turns a capability string indicating what permissions are required to call the specified method on the given interface. string cancallmethod( in nsiidptr iid, in wstring methodname ); parameters iid the iid of the interface this method exists on. methodname the name of the method to be called on the interface. re
turn value the capability required to call this method. see capability strings for ...
...ng what permissions are required to call the specified method on the given interface. string cancallmethod( in nsiidptr iid, in wstring methodname ); parameters iid the iid of the interface this method exists on. methodname the name of the method to be called on the interface. re
turn value the capability required to call this method. see capability strings for details. cancreatewrapper() re
turns a string indicating what permissions are required to create a wrapper for the given interface. string cancreatewrapper( in nsiidptr iid ); parameters iid the interface to reflect into javascript. re
turn value the capability required to reflect this interface. note that if wrapper creation is prevented, the properties and methods will not be defined on the javascript object, whereas if wra...
...And 2 more matches
nsISelection2
void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array...
...lowadjacent, in rangearray results); native code only! void scrollintoview(in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent); attributes attribute type description type short re
turns the type of the selection (see nsiselectioncontroller for available constants). read only. methods getrangesforinterval() re
turn array of ranges intersecting with the given dom interval. void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results ); parameters beginnode beginoffset endnode endoffset these four parameter...
...omnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection. allowadjacent specifies whether the re
turned ranges are allowed to touch the input range rather than merely overlapping it. resultcount re
turns the number of ranges that overlap (or touch) the input range. results re
turns the ranges that overlap (or touch) the input range. native code only!getrangesforintervalcomarray void getrangesforintervalcomarray( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, ...
...And 2 more matches
nsISelectionController
selection_hidden 1 hidden displays selection. selection_on 2 selection_disabled 3 selection_attention 4 scroll constants constant value description scroll_synchronous 1<<1 if set scrolls the selection into view before re
turning. if not set, posts a request which is processed at some point after the method re
turns. scroll_first_ancestor_only 1<<2 if set, only the first ancestor will be scrolled into view. scroll_center_vertically 1<<4 if set, the specified location will be scrolled to the center of the view. methods native code only!characterextendfor...
...it? checkvisibility() checks if textnode and offsets are actually rendered in the current precontext. boolean checkvisibility( in nsidomnode node, in short startoffset, in short endoffset ); parameters node nsidomnode to test. startoffset offset in dom to first char of textnode to test. endoffset offset in dom to last char of textnode to test. re
turn value true if visible, false if not. completemove() will move page view to the top or bottom of the document this will also have the effect of collapsing the selection if the extend = pr_false the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void completemove( in boolean forward, in boolean extend ); parameters fo...
... pr_false. extend should it collapse the selection or extend it? completescroll() will move page view to the top or bottom of the document. void completescroll( in boolean forward ); parameters forward forward or backward if pr_false. getcaretenabled() gets the current state of the caret, as set by setcaretenabled(). boolean getcaretenabled(); parameters none. re
turn value if aoutenabled==null, re
turns ns_error_invalid_arg else ns_ok. getdisplayselection() will get the display mode for the selection. short getdisplayselection(); parameters none. re
turn value off, on, disabled. getselection() will re
turn the selection that the presentation shell may implement. nsiselection getselection( in short type ); parameters type will hold the type of ...
...And 2 more matches
nsIServiceManager
void getservice( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being requested. aiid the interface type ...
...nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); boolean isserviceinstantiated(in nscidref aclass, in nsiidref aiid); boolean isserviceinstantiatedbycontractid(in string acontractid, in nsiidref aiid); methods getservice() this method re
turns a reference to a particular xpcom service given the classid of the service. unlike createinstance, this will always re
turn the same object each time it is called with the same arguments. void getservice( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being requested. aiid the interface type to be re
turned. result the resulting interface pointer. exceptions thrown ns_error_factory_not_registered indicates ...
...n nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the service that is being requested. aiid the interface type to be re
turned. result the resulting interface pointer. exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getservicebycontractid() this method re
turns a reference to a particular xpcom service given the contractid of the service. void getservicebycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the service that is being requested. aiid the interface type to be re
turned. result the resulting interface pointer. exceptions thrown ns_e...
...And 2 more matches
nsISocketTransport
security notification callbacks passed to the secure socket provider via nsisslsocketcontrol at socket creation time. this object supports nsibadcertlistener2 and nsisslerrorlistener for ssl connections, and possibly other interfaces. note: this attribute cannot be changed once a stream has been opened. securityinfo nsisupports security info object re
turned from the secure socket provider. this object supports nsisslsocketcontrol, nsitransportsecurityinfo, and possibly other interfaces. this attribute is only available once the socket is connected. read only. constants timeout type this constants are used by gettransport() and settransport() to specify socket timeouts constant value description ...
... set, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. disable_ipv6 2 when this flag is set, the socket will ignore any ipv6 addresses the host may offer and will only attempt to connect to ipv4 addresses. methods native code only!getpeeraddr re
turns the ip address of the socket connection peer. this attribute is defined only once a connection has been established. prnetaddr getpeeraddr(); parameters none. re
turn value an prnetaddr containing the resolved ip address. native code only!getselfaddr re
turns the ip address of the initiating end. this attribute is defined only once a connection has been established. prnetaddr getselfaddr(); para...
...s of the socket connection peer. this attribute is defined only once a connection has been established. prnetaddr getpeeraddr(); parameters none. re
turn value an prnetaddr containing the resolved ip address. native code only!getselfaddr re
turns the ip address of the initiating end. this attribute is defined only once a connection has been established. prnetaddr getselfaddr(); parameters none. re
turn value an prnetaddr containing the resolved ip address. gettimeout() retrieves a socket timeout. unsigned long gettimeout( in unsigned long atype ); parameters atype the timeout type, who's associated value should be retrieved. can be one of the constants timeout_connect or timeout_read_write. re
turn value re
turns the timeout in seconds for the given type. a value of pr_uint32_m...
...And 2 more matches
nsITextInputProcessorCallback
createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._callback)) { ret...
... }, } met...
... }, } method overview boolean onnotify(in nsitextinputprocessor atextinputprocessor, in nsitextinputprocessornotification anotification); methods onnotify() this is called when gecko requests or notifies something to ime. ...
...And 2 more matches
Setting HTTP request headers
for learning, in an actual real-world application, you'd probably want to code it more like the following. ...
... myhttplistener() { } myhttplistener.prototype = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { log("----------------------------> (" + subject + ") mod request"); var httpchannel = subject.queryinterface(components.interfaces.nsihttpchannel); httpchannel.setrequestheader(headername, headervalue, false); re
turn; } if (topic == "profile-after-change") { log("----------------------------> profile-after-change"); var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(this, "http-on-modify-request", false); re
turn; } }, queryinterface:...
...nents.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(this, "http-on-modify-request", false); re
turn; } }, queryinterface: function (iid) { if (iid.equals(components.interfaces.nsiobserver) || iid.equals(components.interfaces.nsisupports)) re
turn this; components.re
turncode = components.results.ns_error_no_interface; re
turn null; }, }; var mymodule = { registerself: function (compmgr, filespec, location, type) { var compmgr = compmgr.queryinterface(components.interfaces.nsicomponentregistrar); compmgr.registerfactorylocation(this.mycid, this.myname, ...
...And 2 more matches
Storage
te 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. creating a statement there are actually two ways to execute a statement. you should choose the right one based on your needs. ...
...similarly, the c++ looks like th...
...oper(mspecialstatement); // you can use mspecialstatement without concern now. nscomptr<mozistoragestatement> statement; // mdbconn is a database connection that is stored a member variable of the class. nsresult rv = mdbconn->createstatement(ns_literal_cstring("delete from table_name"), getter_addrefs(statement)); ns_ensure_success(rv, rv); re
turn statement->execute(); // once this function re
turns, mspecialstatement will be reset, and statement will // be destroyed. } note: calling reset is not an expensive operation, and nothing bad happens if you call reset more than once. transactions transactions can be used to either improve performance, or group statements together as an atomic operation. in both cases, you execute more than...
...And 2 more matches
Xptcall Porting Guide
uilds a call frame and invokes the method indicated by the index methodindex on the xpcom interface that. here are examples of this implementation for win32 and linux x86, netbsd x86, and freebsd. these implementations use the basic strategy of: figure out how much stack space is needed for the params, make the space in a new frame, copy the params to that space, invoke the method, cleanup and re
turn. c++ is used where appropriate, assembly language is used where necessary. inline assembly language is used here, but it is equally valid to use separate assembly language source files. porters can decide how best to do this for their platforms. the stubs functionality is more complex. the goal here is a class whose vtbl can look like the vtbl of any arbitrary xpcom interface. objects of this cla...
...class can then be built to impersonate any xpcom object. the base interface for this is (from xptcall/public/xptcall.h): class nsxptcstubbase : public nsisupports { public: // include generated vtbl stub declarations. // these are virtual and *also* implemented by this class.. #include "xptcstubsdecl.inc" // the following methods must be provided by inheritor of this class. ...
...s. // these are virtual and *also* implemented by this class.. #include "xptcstubsdecl.inc" // the following methods must be provided by inheritor of this class. ...
...And 2 more matches
Filelink Providers
with the extra information. that url is then loaded into an iframe directly beneath the provider menulist. note: the setup dialog window should resize itself automatically in order to fit the content of the iframe without scrollbars. ...
...rame directly beneath the provider menulist. note: the setup dialog window should resize itself automatically in order to fit the content of the iframe without scrollbars. custom settings fields to handle custom settings, the settings xhtml page should contain a form with the id "provider-form", with its onsubmit attribute set to "re
turn false;". example: <form id="provider-form" onsubmit="re
turn false;"> <label for="username">username:</label> <input id="username" type="text" required="true" /> <label for="server">server:</label> <input id="server" type="text" required="true" /> <label for="port">port:</label> <input id="port" pattern="[0-9]+" required="true" /> </form> the form is expected to use html5 form validation. for each input event, the checkvalidity method of the ...
...r:</label> <input id="server" type="text" required="true" /> <label for="port">port:</label> <input id="port" pattern="[0-9]+" required="true" /> </form> the form is expected to use html5 form validation. for each input event, the checkvalidity method of the form is automatically called. ...
...And 2 more matches
MailNews fakeserver
the specs will require different handlers. writing a new fakeserver since the number of protocols we use is very small, most people shouldn't have to write an entirely new daemon and handler setup by themselves. that said, someone writing a new test may have to take into account a new handler. a handler will contain the following methods: <caption> handler methods </caption> name arguments re
turns notes [command] rest of sent line server's response the name is normalized to be uppercase. onerror command, rest of sent line server's response called if handler does not define the command function. onstartup none server's response called when a connection is made. onmultiline sent line server's response or nothing called when in multi-line mode. postcommand server object none calle...
...ize all occurrences of '\n' (but not '\r') to '\r\n' for you, as well as append the '\r\n' to the response if not present. it will also properly queue all messages sent in pipelining mode and will present lines without any eol characters. in addition, it uses utf-8 as the transmission medium. the server presents the following api to the handler: <caption> server api </caption> name arguments re
turns description closesocket none nothing closes the socket and stops the test. setmultiline the new value of multiline nothing the value is a boolean, with true invoking multiline mode. it is off by default. extending a handler to provide different mechanisms is a process not defined here; please check the documentation of the corresponding handler for instructions. using fakeserver in xpcshe...
..., fakeserver provides no means to keep a persistent connection past a test, requiring connections to be closed, possibly forcibly. alternatively, one can wait for the timeout, which occurs after 3 minutes, so not closing connections would make the tests take unbearably long. ...
...And 2 more matches
ArrayType
arraytype represents c arrays syntax re
turns a new ctype representing an array data type. ctype arraytype() type[ length] ); parameters type: it represents the type of the elements or variable which is going to be present in an array length optional it denotes the number of entries present in an array or the number of elements that an array should contain. if you don't specify this parameter, the array's length is unspecified. re
turn value a ctype represents the newly declared array type. exceptions thrown typeerror type is not a ctype, or type.size is undefined.if the length is specifed but if it is not a valid one,then it is also thrown rangeerror the size of the resulting array can't be represented as both a size_t and as a javascript number. propertie...
... property type description name string the type's name. read only. for primitive types, this is just the name of the corresponding c type. for structure and opaque pointer types, this is simply the string that was passed to the constructor. for other function, pointer, and array types, this should be a valid c type expression. ptr ctype re
turns a ctype representing the data type "pointer to this type". this is the result of calling ctypes.pointertype(the_type). read only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. method overview methods inherited from ctype ctype array([n]) string tosource(...
... method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() arraytype cdata syntax cdata sized_arraytype(); cdata unsized_arraytype(length); sized_arraytype and unsized_arraytype are arraytype ctype. parameters length the number of entries the array type should be able to contain. only for unsized arraytype. re
turn value a cdata representing the newly allocated array. exceptions thrown typeerror length is not provided for unsized array, or is provided for sized array. arraytype cdata properties property type description length number the length of the array. read only. in addition, each element in the array can be referenced by index using standard bracket notat...
...And 2 more matches
FunctionType
functiontype represents c function. syntax re
turns a new ctype object describing a c function. ctype functiontype( abi, re
turntype[, argtype1, ...] ); parameters abi the abi type for the function; this is one of the abi constants. re
turntype a ctype indicating the type of the value re
turned by the function. argtype1... argtypen zero or more ctype objects indicating the types of each of the parameters passed into the c function. re
turn value a ctype describing the function type. the equivalent c function type declaration would be: re
turntype (*) ([argtype1, ..., argtypen]); exceptions thrown typeerror abi is not a valid abi constants, or re
turntype or any of the argument types are not valid ctype objects. properties property type descripti...
...read only. properties inherited from ctype these properties are available on all ctype objects. property type description name string the type's name. read only. ...
...read only. properties inherited from ctype these properties are available on all ctype objects. property type description name string the type's name. read only. for primitive types, this is just the name of the corresponding c type. ...
...And 2 more matches
URLs - Plugins
ate 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 re
turns 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 *target); the instance...
...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 re
turns 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 parameters have the same def...
...est 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 parameters have the same definitions as those of npn_geturl. the notifydata parameter contains private plug-in data that can be used to associate the request with the subsequent npp_urlnotify call (which re
turns this value) and/or to pass a pointer to some request-related payload. if a request is not completed successfully (for example, because the url is invalid or an http server is down), the browser should call npp_urlnotify as soon as possible. if a request completes successfully, and the target is non-null, the browser calls npp_urlnotify after it has finished loading the url. if the target is nul...
...And 2 more matches
Accessibility Inspector - Firefox Developer Tools
ke screenreaders use this information to find out what's on a web page, tell their users what's there, and enable them to interact with the page. the accessibility inspector also uses this information to provide valuable accessibility debugging capabilities in the devtools. accessing the accessibility inspector when you first open any of the other developer tools, the accessibility features are
turned off (unless you've already got them
turned on in another browser tab, or got the firefox accessibility engine started already, e.g., you might be a screenreader user or tester). this is because the accessibility engine runs in the background when the accessibility features are
turned on. while it’s running, it slows performance and takes up memory; therefore it interferes with the metrics fro...
...lready, e.g., you might be a screenreader user or tester). this is because the accessibility engine runs in the background when the accessibility features are
turned on. while it’s running, it slows performance and takes up memory; therefore it interferes with the metrics from other panels such as memory and performance as well as overall browser performance. for this reason, you should keep it
turned off when you aren't specifically using it. when first implemented, the accessibility engine had to be explicitly
turned on. starting in firefox 79, it is automatically enabled when you do one of the following: choose accessibility in the tools > web developer menu. select the accessibility tab in the developer tools toolbox. right-click in the main browser window, and choose inspect acces...
...o the current item. for example, one of the links in one demo has states of focusable, linked, selectable text, opaque, enabled, and sensitive. for a full list of internal states, see gecko states. relations — a list of the accessiblity-relevant relationships between this item and other items. for example, in a form, an entry item could have a "labelled by" relation with a label item, which in
turn has a "label for" relation to the entry item. attributes — a list of all the accessibility-relevant attributes that are applied to the item. this can include style-related attributes such as margin-left and text-indent, and other useful states for accessibility information, such as draggable and level (e.g., what heading level is it, in the case of headings). for a full list of possible attrib...
...And 2 more matches
AudioTrack.label - Web APIs
the list is filtered to only allow certain track kinds through. ...
...the list is filtered to only allow certain track kinds through. ...
...the list is filtered to only allow certain track kinds through. ...
...And 2 more matches
Background Tasks API - Web APIs
onframe() to schedule that. avoid tasks whose run time can't be predicted. your idle callback should avoid doing anything that could take an unpredictable amount of time. for example, anything which might affect layout should be avoided. you should also avoid resolving or rejecting promises, since that would invoke the handler for that promise's resolution or rejection as soon as your callback re
turns. use timeouts when you need to, but only when you need to. using timeouts can ensure that your code runs in a timely manner, but it can also allow you to cause lag or animation stutters by mandating that the browser call you when there's not enough time left for you to run without disrupting performance. falling back to settimeout because the background tasks api is fairly new, your code may...
...settimeout() as a fallback option. this isn't a polyfill, since it's not functionally identical; settimeout() doesn't let you make use of idle periods, but instead runs your code when possible, leaving us to do the best we can to avoid causing the user to experience performance lag. ...
...esn't let you make use of idle periods, but instead runs your code when possible, leaving us to do the best we can to avoid causing the user to experience performance lag. window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); re
turn settimeout(function() { handler({ didtimeout: false, timeremaining: function() { re
turn math.max(0, 50.0 - (date.now() - starttime)); } }); }, 1); } if window.requestidlecallback is undefined, we create it here. the function begins by recording the time at which our implementation was called. we'll be using that to compute the value re
turned by our shim for timeremaining(). then we call settimeout(), passing into it a function which runs the callback passed into our im...
...And 2 more matches
Blob - Web APIs
the user's system. using blobs to construct a blob from other non-blob objects and data, use the blob() constructor. to create a blob that contains a subset of another blob's data, use the slice() method. to obtain a blob object for a file on the user's file system, see the file documentation. the apis accepting blob objects are also listed in the file documentation. constructor blob() re
turns a newly created blob object which contains a concatenation of all of the data in the array passed into the constructor. instance properties blob.prototype.size read only the size, in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. instance ...
...s a concatenation of all of the data in the array passed into the constructor. instance properties blob.prototype.size read only the size, in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. ...
...the size, in bytes, of the data contained in the blob object. blob.prototype.type read only a string indicating the mime type of the data contained in the blob. if the type is unknown, this string is empty. instance methods blob.prototype.arraybuffer() re
turns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data. blob.prototype.slice() re
turns a new blob object containing the data in the specified range of bytes of the blob on which it's called. blob.prototype.stream() re
turns a readablestream that can be used to read the contents of the blob. blob.prototype.text() re
turns a promise that resolves with a usvstring containing the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() construct...
...And 2 more matches
BluetoothRemoteGATTCharacteristic - Web APIs
bluetoothremotegattchara...
...e); promise<void> startnotifications(); promise<void> stopnotifications(); }; bluetoothremotegattcharacteristic implements eventtarget; bluetoothremotegattcharacteristic implements characteristiceventhandlers; properties bluetoothremotegattcharacteristic.serviceread only re
turns the bluetoothgattservice this characteristic belongs to. bluetoothremotegattcharacteristic.uuidread only re
turns a domstring containing the uuid of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. bluetoothremotegattcharacteristic.propertiesread only re
turns the properties of this characteristic. bluetoothremotegattcharacteristic.valueread only the currently cached characteristic value. this value gets updated when the value of the ...
...ment characteristic. bluetoothremotegattcharacteristic.propertiesread only re
turns the properties of this characteristic. bluetoothremotegattcharacteristic.valueread only the currently cached characteristic value. this value gets updated when the value of the characteristic is read or updated via a notification or indication. methods bluetoothremotegattcharacteristic.getdescriptor() re
turns a promise that resolves to the first bluetoothgattdescriptor for a given descriptor uuid. bluetoothremotegattcharacteristic.getdescriptors() re
turns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid. ...
...And 2 more matches
CSSCounterStyleRule - Web APIs
ts properties from its parent cssrule. csscounterstylerule.name is a domstring object that contains the serialization of the <counter-style-name> defined for the associated rule. csscounterstylerule.system is a domstring object that contains the serialization of the system descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.symbols is a domstring object that contains the serialization of the symbols descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.additivesymbols is a domstring object that contains the serialization of the additive-symbols descriptor defined for ...
...ation of the symbols descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.additivesymbols is a domstring object that contains the serialization of the additive-symbols descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.negative is a domstring object that contains the serialization of the negative descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.prefix is a domstring object that contains the serialization of the prefix descriptor defined for the associated ru...
...tains the serialization of the negative descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.prefix is a domstring object that contains the serialization of the prefix descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.suffix is a domstring object that contains the serialization of the suffix descriptor defined for the associated rule. if the descriptor was not specified in the associated rule, the attribute re
turns an empty string. csscounterstylerule.range is a domstring object that contains the serialization of the range descriptor defined for the associated rule. if...
...And 2 more matches
Cache.match() - Web APIs
if no match is found, the promise resolves to undefined. syntax cache.match(request, {options}).then(function(response) { // do something with the response }); parameters request the request for which you are attempting to find responses in the cache. this can be a request object or a url. options optional an object that sets options for the match operation. the available options are: ignoresearch: a boolean that specifies whether to ignore the query string in the url. ...
...en set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of whether the response object has a vary header. it defaults to false. re
turn value a promise that resolves to the first response that matches the request or to undefined if no match is found. note: cache.match() is basically identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). examples this example is taken from the custom offline page examp...
...than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). examples this example is taken from the custom offline page example (live demo). it uses a cache to supply selected data when a request fails. a catch() clause is triggered when the call to fetch() throws an exception. inside the catch() clause, match() is used to re
turn the correct response. in this example, only html documents retrieved with the get http verb will be cached. if our if() condition is false, then this fetch handler won't intercept the request. if there are any other fetch handlers registered, they will get a chance to call event.respondwith(). if no fetch handlers call event.respondwith(), the request will be handled by the browser as if there w...
...And 2 more matches
CanvasRenderingContext2D - Web APIs
h height onto the canvas, using the current stroke style. drawing text the following methods draw text. see also the textmetrics object for text properties. canvasrenderingcontext2d.filltext() draws (fills) a given text at the given (x, y) position. canvasrenderingcontext2d.stroketext() draws (strokes) a given text at the given (x, y) position. canvasrenderingcontext2d.measuretext() re
turns a textmetrics object. line styles the following methods and properties control how lines are drawn. canvasrenderingcontext2d.linewidth width of lines. default 1.0. canvasrenderingcontext2d.linecap type of endings on the end of lines. possible values: butt (default), round, square. canvasrenderingcontext2d.linejoin defines the type of corners where two lines meet. possible values: roun...
...dth width of lines. default 1.0. canvasrenderingcontext2d.linecap type of endings on the end of lines. possible values: butt (default), round, square. canvasrenderingcontext2d.linejoin defines the type of corners where two lines meet. possible values: round, bevel, miter (default). canvasrenderingcontext2d.miterlimit miter limit ratio. default 10. canvasrenderingcontext2d.getlinedash() re
turns the current line dash pattern array containing an even number of non-negative numbers. canvasrenderingcontext2d.setlinedash() sets the current line dash pattern. canvasrenderingcontext2d.linedashoffset specifies where to start a dash array on a line. text styles the following properties control how text is laid out. canvasrenderingcontext2d.font font setting. default value 10px sans-s...
...the coordinates represented by the parameters. canvasrenderingcontext2d.createradialgradient() creates a radial gradient given by the coordinates of the two circles represented by the parameters. canvasrenderingcontext2d.createpattern() creates a pattern using the specified image (a canvasimagesource). it repeats the source in the directions specified by the repetition argument. this method re
turns a canvaspattern. shadows canvasrenderingcontext2d.shadowblur specifies the blurring effect. default: 0 canvasrenderingcontext2d.shadowcolor color of the shadow. default: fully-transparent black. canvasrenderingcontext2d.shadowoffsetx horizontal distance the shadow will be offset. default: 0. canvasrenderingcontext2d.shadowoffsety vertical distance the shadow will be offset. default: ...
...And 2 more matches
Compositing example - Web APIs
function createcanvas() { var canvas = document.createelement("canvas"); canvas.style.background = "url("+op_8x8.data+")"; canvas.style.border = "1px solid #000"; canvas.style.margin = "5px"; canvas.width = width/2; canvas.height = height/2; ...
... and this code, runcomposite(), handles the bulk of the work, relying on a number of utility functions to do the hard parts. ...
...eft + halfwidth, otop + halfwidth); ctx.lineto(oleft + halfwidth + 6, otop); ctx.fillstyle = gradient; ctx.fill(); ctx.translate(oleft + halfwidth, otop + halfwidth); ctx.rotate(rotate); ctx.translate(-(oleft + halfwidth), -(otop + halfwidth)); } ctx.beginpath(); ctx.fillstyle = "#00f"; ctx.fillrect(15,15,30,30) ctx.fill(); re
turn ctx.canvas; }; // hsv (1978) = h: hue / s: saturation / v: value color = {}; color.hsv_rgb = function (o) { var h = o.h / 360, s = o.s / 100, v = o.v / 100, r, g, b; var a, b, c, d; if (s == 0) { r = g = b = math.round(v * 255); } else { if (h >= 1) h = 0; h = 6 * h; d = h - math.floor(h); a = math.round(255 * v * (...
...And 2 more matches
Pixel manipulation with canvas - Web APIs
the imagedata object represents the underlying pixel data of an area of a canvas object. it contains the following read-only attributes: width the width of the image in pixels. height the height of the image in pixels. data a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer values between 0 and 255 (included). the data property re
turns a uint8clampedarray which can be accessed to look at the raw pixel data; each pixel is represented by four one-byte values (red, green, blue, and alpha, in that order; that is, "rgba" format). each color component is represented by an integer between 0 and 255. each component is assigned a consecutive index within the array, with the top left pixel's red component being at index 0 within the arr...
...value from the pixel at column 200, row 50 in the image, you would do the following: bluecomponent = imagedata.data[((50 * (imagedata.width * 4)) + (200 * 4)) + 2]; if given a set of coordinates (x and y), you may end up doing something like this: var xcoord = 50; var ycoord = 100; var canvaswidth = 1024; function getcolorindicesforcoord(x, y, width) { var red = y * (width * 4) + x * 4; re
turn [red, red + 1, red + 2, red + 3]; } var colorindices = getcolorindicesforcoord(xcoord, ycoord, canvaswidth); var redindex = colorindices[0]; var greenindex = colorindices[1]; var blueindex = colorindices[2]; var alphaindex = colorindices[3]; var redforcoord = imagedata.data[redindex]; var greenforcoord = imagedata.data[greenindex]; var blueforcoord = imagedata.data[blueindex]; var alphaforcoor...
... = colorindices[3]; var redforcoord = imagedata.data[redindex]; var greenforcoord = imagedata.data[greenindex]; var blueforcoord = imagedata.data[blueindex]; var alphaforcoord = imagedata.data[alphaindex]; or, if es2015 is appropriate: const xcoord = 50; const ycoord = 100; const canvaswidth = 1024; const getcolorindicesforcoord = (x, y, width) => { const red = y * (width * 4) + x * 4; re
turn [red, red + 1, red + 2, red + 3]; }; const colorindices = getcolorindicesforcoord(xcoord, ycoord, canvaswidth); const [redindex, greenindex, blueindex, alphaindex] = colorindices; you may also access the size of the pixel array in bytes by reading the uint8clampedarray.length attribute: var numbytes = imagedata.data.length; creating an imagedata object to create a new, blank imagedata obj...
...And 2 more matches
CharacterData - Web APIs
xt-anchor="middle" alignment-baseline="middle">characterdata</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.data is a domstring representing the textual data contained in this object. ...
...rties inherits properties from its parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.data is a domstring representing the textual data contained in this object. characterdata.length read only re
turns an unsigned long representing the size of the string contained in characterdata.data. nondocumenttypechildnode.nextelementsibling read only re
turns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. nondocumenttypechildnode.previouselementsibling read only re
turns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. methods inherits methods from its pa...
...ng read only re
turns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. methods inherits methods from its parent, node, and implements the childnode and nondocumenttypechildnode interface. characterdata.appenddata() appends the given domstring to the characterdata.data string; when this method re
turns, data contains the concatenated domstring. characterdata.deletedata() removes the specified amount of characters, starting at the specified offset, from the characterdata.data string; when this method re
turns, data contains the shortened domstring. ...
...And 2 more matches
ContentIndex.getAll() - Web APIs
title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. ...
... title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. ...
... title: a string title for the item. used in user-visible lists of content. title: a string title of the item. used in user-visible lists of content. description: a string description of the item. used in user-visible lists of content. ...
...And 2 more matches
DataTransferItem.getAsFile() - Web APIs
example this example shows the use of the getasfile() method in a drop event handler. ...
... example this example shows the use of the getasfile() method in a drop event handler. ...
... example this example shows the use of the getasfile() method in a drop event handler. ...
...And 2 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
this will be either filesystemfileentry or filesystemdirectoryentry. ...
...this will be either filesystemfileentry or filesystemdirectoryentry. ...
...this will be either filesystemfileentry or filesystemdirectoryentry. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing. ...
...And 2 more matches
DirectoryEntrySync - Web APIs
iled to reach any substantial traction. basic concepts if you want to create subdirectories, you have to create each child directory in sequence. if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. so create the hierarchy by recursively adding a new path after creating the parent directory. example the getfile() method re
turns a fileentrysync, which represents a file in the file system. the following creates an empty file called seekrits.txt in the root directory. var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method re
turns a directoryentrysync, which represents a file in the file system. the following creates a new directory called superseekrit in the root directory. var dir...
...ng path, in optional flags options) raises (fileexception); directoryentrysync getdirectory (in domstring path, in optional flags options) raises (fileexception); void removerecursively () raises (fileexception); methods createreader() creates a new directoryreadersync to read entries from this directory. directoryreadersync createreader ( ) raises (fileexception); re
turns directoryreadersync represents a directory in a file system. parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. security_err the browser determined that it was not safe to look up the metadata. [ todo: explain why ] getfile() depending...
...xist, it is created. object literal condition result create: true exclusive: true path already exists an error is thrown. create: true exclusive: false path doesn't exist and no other error occurs a file is created. if a file already exists, no error is thrown. create: false (exclusive is ignored) path exists the file is re
turned. create: false (exclusive is ignored) path doesn't exist an error is thrown. create: false (exclusive is ignored) path exists, but is a directory an error is thrown. re
turns fileentrysync represents a file in a file system. exceptions this method can raise a fileexception with the following codes: exception description enco...
...And 2 more matches
Document.querySelector() - Web APIs
note: the matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. syntax element = document.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match. this string must be a valid css selector string; if it isn't, a syntax_err exception is thrown. see locating dom elements using selectors for more about selectors and how to manage them. ...
...r exception is thrown. see locating dom elements using selectors for more about selectors and how to manage them. note: characters that are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, be especially careful when writing string literals using these characters. see escaping special characters for more information. re
turn value an htmlelement object representing the first element in the document that matches the specified set of css selectors, or null is re
turned if there are no matches. if you need a list of all elements matching the specified selectors, you should use queryselectorall() instead. exceptions syntax_err the syntax of the specified selectors is invalid. usage notes if the specified selecto...
... escaping special characters to match against an id or selectors that do not follow standard css syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). ...
...And 2 more matches
Document.querySelectorAll() - Web APIs
note: this method is implemented based on the parentnode mixin's queryselectorall() method. syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. ...
... using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. re
turn value a non-live nodelist containing one element object for each element that matches at least one of the specified selectors or an empty nodelist in case of no matches. note: if the specified selectors include a css pseudo-element, the re
turned list is always empty. exceptions syntaxerror the syntax of the specified selectors string is not valid. examples obtaining a list of matches ...
...r an empty nodelist in case of no matches. note: if the specified selectors include a css pseudo-element, the re
turned list is always empty. exceptions syntaxerror the syntax of the specified selectors string is not valid. examples obtaining a list of matches to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example re
turns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert"); here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose id is test. var container = document.queryselector("#test"); var matches = container.querys...
...And 2 more matches
Introduction to the DOM - Web APIs
e modified with a scripting language such as javascript. the w3c dom and whatwg dom standards are implemented in most modern browsers. many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different doms. for example, the standard dom specifies that the getelementsbytagname method in the code below must re
turn a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc. alert(paragraphs[0].nodename); all of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that represents t...
... api that you should be aware of. note: because the vast majority of code that uses the dom revolves around manipulating html documents, it's common to refer to the nodes in the dom as elements, although strictly speaking not every node is an element. the following table briefly describes these data types. data type (interface) description document when a member re
turns an object of type document (e.g., the ownerdocument property of an element re
turns the document to which it belongs), this object is the root document object itself. the dom document reference chapter describes the document object. node every object located within a document is a node of some kind. in an html document, an object can be an element node but also a text node or attribut...
...gs), this object is the root document object itself. the dom document reference chapter describes the document object. node every object located within a document is a node of some kind. in an html document, an object can be an element node but also a text node or attribute node. element the element type is based on node. it refers to an element or a node of type element re
turned by a member of the dom api. rather than saying, for example, that the document.createelement() method re
turns an object reference to a node, we just say that this method re
turns the element that has just been created in the dom. element objects implement the dom element interface and also the more basic node interface, both of which are included together in this reference. in an html document, ...
...And 2 more matches
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
if pname is ext.query_result_available_ext: a glboolean indicating whether or not a query result is available. ...
... if pname is ext.query_result_available_ext: a glboolean indicating whether or not a query result is available. ...
... if pname is ext.query_result_available_ext: a glboolean indicating whether or not a query result is available. ...
...And 2 more matches
Element.attachShadow() - Web APIs
elements you can attach a shadow to note that you can't attach a shadow root to every type of element. there are some that can't have a shadow dom for security reasons (for example <a>), and more besides. ...
...ent.attachshadow(shadowrootinit); parameters shadowrootinit a shadowrootinit dictionary, which can contain the following fields: mode a string specifying the encapsulation mode for the shadow dom tree. this can be one of: open: elements of the shadow root are accessible from javascript outside the root, for example using element.shadowroot: element.shadowroot; // re
turns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: element.shadowroot; // re
turns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability. when a non-focusable part of the shadow dom is clicked, the first focusable part is given focus, a...
... exceptions exception explanation invalidstateerror the element you are trying to attach to is already a shadow host. ...
...And 2 more matches
Element.querySelectorAll() - Web APIs
note: this method is implemented based on the parentnode mixin's queryselectorall() method. syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using selectors for more information about using selectors to identify elements. multiple selectors may be specified by separating them using commas. ...
... using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. re
turn value a non-live nodelist containing one element object for each descendant node that matches at least one of the specified selectors. note: if the specified selectors include a css pseudo-element, the re
turned list is always empty. exceptions syntaxerror the syntax of the specified selectors string is not valid. examples dataset selector & attribute selectors <section class="box" id...
... var container = document.queryselector("#test"); var matches = con...
...And 2 more matches
Element.toggleAttribute() - Web APIs
[, force]); parameters name a domstring specifying the name of the attribute to be toggled. the attribute name is automatically converted to all lower-case when toggleattribute() is called on an html element in an html document. force optional a boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. re
turn value true if attribute name is eventually present, and false otherwise. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>. html <input value="text"> <button>toggleattribute("readonly")</button> ja...
... living standard ...
... living standard ...
...And 2 more matches
Event - Web APIs
event.cancelable read only a boolean indicating whether the event is cancelable. event.com...
... event.cancelable read only a boolean indicating whether the event is cancelable. ...
...indicates whether or not the call to event.preventdefault() canceled the event. event.eventphase read only indicates which phase of the event flow is being processed. event.explicitoriginaltarget read only the explicit original target of the event (mozilla-specific.) event.originaltarget read only the original target of the event, before any retargetings. (mozilla-specific.) event.re
turnvalue a historical property introduced by internet explorer and eventually adopted into the dom specification in order to ensure existing sites continue to work. ideally, you should try to use event.preventdefault() and event.defaultprevented instead, but you can use re
turnvalue if you choose to do so. event.srcelement a non-standard alias (from old versions of microsoft internet explorer) fo...
...And 2 more matches
FetchEvent.request - Web APIs
this property is non-nullable (since version 46, in the case of firefox.) if a request is not provided by some other means, the constructor init object must contain a request (see fetchevent.fetchevent().) syntax var recentrequest = fetchevent.request; value a request object. example this code snippet is from the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. ...
...pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http error response (e.g., 404) will not trigger an exception. ...
...04) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); re
turn response; } console.log('no response found in cache. ...
...And 2 more matches
File - Web APIs
a file object is a specific kind of a blob, and can be used in any context that a blob can. in particular, filereader, url.createobjecturl(), createimagebitmap(), and xmlhttprequest.send() accept both blobs and files. ...
...ocs/web/api/file" target="_top"><rect x="116" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="153.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">file</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor file() re
turns a newly constructed file. instance properties file.prototype.lastmodified read only re
turns the last modified time of the file, in millisecond since the unix epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only re
turns the last modified date of the file referenced by the file object. file.prototype.nameread only re
turns the name of the file referenced b...
...stmodified read only re
turns the last modified time of the file, in millisecond since the unix epoch (january 1st, 1970 at midnight). file.prototype.lastmodifieddate read only re
turns the last modified date of the file referenced by the file object. file.prototype.nameread only re
turns the name of the file referenced by the file object. file.prototype.webkitrelativepath read only re
turns the path the url of the file is relative to. file implements blob, so it also has the following properties available to it: file.prototype.size read only re
turns the size of the file in bytes. file.prototype.type read only re
turns the mime type of the file. instance methods the file interface doesn't define any methods, but inherits methods from the blob interface: blob.prototype...
...And 2 more matches
Using the Geolocation API - Web APIs
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. ...
... navigator.geolocation.getcurrentposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the above example will cause the dosomething() function to execute when the location is obtained. ...
...iques are used to geolocate you. the error callback function, which is optional just as it is for getcurrentposition(), can be called repeatedly. note: you can use watchposition() without an initial getcurrentposition() call. const watchid = navigator.geolocation.watchposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the watchposition() method re
turns an id number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearwatch() method to stop watching the user's location. navigator.geolocation.clearwatch(watchid); fine tuning the response both getcurrentposition() and watchposition() accept a success callback, an optional error callback, and an optional positionoptions object. this ...
...And 2 more matches
HTMLFormElement.elements - Web APIs
note: similarly, you can get a list of all of the forms contained within a given document using the document's forms property. syntax nodelist = htmlformelement.elements value an htmlformcontrolscollection containing all non-image controls in the form. ...
... note: similarly, you can get a list of all of the forms contained within a given document using the document's forms property. syntax nodelist = htmlformelement.elements value an htmlformcontrolscollection containing all non-image controls in the form. ...
... note: similarly, you can get a list of all of the forms contained within a given document using the document's forms property. syntax nodelist = htmlformelement.elements value an htmlformcontrolscollection containing all non-image controls in the form. ...
...And 2 more matches
HTMLObjectElement - Web APIs
bclass, or the path to get to the class, including the class file itself. htmlobjectelement.codebase is a domstring that reflects the codebase html attribute, specifying the base path to use to resolve relative uris. htmlobjectelement.codetype is a domstring that reflects the codetype html attribute, specifying the content type of the data. ...
...ing the base path to use to resolve relative uris. htmlobjectelement.codetype is a domstring that reflects the codetype html attribute, specifying the content type of the data. htmlobjectelement.contentdocument read only re
turns a document representing the active document of the object element's nested browsing context, if any; otherwise null. htmlobjectelement.contentwindow read only re
turns a windowproxy representing the window proxy of the object element's nested browsing context, if any; otherwise null. htmlobjectelement.data re
turns a domstring that reflects the data html attribute, specifying the address of a resource's data. htmlobjectelement.declare is a boolean that reflects the declare html attribute, indicating that this is a declaration, not an instantiation, of the...
...ects the data html attribute, specifying the address of a resource's data. htmlobjectelement.declare is a boolean that reflects the declare html attribute, indicating that this is a declaration, not an instantiation, of the object. htmlobjectelement.form read only retuns a htmlformelement representing the object element's form owner, or null if there isn't one. htmlobjectelement.height re
turns a domstring that reflects the height html attribute, specifying the displayed height of the resource in css pixels. htmlobjectelement.hspace is a long representing the horizontal space in pixels around the control. htmlobjectelement.name re
turns a domstring that reflects the name html attribute, specifying the name of the browsing context. htmlobjectelement.standby is a domstring that ...
...And 2 more matches
HTMLTableElement - Web APIs
a <tfoot>, a domexception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any. htmltableelement.rowsread only re
turns a live htmlcollection containing all the rows of the element, that is all <tr> that are a child of the element, or a child of one of its <thead>, <tbody> and <tfoot> children. the rows members of a <thead> appear first, in tree order, and those members of a <tbody> last, also in tree order. the htmlcollection is live and is automatically updated when the htmltableelement changes. htmltableeleme...
...containing all the rows of the element, that is all <tr> that are a child of the element, or a child of one of its <thead>, <tbody> and <tfoot> children. the rows members of a <thead> appear first, in tree order, and those members of a <tbody> last, also in tree order. the htmlcollection is live and is automatically updated when the htmltableelement changes. htmltableelement.tbodiesread only re
turns a live htmlcollection containing all the <tbody> of the element. the htmlcollection is live and is automatically updated when the htmltableelement changes. obsolete properties warning: the following properties are obsolete. you should avoid using them. htmltableelement.align is a domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of t...
...s a domstring containing a description of the purpose or the structure of the table. it reflects the obsolete summary attribute. htmltableelement.width is a domstring containing the length in pixels or in percentage of the desired width fo the entire table. it reflects the obsolete width attribute. methods inherits methods from its parent, htmlelement. htmltableelement.createthead() re
turns an htmlelement representing the first <thead> that is a child of the element. if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. htmltableelement.deletethead() removes the first <thead> that is a child of the element. htmltableelement.createtfoot()...
...And 2 more matches
HTMLVideoElement - Web APIs
its ancestor interfaces, htmlmediaelement, and htmlelement. htmlvideoelement.height is a domstring that reflects the height html attribute, which specifies the height of the display area, in css pixels. htmlvideoelement.poster is a domstring that reflects the poster html attribute, which specifies an image to show while no video data is available. htmlvideoelement.videoheight read only re
turns an unsigned integer value indicating the intrinsic height of the resource in css pixels, or 0 if no media is available yet. htmlvideoelement.videowidth read only re
turns an unsigned integer value indicating the intrinsic width of the resource in css pixels, or 0 if no media is available yet. htmlvideoelement.width is a domstring that reflects the width html attribute, which specifies the wi...
...e yet. htmlvideoelement.videowidth read only re
turns an unsigned integer value indicating the intrinsic width of the resource in css pixels, or 0 if no media is available yet. htmlvideoelement.width is a domstring that reflects the width html attribute, which specifies the width of the display area, in css pixels. gecko-specific properties htmlvideoelement.mozparsedframes read only re
turns an unsigned long with the count of video frames that have been parsed from the media resource. htmlvideoelement.mozdecodedframes read only re
turns an unsigned long with the count of parsed video frames that have been decoded into images. ...
...area, in css pixels. gecko-specific properties htmlvideoelement.mozparsedframes read only re
turns an unsigned long with the count of video frames that have been parsed from the media resource. htmlvideoelement.mozdecodedframes read only re
turns an unsigned long with the count of parsed video frames that have been decoded into images. htmlvideoelement.mozpresentedframes read only re
turns an unsigned long with the count of decoded frames that have been presented to the rendering pipeline for painting. htmlvideoelement.mozpaintedframes read only re
turns an unsigned long with the count of presented frames which were painted on the screen. htmlvideoelement.mozframedelay read only re
turns an double with the time which the last painted video frame was late by, in seconds. htm...
...And 2 more matches
Drag Operations - Web APIs
the data. during the drag, in an event listener for the dragenter and dragover events, you use the data types of the data being dragged to check whether a drop is allowed. for instance, a drop target that accepts links would check for the type text/uri-list. during a drop event, a listener would retrieve the data being dragged and insert it at the drop location. the drag data's types property re
turns a list of mime-type like domstrings, such as text/plain or image/jpeg. you can also create your own types. the most commonly used types are listed in the article recommended drag types. a drag may include data items of several different types. this allows data to be provided in more specific types, often custom types, yet still provide fallback data for drop targets that do not support more spe...
...ragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped. most areas of a web page or application are not valid places to drop data. thus, the default handling of these events is not to allow a drop. if you want to allow a drop, you must prevent the default handling by cancelling both the dragenter and dragover events. you can do this either by re
turning false from attribute-defined event listeners, or by calling the event's preventdefault() method. the latter may be more feasible in a function defined in a separate script. <div ondragover="re
turn false"> <div ondragover="event.preventdefault()"> calling the preventdefault() method during both a dragenter and dragover event will indicate that a drop is allowed at that location. however, you...
...condition is met. if the condition is not met, don't cancel the event, and a drop will not occur there if the user releases the mouse button. it is most common to accept or reject a drop based on the type of drag data in the data transfer — for instance, allowing images, or links, or both. to do this, you can check the types property of the event's datatransfer (property). the types property re
turns an array of the string types that were added when the drag began, in the order from most significant to least significant. function dodragover(event) { const islink = event.datatransfer.types.includes("text/uri-list"); if (islink) { event.preventdefault(); } } in this example, we use the includes method to check if the type text/uri-list is present in the list of types. if it is, we ...
...And 2 more matches
Recommended Drag Types - Web APIs
st and text/plain types. these types should be added afterward so that the more specific application/x-moz-file type has higher priority. multiple files will be received during a drop as multiple items in the data transfer. see dragging and dropping multiple items for more details about this. ...
... added afterward so that the more specific application/x-moz-file type has higher priority. multiple files will be received during a drop as multiple items in the data transfer. see dragging and dropping multiple items for more details about this. ...
...le files will be received during a drop as multiple items in the data transfer. see dragging and dropping multiple items for more details about this. the following example shows how to create an area for receiving dropped files: <listbox ondragenter="re
turn checkdrag(event)" ondragover="re
turn checkdrag(event)" ondrop="dodrop(event)"/> <script> function checkdrag(event) { re
turn event.datatransfer.types.contains("application/x-moz-file"); } function dodrop(event) { var file = event.datatransfer.mozgetdataat("application/x-moz-file", 0); if (file instanceof components.interfaces.nsifile) { event.currenttarget.appenditem(file.leafname); } } </script> in this example, the event re
turns false only if the data transfer contains the application/x-moz-file type. du...
...And 2 more matches
Headers.getAll() - Web APIs
obsolete since gecko 52 (firefox 52 / thunderbird 52 / seamonkey 2.49)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the getall() method of the headers interface used to re
turn an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one. if the requested header doesn't exist in the headers object, it re
turns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.ge...
...ray. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.getall(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. ...
...rows a typeerror. re
turns an array containing a bytestring sequence representing the values of the retrieved header. ...
...And 2 more matches
IDBRequest - Web APIs
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 re
turn 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 re
turns 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, a...
...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). ...
...t="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="201" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbrequest</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties also inherits properties from eventtarget. idbrequest.error read only re
turns a domexception in the event of an unsuccessful request, indicating what went wrong. idbrequest.result read only re
turns the result of the request. if the the request failed and the result is not available, an invalidstateerror exception is thrown. idbrequest.source read only the source of the request, such as an idbindex or an idbobjectstore. if no source exists (such as when calling i...
...And 2 more matches
Checking when a deadline is due - Web APIs
orded as full four digit year numbers. when the form's submit button is pressed, we run the adddata() function, which starts like this: function adddata(e) { e.preventdefault(); if(title.value == '' || hours.value == null || minutes.value == null || day.value == '' || month.value == '' || year.value == null) { note.innerhtml += '<li>data not submitted — form incomplete.</li>'; re
turn; } in this segment, we check to see if the form fields have all been filled in. if not, we drop a message into our developer notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out of the function. this step is mainly for browsers that don't support html form validation (i have used the required attribute in my html to force validation, in those ...
... = now.gethours(); var daycheck = now.getdate(); var monthcheck = now.getmonth(); var yearcheck = now.getfullyear(); the date object has a number of methods to extract various parts of the date and time inside it. ...
...ow.getdate(); var monthcheck = now.getmonth(); var yearcheck = now.getfullyear(); the date object has a number of methods to extract various parts of the date and time inside it. ...
...And 2 more matches
LockManager.request() - Web APIs
the mode property of the options parameter may be either "exclusive" or "shared". request an "exclusive" lock when it should only be held by one code instance at a time. this applies to code in both tabs and workers. use this to represent mutually exclusive access to a resource. ...
...alse. steal optional: if true, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it. the default value is 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 … re
turn 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 re
turns. await navigator.locks.request('my_resource', async lock => { //...
...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. }); } ifavailable example to grab a lock only if it isn't already being held, use the ifavailable option. ...
...And 2 more matches
ParentNode.querySelectorAll() - Web APIs
if you need only a single result, consider the queryselector() method instead. note: this method is implemented as element.queryselectorall(), document.queryselectorall(), and documentfragment.queryselectorall() syntax elementlist = parentnode.queryselectorall(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid css selector string; if it's not, a syntaxerror exception is thrown. ...
... using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. re
turn value a non-live nodelist containing one element object for each descendant node that matches at least one of the specified selectors. note: if the specified selectors include a css pseudo-element, the re
turned list is always empty. exceptions syntaxerror the syntax of the specified selectors string is not valid. examples to obtain a nodelist of all of the <p> elements in the document...
...h descendant node that matches at least one of the specified selectors. note: if the specified selectors include a css pseudo-element, the re
turned list is always empty. exceptions syntaxerror the syntax of the specified selectors string is not valid. examples to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example re
turns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert"); here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose id is test. var container = document.queryselector("#test"); var matches = container.querys...
...And 2 more matches
PaymentRequestEvent - Web APIs
the paymentrequestevent interface of the the payment request api is the object passed to a payment handler when a paymentrequest is made. constructor paymentrequestevent() creates a new paymentrequestevent object. properties instrumentkeyread only re
turns a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. ...
... api is the object passed to a payment handler when a paymentrequest is made. constructor paymentrequestevent() creates a new paymentrequestevent object. properties instrumentkeyread only re
turns a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. methoddataread only re
turns an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data. ...
...urns a paymentinstrument object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument. methoddataread only re
turns an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data. modifiersread only re
turns an array of objects containing changes to payment details. paymentrequestidread only re
turns the id of the paymentrequest object. ...
...And 2 more matches
PaymentResponse - Web APIs
the paymentresponse interface of the payment request api is re
turned after a user selects a payment method and approves a payment request. properties paymentresponse.details read only secure context re
turns a json-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. the contents of the object depend on the payment method being used; for example, if the basic card payment method is used, this object must conform to the structure defined in the basiccardresponse dictionary. paymentresponse.methodname read only secure context re
turns the payment method identifier for the payment method that the user selected, for example, visa, mastercard, paypal, etc.. paymentresponse.payeremail r...
...od being used; for example, if the basic card payment method is used, this object must conform to the structure defined in the basiccardresponse dictionary. paymentresponse.methodname read only secure context re
turns the payment method identifier for the payment method that the user selected, for example, visa, mastercard, paypal, etc.. paymentresponse.payeremail read only secure context re
turns the email address supplied by the user. this option is only present when the requestpayeremail option is set to true in the options parameter of the paymentrequest() constructor. paymentresponse.payername read only secure context re
turns the name supplied by the user. this option is only present when the requestpayername option is set to true in the options parameter of the paymentrequest() c...
... when the requestpayeremail option is set to true in the options parameter of the paymentrequest() constructor. paymentresponse.payername read only secure context re
turns the name supplied by the user. this option is only present when the requestpayername option is set to true in the options parameter of the paymentrequest() constructor. paymentresponse.payerphone read only secure context re
turns the phone number supplied by the user. this option is only present when the requestpayerphone option is set to true in the options parameter of the paymentrequest() constructor. paymentresponse.requestid read only secure context re
turns the identifier of the paymentrequest that produced the current response. this is the same value supplied in the paymentrequest() constructor by details.id. p...
...And 2 more matches
performance.clearResourceTimings() - Web APIs
moves all performance entries with an entrytype of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. ...
...rytype of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void re
turn value none this method has no re
turn value. ...
...yntax performance.clearresourcetimings(); arguments void re
turn value none this method has no re
turn value. ...
...And 2 more matches
RTCPeerConnection.getStats() - Web APIs
the rtcpeerconnection method getstats() re
turns a promise which resolves with data providing statistics about either the overall connection or about the specified mediastreamtrack. syntax promise = rtcpeerconnection.getstats(selector) parameters selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. re
turn value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection. ...
...to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. re
turn value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the selector as well as other details of the connection. exceptions this method does not throw exceptions; instead, it rejects the re
turned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver. obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise. this version of getstats() is obsolete; in addition, t...
...th one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtpreceiver whose track matches the specified selector, or selector matches more than one sender or receiver. obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise. this version of getstats() is obsolete; in addition, the data it re
turns is entirely different from the current specification, and the form of that data was never documented. this form of getstats() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the new promise-based version. check the browser compatibility table to verify the state of this method. promise = rtcpeerconnection.getstats(selector, succ...
...And 2 more matches
RTCPeerConnection.setConfiguration() - Web APIs
ion for a connection once it's already been set. syntax rtcpeerconnection.setconfiguration(configuration); parameters configuration an rtcconfiguration object which provides the options to be set. the changes are not additive; instead, the new values completely replace the existing ones. exceptions invalidaccesserror one or more of the urls specified in configuration.iceservers is a
turn server, but complete login information is not provided (that is, either the rtciceserver.username or rtciceserver.credentials is missing). this prevents successful login to the server. invalidmodificationerror the configuration includes changed identity information, but the connection already has identity information specified. this happens if configuration.peeridentity or configuration.certifi...
...e current configuration. invalidstateerror the rtcpeerconnection is closed. syntaxerror one or more of the urls provided in the configuration.iceservers list is invalid. example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server. ...
...nfiguration. invalidstateerror the rtcpeerconnection is closed. syntaxerror one or more of the urls provided in the configuration.iceservers list is invalid. example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server. ...
...And 2 more matches
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 re
turns 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...
...tes a new offer and sets that as the new local description. otherwise, setlocaldescription() creates an answer, which becomes the new local description. type of the description parameter the description is of type rtcsessiondescriptioninit, which is a serialized version of a rtcsessiondescription browser object. ...
...l description. type of the description parameter the description is of type rtcsessiondescriptioninit, which is a serialized version of a rtcsessiondescription browser object. ...
...And 2 more matches
ReadableStream.ReadableStream() - Web APIs
the readablestream() constructor creates and re
turns a readable stream object from the given handlers. syntax var readablestream = new readablestream(underlyingsource[, queuingstrategy]); parameters underlyingsource an object containing methods and properties that 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 re
turn a promise to signal success or failure. the controller parameter passed to this method is a readablestre...
...od 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 when the stream's internal queue of chunks is not full, up until it reaches its high water mark. if pull() re
turns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. the controller parameter passed to this method is a readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream as more chunks are fetched. cancel(reason) optiona...
...y. 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 re
turn 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 buffer)/byte stream. if it ...
...And 2 more matches
ReadableStream.getReader() - Web APIs
string specifying the type of reader to create. values can be: "byob", which results in a readablestreambyobreader being created that can read readable byte streams (i.e. can handle "bring your own buffer" reading). undefined (or not specified at all — this is the default), which results in a readablestreamdefaultreader being created that can read individual chunks from a stream. re
turn value a readablestreamdefaultreader or readablestreambyobreader object instance, depending on the mode value. exceptions rangeerror the provided mode value is not "byob" or undefined. typeerror the stream you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefau...
...eam you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). ...
...eader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we re
turn out of the recursive function and print the entire stream to another part of the ui. ...
...And 2 more matches
ReadableStream.tee() - Web APIs
the tee() method of the readablestream interface tees the current readable stream, re
turning a two-element array containing the two resulting branches as new readablestream instances. this is useful for allowing two readers to read a stream simultaneously, perhaps at different speeds. you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, you’d need two copies to do this. to cancel the stream you then need to cancel both resulting branches. ...
...it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, you’d need two copies to do this. to cancel the stream you then need to cancel both resulting branches. teeing a stream will generally lock it for the duration, preventing other readers from locking it. syntax var teedstreams = readablestream.tee(); parameters none. re
turn value an array containing two readablestream instances. exceptions typeerror the source stream is not a readablestream. examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to...
...at reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full code. ...
...And 2 more matches
ReadableStream - Web APIs
methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. ...
... methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. ...
...eadablestream.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 transform stream or any other writable/readable pair. readablestream.pipeto() pipes the current readablestream to a given writablestream and re
turns 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, re
turning 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 metho...
...And 2 more matches
ReadableStreamDefaultReader.cancel() - Web APIs
still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreamdefaultreader.cancel(reason); parameters reason optional a domstring providing a human-readable reason for the cancellation. re
turn value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream exa...
... is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream example). ...
... // value - some data. always undefined when done is true. ...
...And 2 more matches
ReadableStreamDefaultReader.read() - Web APIs
the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. ...
...eam chunks not ending on line boundaries for example. in this example stream is a previously-created custom readablestream. it is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). ...
...er(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui as an array of utf-8 bytes, until the stream has finished being read, at which point we re
turn out of the recursive function and print the entire stream to another part of the ui. ...
...And 2 more matches
ReadableStreamDefaultReader - Web APIs
the readablestreamdefaultreader interface of the streams api represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). constructor readablestreamdefaultreader() creates and re
turns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. re
turns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreamdefaultreader.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. readablestreamdefaul...
... readablestreamdefaultreader.releaselock() releases the reader's lock on the stream. examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
...e browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
...And 2 more matches
SVGRectElement - Web APIs
stroke-width="2px" /><text x="-29" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgrectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. ...
...d4e53" text-anchor="middle" alignment-baseline="middle">svgrectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. svgrectelement.x read only re
turns an svganimatedlength corresponding to the x attribute of the given <rect> element. svgrectelement.y read only re
turns an svganimatedlength corresponding to the y attribute of the given <rect> element. ...
...d; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. svgrectelement.x read only re
turns an svganimatedlength corresponding to the x attribute of the given <rect> element. svgrectelement.y read only re
turns an svganimatedlength corresponding to the y attribute of the given <rect> element. svgrectelement.width read only re
turns an svganimatedlength corresponding to the width attribute of the given <rect> element. svgrectelement.height read only re
turns an svganimatedlength corresponding to the height attribute of the given <rect> element. ...
...And 2 more matches
Screen.availLeft - Web APIs
re
turns the first available pixel available from the left side of the screen. syntax let availleft = window.screen.availleft; example let setx = window.screen.width - window.screen.availleft; let sety = window.screen.height - window.screen.availtop; window.moveto(setx, sety); notes in most cases, this property re
turns 0. if you work with two screens this property, evaluated on the right screen, re
turns the width of the left one in pixels (thereby indicating the x coordinate of the left edge of the screen on the right). on windows, this property depends on which screen is set as your primary, re
turning the x coordinate of the leftmost available pixel relative to the primary screen. that is, the primary screen's left edge always has the x coordinate 0, even if it's not the le...
...perty depends on which screen is set as your primary, re
turning the x coordinate of the leftmost available pixel relative to the primary screen. that is, the primary screen's left edge always has the x coordinate 0, even if it's not the leftmost screen. ...
...et as your primary, re
turning the x coordinate of the leftmost available pixel relative to the primary screen. that is, the primary screen's left edge always has the x coordinate 0, even if it's not the leftmost screen. ...
...And 2 more matches
Screen.lockOrientation() - Web APIs
the following strings represent the possible orientation requirements you may specify: portrait-primary it represents the orientation of the screen when it is in its primary portrait mode. ...
...held
turned by 90° clockwise. the normal position is device dependant. portrait-secondary it represents the orientation of the screen when it is in its secondary portrait mode. a screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is
turned by 90° anticlockwise. the normal position is device dependant. landscape-primary it represents the orientation of the screen when it is in its primary landscape mode. ...
...ice held is
turned by 90° anticlockwise. the normal position is device dependant. landscape-primary it represents the orientation of the screen when it is in its primary landscape mode. a screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is
turned by 90° clockwise. the normal position is device dependant. landscape-secondary it represents the orientation of the screen when it is in its secondary landscape mode. ...
...And 2 more matches
ServiceWorkerContainer - Web APIs
nregister and update service workers, and access the state of service workers and their registrations. most importantly, it exposes the serviceworkercontainer.register() method used to register service workers, and the serviceworkercontainer.controller property used to determine whether or not the current page is actively controlled. ...
...ers and their registrations. most importantly, it exposes the serviceworkercontainer.register() method used to register service workers, and the serviceworkercontainer.controller property used to determine whether or not the current page is actively controlled. properties serviceworkercontainer.controller read only re
turns a serviceworker object if its state is activated (the same object re
turned by serviceworkerregistration.active). ...
...e serviceworkercontainer.register() method used to register service workers, and the serviceworkercontainer.controller property used to determine whether or not the current page is actively controlled. properties serviceworkercontainer.controller read only re
turns a serviceworker object if its state is activated (the same object re
turned by serviceworkerregistration.active). this property re
turns null during a force-refresh request (shift + refresh) or if there is no active worker. ...
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
erglobalscope.skipwaiting() allows the current service worker registration to progress from waiting to active state while service worker clients are using it. serviceworkerglobalscope implements workerglobalscope — which implements windoworworkerglobalscope. therefore it also has the following property available to it: globalfetch.fetch() starts the process of fetching a resource. ...
...s re
turns a promise that resolves to the response object representing the response to your request. this algorithm is the entry point for the fetch handling handed to the service worker context. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code re
turns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code set. self.addeventlistener('fetch...
...04) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); re
turn response; } console.log('no response found in cache. ...
...And 2 more matches
SpeechRecognitionEvent - Web APIs
the speechrecognitionevent interface of the web speech api represents the event object for the result and nomatch events, and contains all the data associated with an interim or final speech recognition result. properties speechrecognitionevent also inherits properties from its parent interface, event. ...
...ch events, and contains all the data associated with an interim or final speech recognition result. properties speechrecognitionevent also inherits properties from its parent interface, event. speechrecognitionevent.emma read only re
turns an extensible multimodal annotation markup language (emma) — xml — representation of the result. speechrecognitionevent.interpretation read only re
turns the semantic meaning of what the user said. speechrecognitionevent.resultindex read only re
turns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed. speechrecognitionevent.results read only re
turns a speechrecognitionresultlist object representing all the speech recognition results for the current session. examples this code is excerpted f...
... in the speechrecognitionresultlist "array" that has actually changed. speechrecognitionevent.results read only re
turns a speechrecognitionresultlist object representing all the speech recognition results for the current session. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters...
...And 2 more matches
SpeechRecognitionResult - Web APIs
the speechrecognitionresult interface of the web speech api represents a single recognition match, which may contain multiple speechrecognitionalternative objects. properties speechrecognitionresult.isfinal read only a boolean that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be re
turned; if not, then this result is an interim result, and may be updated later on. ...
...tion match, which may contain multiple speechrecognitionalternative objects. properties speechrecognitionresult.isfinal read only a boolean that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be re
turned; if not, then this result is an interim result, and may be updated later on. speechrecognitionresult.length read only re
turns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.
...ts contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters...
...And 2 more matches
StylePropertyMapReadOnly - Web APIs
the stylepropertymapreadonly interface of the the css typed object model api provides a read-only representation of a css declaration block that is an alternative to cssstyledeclaration. retrieve an instance of this interface using element.computedstylemap(). properties stylepropertymapreadonly.size re
turns an unsinged long integer containing the size of the stylepropertymapreadonly object. methods stylepropertymapreadonly.entries() re
turns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly. styl...
...donly.entries() re
turns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly. stylepropertymapreadonly.get() re
turns the value of the specified property. stylepropertymapreadonly.getall() re
turns an array of cssstylevalue objects containing the values for the provided property. stylepropertymapreadonly.has() indicates whether the specified property is in the stylepropertymapreadonly object. ...
... examples we have to have an element to observe: <p> this is a paragraph with some text. ...
...And 2 more matches
StyleSheet - Web APIs
an object implementing the stylesheet interface represents a single style sheet. css style sheets will further implement the more specialized cssstylesheet interface. properties stylesheet.disabled is a boolean representing whether the current stylesheet has been applied or not. stylesheet.href read only re
turns a domstring representing the location of the stylesheet. ...
...mplementing the stylesheet interface represents a single style sheet. css style sheets will further implement the more specialized cssstylesheet interface. properties stylesheet.disabled is a boolean representing whether the current stylesheet has been applied or not. stylesheet.href read only re
turns a domstring representing the location of the stylesheet. stylesheet.media read only re
turns a medialist representing the intended destination medium for style information. ...
...cialized cssstylesheet interface. properties stylesheet.disabled is a boolean representing whether the current stylesheet has been applied or not. stylesheet.href read only re
turns a domstring representing the location of the stylesheet. stylesheet.media read only re
turns a medialist representing the intended destination medium for style information. stylesheet.ownernode read only re
turns a node associating this style sheet with the current document. stylesheet.parentstylesheet read only re
turns a stylesheet including this one, if any; re
turns null if there aren't any. ...
...And 2 more matches
SubtleCrypto.deriveKey() - Web APIs
it's worth noting that the three key derivation algorithms you can use have quite different characteristics and are appropriate in quite different situations. see supported algorithms for some more detail on this. ...
...ed to encrypt messages. decrypt: the key may be used to decrypt messages. sign: the key may be used to sign messages. verify: the key may be used to verify signatures. derivekey: the key may be used in deriving a new key. "derivebits": the key may be used in deriving bits. "wrapkey": the key may be used to wrap a key. "unwrapkey": the key may be used to unwrap a key. re
turn value result is a promise that fulfills with a cryptokey. exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the master key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an algorithm that is either unk...
... can try the working examples on github. ecdh in this example alice and bob each generate an ecdh key pair, then exchange public keys. they then use derivekey() to derive a shared aes key, that they could use to encrypt messages. see the complete code on github. ...
...And 2 more matches
TextEncoder - Web APIs
textencoder takes a stream of code points as input and emits a stream of utf-8 bytes. note: there is a polyfill implementation to support non-utf-8 text encodings on github. example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() re
turns a newly constructed textencoder that will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always re
turns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and re
turns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a u...
...rty. textencoder.prototype.encodingread only always re
turns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and re
turns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and re
turns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method. polyfill the below polyfill is compliant with the standard and therefore only supports utf-8. it is designed to work in ie5 "out of the box". however, in ie5-ie9, it will re
turn a regular array instead of a typedarray. in those cases a polyfill might be impractical ...
...these sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. ...
...And 2 more matches
TransformStream - Web APIs
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. ...
...ded as a polyfill for unsupported platforms. ...
...examples include building a pwa with progressive loading and progressive streaming. let responses = [ /* conjoined response tre...
...And 2 more matches
URL - Web APIs
url. you can then easily read the parsed components of the url or make changes to the url. if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property. be sure to check to see if any of your target browsers require this to be prefixed. note: this feature is available in web workers. constructor new url() creates and re
turns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string. properties hash a usvstring containing a '#' followed by the fragment identifier of the url. host a usvstring containing the domain (that is the hostname) followed by (if a port was specified) a ':' and the port of the url. hostname a usvstring containing the domain ...
...fied using an absolute url string, or a relative url string and a base url string. properties hash a usvstring containing a '#' followed by the fragment identifier of the url. host a usvstring containing the domain (that is the hostname) followed by (if a port was specified) a ':' and the port of the url. hostname a usvstring containing the domain of the url. href a stringifier that re
turns a usvstring containing the whole url. origin read only re
turns a usvstring containing the origin of the url, that is its scheme, its domain and its port. password a usvstring containing the password specified before the domain name. pathname a usvstring containing an initial '/' followed by the path of the url. port a usvstring containing the port number of the url. protocol a usvstri...
...earch a usvstring indicating the url's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading ? character. searchparams read only a urlsearchparams object which can be used to access the individual query parameters found in search. username a usvstring containing the username specified before the domain name. ...
...And 2 more matches
VideoTrack.label - Web APIs
the list is filtered to only allow certain track kinds through. ...
...the list is filtered to only allow certain track kinds through. ...
...the list is filtered to only allow certain track kinds through. ...
...And 2 more matches
WebGLRenderingContext.getUniformLocation() - Web APIs
part of the webgl api, the webglrenderingcontext method getuniformlocation() re
turns the location of a specific uniform variable which is part of a given webglprogram. the uniform variable is re
turned as a webgluniformlocation object, which is an opaque identifier used to specify where in the gpu's memory that uniform variable is located. once you have the uniform's location, you can access the uniform itself using one of the other uniform access methods, passing in the uniform location as one of the inputs: getuniform() re
turns the value of the uniform at the given location. uniform[1234][fi][v]() sets the uniform's value to the specified value, which may be a single floating point or integer number, or a 2-4 component vector specified either as a list of values or as a float32array o...
...esented as a sequence of glfloat values or as a float32array. the uniform itself is declared in the shader program using glsl. syntax webgluniformlocation = webglrenderingcontext.getuniformlocation(program, name); parameters program the webglprogram in which to locate the specified uniform variable. name a domstring specifying the name of the uniform variable whose location is to be re
turned. the name can't have any whitespace in it, and you can't use this function to get the location of any uniforms starting with the reserved string "gl_", since those are internal to the webgl layer. the possible values correspond to the uniform names re
turned by getactiveuniform; see that function for specifics on how declared uniforms map to uniform location names. additionally, for unifor...
... the reserved string "gl_", since those are internal to the webgl layer. the possible values correspond to the uniform names re
turned by getactiveuniform; see that function for specifics on how declared uniforms map to uniform location names. additionally, for uniforms declared as arrays, the following names are also valid: the uniform name without the [0] suffix. e.g. the location re
turned for arrayuniform is equivalent to the one for arrayuniform[0]. the uniform name indexed with an integer. e.g. the location re
turned for arrayuniform[2] would point directly to the third entry of the arrayuniform uniform. ...
...And 2 more matches
WebGLRenderingContext.getVertexAttrib() - Web APIs
the webglrenderingcontext.getvertexattrib() method of the webgl api re
turns information about a vertex attribute at a given position. syntax any gl.getvertexattrib(index, pname); parameters index a gluint specifying the index of the vertex attribute. pname a glenum specifying the information to query. possible values: gl.vertex_attrib_array_buffer_binding: re
turns the currently bound webglbuffer. gl.vertex_attrib_array_enabled: re
turns a glboolean that is true if the vertex attribute is enabled at this index. otherwise false. gl.vertex_attrib_array_size: re
turns a glint indicating the size of an element of the vertex array. gl.vertex_attrib_array_stride: re
turns a glint indicating the number of bytes between successive elements in the array. 0 means that the elements are s...
... re
turns a glboolean that is true if the vertex attribute is enabled at this index. otherwise false. gl.vertex_attrib_array_size: re
turns a glint indicating the size of an element of the vertex array. gl.vertex_attrib_array_stride: re
turns a glint indicating the number of bytes between successive elements in the array. 0 means that the elements are sequential. gl.vertex_attrib_array_type: re
turns a glenum representing the array type. one of gl.byte, gl.unsigned_byte, gl.short, gl.unsigned_short, gl.float. gl.vertex_attrib_array_normalized: re
turns a glboolean that is true if fixed-point data types are normalized for the vertex attribute array at the given index. ...
...e elements are sequential. gl.vertex_attrib_array_type: re
turns a glenum representing the array type. one of gl.byte, gl.unsigned_byte, gl.short, gl.unsigned_short, gl.float. gl.vertex_attrib_array_normalized: re
turns a glboolean that is true if fixed-point data types are normalized for the vertex attribute array at the given index. gl.current_vertex_attrib: re
turns a float32array (with 4 elements) representing the current value of the vertex attribute at the given index. ...
...And 2 more matches
Using textures in WebGL - Web APIs
srcformat, srctype, image); // webgl1 has different requirements for power of 2 images // vs non power of 2 images so check if the image is a // power of 2 in both dimensions. if (ispowerof2(image.width) && ispowerof2(image.height)) { // yes, it's a power of 2. generate mips. gl.generatemipmap(gl.texture_2d); } else { // no, it's not a power of 2. ...
...it then uploads a single blue pixel using teximage2d(). ...
...it then uploads a single blue pixel using teximage2d(). this makes the texture immediately usable as a solid blue color even though it may take a few moments for our image to download. ...
...And 2 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
the ability to inspect and obtain information about incoming mediastreamtrack data. a connection's receivers can be obtained by calling rtcpeerconnection.getreceivers(). rtcrtptransceiver an rtcrtptransceiver is a pair of one rtp sender and one rtp receiver which share an sdp mid attribute, which means they share the same sdp media m-line (representing a bidirectional srtp stream). these are re
turned by the rtcpeerconnection.gettransceivers() method, and each mid and transceiver share a one-to-one relationship, with the mid being unique for each rtcpeerconnection. leveraging rtp to implement a "hold" feature because the streams for an rtcpeerconnection are implemented using rtp and the interfaces above, you can take advantage of the access this gives you to the internals of streams to ma...
...for each rtcpeerconnection. leveraging rtp to implement a "hold" feature because the streams for an rtcpeerconnection are implemented using rtp and the interfaces above, you can take advantage of the access this gives you to the internals of streams to make adjustments. ...
... activating hold mode local peer when the local user decides to enable hold mode, the enablehold() method below is called. ...
...And 2 more matches
WindowEventHandlers.onbeforeunload - Web APIs
window.addeventlistener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the beforeunload event, instead of onbeforeunload. example this example prompts the user before unloading. ...
...e this example prompts the user before unloading. the html specification states that authors should use the event.preventdefault() method instead of using event.re
turnvalue to prompt the user. ...
...e user before unloading. the html specification states that authors should use the event.preventdefault() method instead of using event.re
turnvalue to prompt the user. ...
...And 2 more matches
WritableStream.getWriter() - Web APIs
exceptions typeerror the stream you are trying to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. ...
... exceptions typeerror the stream you are trying to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. ...
...ng to create a writer for is not a writablestream. examples the following example illustrates several features of this interface. it shows the creation of the writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const...
...And 2 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
the xrreferencespace interface's getoffsetreferencespace() method re
turns a new reference space object which describes the relative difference in position between the object on which the method is called and a given point in 3d space. the object re
turned by getoffsetreferencespace() is an xrreferencespace if called on an xrreferencespace, or an xrboundedreferencespace if called on an object of that type. in other words, when you have an object in 3d space and need to position another object relative to that one, you can call getoffsetreferencespace(), passing into it the position and orientation you want the second object to have relative to the position and orientation of the object on which you call getoffsetreferencespace(). then, when drawing the scene, you can use the offset referenc...
...ng angle. syntax offsetreferencespace = xrreferencespace.getoffsetreferencespace(originoffset); parameters originoffset an xrrigidtransform specifying the offset to the origin of the new reference space. these values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the newly created xrreferencespace. re
turn value a new xrreferencespace object describing a reference space with the same native origin as the reference space on which the method was called, but with an origin offset indicating the distance from the object to the point given by originoffset. if the object on which you call this method is an xrboundedreferencespace, the re
turned object is one as well. the boundsgeometry of the new refere...
...* mouse_speed; if (mousepitch < -math.pi * 0.5) { mousepitch = -math.pi * 0.5; } else if (mousepitch > math.pi * 0.5) { mousepitch = math.pi * 0.5; } } finally, we need code that actually applies the computed yaw and pitch to the viewer's orientation. ...
...And 2 more matches
XRSession - Web APIs
can poll the viewer's position and orientation (the xrviewerpose), gather information about the user's environment, and present imagery to the user. xrsession supports both inline and immersive virtual and augmented reality modes. properties in addition to the properties listed below, xrsession inherits properties from its parent interface, eventtarget. ...
... renderstate read only an xrrenderstate object which contains options affecting how the imagery is rendered. ...
...ble to the user, and if so, if it's being visible but not currently the target for user events. methods xrsession provides the following methods in addition to those inherited from its parent interface, eventtarget. ...
...And 2 more matches
<color> - CSS: Cascading Style Sheets
shades of a single hue). syntax hsl colors are expressed through the functional hsl() and hsla() notations. note: as of css colors level 4, hsla() is an alias for hsl(). in browsers that implement the level 4 standard, they accept the same parameters and behave the same way. functional notation: hsl[a](h, s, l[, a]) h (hue) is an <angle> of the color circle given in degs, rads, grads, or
turns in css color module level 4. when written as a unitless <number>, it is interpreted as degrees, as specified in css color module level 3. by definition, red=0deg=360deg, with the other colors spread around the circle, so green=120deg, blue=240deg, etc. as an <angle>, it implicitly wraps around such that -120deg=240deg, 480deg=120deg, -1
turn=1
turn, etc. s (saturation) and l (lightness) are perce...
... to adopt that color, allowing you to test our color values. ...
... values. ...
...And 2 more matches
conic-gradient() - CSS: Cascading Style Sheets
ellipse, outward, in all directions. a conic gradient is specified by indicating a rotation angle, the center of the gradient, and then specifying a list of color-stops. unlike linear and radial gradients, whose color-stops are placed by specifying a length, the color-stops of a conic gradient are specified with an angle. units include deg for degrees, grad for gradients, rad for radians, and
turn for
turns. there are 360 degrees, 400 gradians, 2π radians, and 1
turn in a circle. browsers supporting conic gradients also accept percent values, with 100% equaling 360 degrees, but this is not in the specification. similar to radial gradients, the conic gradient syntax provides for positioning the center of the gradient anywhere within, or even outside, the image. the values for the position...
...color at the subsequent color stop, with the midpoint between the colors being the half way point between the color transition. you can move this color transition midpoint to any point between two color stops by adding a color hint, indicating where the middle of the color transition should be. the following is solid red from the start to the 10% mark, transitions from red to blue over 80% of the
turn, with the final 10% being solid blue. the midpoint of the red to blue gradient change, however, is at the 20% mark rather than the 50% mark as would have happened without the 80grad, or 20%, color hint. conic-gradient(red 40grad, 80grad, blue 360grad); if two or more color stops are at the same location, the transition will be a hard line between the first and last colors declared at that locat...
...declared at that location. to use conic gradients to create pie charts --- which is not the correct way to create pie charts as background images are not accessible -- use hard color stops, where the color stop angles for two adjacent color stops are the same. the easiest way to do this is to use multip position colors stops. the following two declarations are equivalent: conic-gradient(#fff 0.09
turn, #bbb 0.09
turn, #bbb 0.27
turn, #666 0.27
turn, #666 0.54
turn, #000 0.54
turn); conic-gradient(#fff 0
turn 0.09
turn, #bbb 0.09
turn 0.27
turn, #666 0.27
turn 0.54
turn, #000 0.54
turn 1
turn); color stops should be listed in ascending order. subsequent color stops of lower value will override the value of the previous color stop creating a hard transition. the following changes from red to yellow at the 3...
...And 2 more matches
Sets (set) - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt sets package offers functions that let you perform set manipulation. the namespace for these functions is http://exslt.org/sets. set:difference()set:difference() re
turns the difference between two node-sets. ...
... xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt sets package offers functions that let you perform set manipulation. the namespace for these functions is http://exslt.org/sets. set:difference()set:difference() re
turns the difference between two node-sets. ...
...t elements, exslt functions, xpath functions, xpath axes the exslt sets package offers functions that let you perform set manipulation. the namespace for these functions is http://exslt.org/sets. set:difference()set:difference() re
turns the difference between two node-sets. ...
...And 2 more matches
Getting Started - Developer guides
/ perfect! } else { // there was a problem with the request. // for example, the response may have a 404 (not found) // or 500 (internal server error) response code. } after checking the state of the request and 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 – re
turns the server response as a string of text httprequest.responsexml – re
turns 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 di...
...php files should be placed in the same directory. ...
...cript> in this example: the user clicks the "make a request" button; the event handler calls the makerequest() function; the request is made and then (onreadystatechange) the execution is passed to alertcontents(); alertcontents() checks if the response was received and ok, then alert()s the contents of the test.html file. note: if you're sending a request to a piece of code that will re
turn xml, rather than a static html file, you must set response headers to work in internet explorer. if you do not set header content-type: application/xml, ie will throw a javascript "object expected" error after the line where you tried to access an xml element. note 2: if you do not set header cache-control: no-cache the browser will cache the response and never re-submit the request, making debu...
...And 2 more matches
Media buffering, seeking, and time ranges - Developer guides
sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. buffered the buffered attribute will tell us which parts of the media has been downloaded. it re
turns a timeranges object, which will tell us which chunks of media have been downloaded. this is usually contiguous but if the user jumps about while media is buffering, it may contain holes. this will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> we can access these attributes like so: var myaudio = document.g...
... the second spanning 15 to 19 seconds. ...
...------------------------------------------------------ |=============| |===========| | ------------------------------------------------------ 0 5 15 19 21 for this audio instance, the associated timeranges object would have the following available properties: myaudio.buffered.length; // re
turns 2 myaudio.buffered.start(0); // re
turns 0 myaudio.buffered.end(0); // re
turns 5 myaudio.buffered.start(1); // re
turns 15 myaudio.buffered.end(1); // re
turns 19 to try out and visualize buffered time ranges we can write a little bit of html: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of...
...And 2 more matches
<input type="url"> - HTML: Hypertext Markup Language
e other explanatory text nearby. see the section pattern validation for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...lcheck are: false disable spell checking for this element. true enable spell checking for this element. "" (empty string) or no value follow the element's default behavior for spell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value re
turned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. non-standard attributes the following non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indic...
...lowing non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indicating whether or not autocorrect is on or off. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses the enter or re
turn key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. firefox for android only. autocorrect a safari extension, the autocorrect attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. permitted values are: on enable automatic correction of typos, as well as ...
...And 2 more matches
Regular expressions - JavaScript
that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level. /a\*b/ and new regexp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" followed by "b". if escape strings are not already part of your pattern you can add them using string.replace: function escaperegexp(string) { re
turn string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } the "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and re
turning all matches. it is explained in detail below in advanced searching with flags. why isn't this built into javascript? there is a proposal to add such a function to regexp, but it...
...etails. using regular expressions in javascript regular expressions are used with the regexp methods test() and exec() and with the string methods match(), replace(), search(), and split(). these methods are explained in detail in the javascript reference. methods that use regular expressions method description exec() executes a search for a match in a string. it re
turns an array of information or null on a mismatch. test() tests for a match in a string. it re
turns true or false. match() re
turns an array containing all of the matches, including capturing groups, or null if no match is found. matchall() re
turns an iterator containing all of the matches, including capturing groups. search() tests for a match in a str...
... replace() executes a search for a match in a string, and replaces the matched substring with a replacement substring. ...
...And 2 more matches
The legacy Iterator protocol - JavaScript
the deprecated firefox-only iterator protocol firefox, prior to version 26 implemented another iterator protocol that is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration. ...
...iterator protocol that is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration. property value next a zero arguments function that re
turns an value. ...
...is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration. property value next a zero arguments function that re
turns an value. ...
...And 2 more matches
Warning: expression closures are deprecated - JavaScript
on closures are deprecated error type warning. javascript execution won't be halted. what went wrong? the non-standard expression closure syntax (shorthand function syntax) is deprecated and shouldn't be used anymore. this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntaxerror then. ...
...scripts using it will throw a syntaxerror then. examples deprecated syntax expression closures omit curly braces or re
turn statements from function declarations or from method definitions in objects. var x = function() 1; var obj = { count: function() 1 }; standard syntax to convert the non-standard expression closures syntax to standard ecmascript syntax, you can add curly braces and re
turn statements. ...
... then. examples deprecated syntax expression closures omit curly braces or re
turn statements from function declarations or from method definitions in objects. var x = function() 1; var obj = { count: function() 1 }; standard syntax to convert the non-standard expression closures syntax to standard ecmascript syntax, you can add curly braces and re
turn statements. ...
...And 2 more matches
SyntaxError: Malformed formal parameter - JavaScript
like a number or object. ok, that fixed my problem. but why didn't you say that in the first place? admittedly the wording in the error message is slightly strange. "formal parameter" is a fancy way of saying "function argument". and we use the word "malformed" because all firefox engineers are huge fans of 19th-century gothic horror novels. ...
...y that in the first place? admittedly the wording in the error message is slightly strange. "formal parameter" is a fancy way of saying "function argument". and we use the word "malformed" because all firefox engineers are huge fans of 19th-century gothic horror novels. ...
...rd "malformed" because all firefox engineers are huge fans of 19th-century gothic horror novels. ...
...And 2 more matches
Rest parameters - JavaScript
ount of its elements is given by the length property: function fun1(...theargs) { console.log(theargs.length) } fun1() // 0 fun1(5) // 1 fun1(5, 6, 7) // 3 ordinary parameter and rest parameters in the next example, a rest parameter is used to collect all parameters after the first into an array. ...
...nction fun1(...theargs) { console.log(theargs.length) } fun1() // 0 fun1(5) // 1 fun1(5, 6, 7) // 3 ordinary parameter and rest parameters in the next example, a rest parameter is used to collect all parameters after the first into an array. ...
...log(theargs.length) } fun1() // 0 fun1(5) // 1 fun1(5, 6, 7) // 3 ordinary parameter and rest parameters in the next example, a rest parameter is used to collect all parameters after the first into an array. ...
...And 2 more matches
Array.prototype.lastIndexOf() - JavaScript
the array is searched backwards, starting at fromindex. 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 arr.lastindexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index at which to start searching backwards. defaults to the array's length minus one (arr.length - 1), i.e. the whole array will be searched. ...
...aults to the array's length minus one (arr.length - 1), i.e. the whole array will be searched. if the index is greater than or equal to the length of the array, the whole array will be searched. if negative, it is taken as the offset from the end of the array. note that even when the index is negative, the array is still searched from back to front. if the calculated index is less than 0, -1 is re
turned, i.e. the array will not be searched. re
turn value the last index of the element in the array; -1 if not found. description lastindexof compares searchelement to elements of the array using strict equality (the same method used by the ===, or triple-equals, operator). polyfill lastindexof was added to the ecma-262 standard in the 5th edition; as such it may not be present in other imple...
...math.min(n, len - 1) : len - math.abs(n); k >= 0; k--) { if (k in t && t[k] === searchelement) { retur...
...And 2 more matches
Array.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. ...
... this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. ...
... this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. ...
...And 2 more matches
Atomics.notify() - JavaScript
exceptions throws a typeerror, if typedarray is not a int32array. ...
... exceptions throws a typeerror, if typedarray is not a int32array. throws a rangeerror, if index is out of bounds in the typedarray. ...
... exceptions throws a typeerror, if typedarray is not a int32array. throws a rangeerror, if index is out of bounds in the typedarray. ...
...And 2 more matches
BigInt.prototype.toString() - JavaScript
exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. ...
...e 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 bigintobj.tostring([radix]) parameters radixoptional optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. ...
...for radixes above 10, the letters of the alphabet indicate numerals greater than 9. for example, for hexadecimal numbers (base 16) a through f are used. ...
...And 2 more matches
BigInt - JavaScript
safe * 2n // ↪ 18014398509481982n const subtr = multi – 10n // ↪ 18014398509481972n const mod = multi % 10n // ↪ 2n const bign = 2n ** 54n // ↪ 18014398509481984n bign * -1n // ↪ –18014398509481984n the / operator also works as expected with whole numbers. however, since these are bigints and not bigdecimals, this operation will round towards 0 (which is to say, it will not re
turn any fractional digits). an operation with a fractional result will be truncated when used with a bigint. const expected = 4n / 2n // ↪ 2n const rounded = 5n / 2n // ↪ 2n, not 2.5n comparisons a bigint is not strictly equal to a number, but it is loosely so: 0n === 0 // ↪ false 0n == 0 // ↪ true a number and a bigint may be compared as usual: 1n < 2 // ↪ true 2n > 1 // ↪ ...
...ean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a new bigint value. static methods bigint.asintn() wraps a bigint value to a signed integer between -2width-1 and 2width-1 - 1. bigint.asuintn() wraps a bigint value to an unsigned integer between 0 and 2width - 1. instance methods bigint.prototype.tolocalestring() re
turns a string with a language-sensitive representation of this number. overrides the object.prototype.tolocalestring() method. bigint.prototype.tostring() re
turns a string representing the specified object in the specified radix (base). overrides the object.prototype.tostring() method. bigint.prototype.valueof() re
turns the primitive value of the specified object. overrides the object.prototype.v...
...ce between the two types. cryptography the operations supported on bigints are not constant time. bigint is therefore unsuitable for use in cryptography. use within json using json.stringify() with any bigint value will raise a typeerror as bigint values aren't serialized in json by default. ...
...And 2 more matches
Function - JavaScript
constructor function() creates a new function object. calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. however, unlike eval, the function constructor creates functions that execute in the global scope only. instance properties function.arguments an array corresponding to the arguments passed to a function. this is deprecated as a property of function. ...
...argn]]]) creates a new function which, when called, has its this set to the provided thisarg. optionally, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called. function.prototype.call(thisarg[, arg1, arg2, ...argn]) calls a function and sets its this to the provided value. arguments can be passed as they are. function.prototype.tostring() re
turns a string representing the source code of the function. overrides the object.prototype.tostring method. examples difference between function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local vari...
... not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the function constructor was created. this is different from using eval with code for a function expression. ...
...And 2 more matches
Generator.prototype.next() - JavaScript
has the value false if the iterator was able to produce the next value in the sequence. ...
...s an object with two properties done and value. you can also provide a parameter to the next method to send a value to the generator. syntax gen.next(value) parameters value the value to send to the generator. the value will be assigned as a result of a yield expression. for example, in variable = yield expression, the value passed to the .next() function will be assigned to variable. ...
...value to send to the generator. the value will be assigned as a result of a yield expression. for example, in variable = yield expression, the value passed to the .next() function will be assigned to variable. re
turn value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the re
turn value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. ...
...And 2 more matches
Generator - JavaScript
generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). ...
... generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). ...
... generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). ...
...And 2 more matches
Intl.Collator.supportedLocalesOf() - JavaScript
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 intl.collator.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ollowing property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in collation, ...
...And 2 more matches
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
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 intl.datetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ty: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese...
...And 2 more matches
Intl.DisplayNames.supportedLocalesOf() - JavaScript
the intl.displaynames.supportedlocalesof() method re
turns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale. syntax intl.displaynames.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ty: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese...
...And 2 more matches
Intl.ListFormat.supportedLocalesOf() - JavaScript
the intl.listformat.supportedlocalesof() method re
turns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale. syntax intl.listformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ty: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese...
...And 2 more matches
Intl.Locale - JavaScript
ype. traditionally, the intl api used strings to represent locales, just as unicode does. this is a simple and lightweight solution that works well. adding a locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. constructor intl.locale() creates a new locale object. ...
...works well. adding a locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. constructor intl.locale() creates a new locale object. instance properties intl.locale.prototype.basename re
turns basic, core information about the locale in the form of a substring of the complete data string. intl.locale.prototype.calendar re
turns the part of the locale that indicates the locale's calendar era. ...
... region, as well as extension tags. constructor intl.locale() creates a new locale object. instance properties intl.locale.prototype.basename re
turns basic, core information about the locale in the form of a substring of the complete data string. intl.locale.prototype.calendar re
turns the part of the locale that indicates the locale's calendar era. intl.locale.prototype.casefirst re
turns whether case is taken into account for the locale's collation rules. intl.locale.prototype.collation re
turns the collation type for the locale, which is used to order strings according to the locale's rules. intl.locale.prototype.hourcycle re
turns the time keeping format convention used by the locale. intl.locale.prototype.language re
turns the language associated with the locale. intl.loc...
...And 2 more matches
Intl.NumberFormat.prototype.formatToParts() - JavaScript
the intl.numberformat.prototype.formattoparts() method allows locale-aware formatting of strings produced by numberformat formatters. syntax intl.numberformat.prototype.formattoparts(number) parameters number optional a number or bigint to format. re
turn value an array of objects containing the formatted number in parts. description the formattoparts() method is useful for custom formatting of number strings. ...
...e.formattoparts() method allows locale-aware formatting of strings produced by numberformat formatters. syntax intl.numberformat.prototype.formattoparts(number) parameters number optional a number or bigint to format. re
turn value an array of objects containing the formatted number in parts. description the formattoparts() method is useful for custom formatting of number strings. it re
turns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. ...
... decimal the decimal separator string ("."). ...
...And 2 more matches
Intl.NumberFormat.supportedLocalesOf() - JavaScript
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 intl.numberformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
... property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in number formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in num...
...And 2 more matches
Intl.PluralRules.supportedLocalesOf() - JavaScript
the intl.pluralrules.supportedlocalesof() method re
turns an array containing those of the provided locales that are supported in plural formatting without having to fall back to the runtime's default locale. syntax intl.pluralrules.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are lookup and best fit; the default is best fit. for information about this option, see the intl page. ...
... locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are lookup and best fit; the default is best fit. for information about this option, see the intl page. ...
...lowing property: localematcher the locale matching algorithm to use. possible values are lookup and best fit; the default is best fit. for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in plural formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in plural formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof() assuming a runtime that supports indonesian and german but not balinese in p...
...And 2 more matches
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
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 intl.relativetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. ...
...ales a string with a bcp 47 language tag, or an array of such strings. for the general form of the locales argument, see the intl page. options optional. an object that may have the following property: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. ...
...ty: localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. re
turn value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale. description re
turns an array with a subset of the language tags provided in locales. the language tags re
turned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese...
...And 2 more matches
Math.floor() - JavaScript
the math.floor() function re
turns the largest integer less than or equal to a given number. 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 math.floor(x) parameters x a number. re
turn value a number representing the largest integer less than or equal to the specified number. description because floor() is a static method of math, you always use it as math.floor(), rather than as a method of a math object you created (math is not a constructor). note: math.floor(null) re
turns 0, not a nan. examples using math.floor() math.floor( 45.95); // 45 math.floor( 45.05); // 45 math.floor( 4 ); // ...
...les using math.floor() math.floor( 45.95); // 45 math.floor( 45.05); // 45 math.floor( 4 ); // 4 math.floor(-45.05); // -46 math.floor(-45.95); // -46 decimal adjustment /** * decimal adjustment of a number. * * @param {string} type the type of adjustment. * @param {number} value the number. * @param {integer} exp the exponent (the 10 logarithm of the adjustment base). ...
...nt /** * decimal adjustment of a number. * * @param {string} type the type of adjustment. * @param {number} value the number. * @param {integer} exp the exponent (the 10 logarithm of the adjustment base). * @re
turns {number} the adjusted value. */ function decimaladjust(type, value, exp) { // if the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { re
turn math[type](value); } value = +value; exp = +exp; // if the value is not a number or the exp is not an integer... ...
...And 2 more matches
Math.log1p() - JavaScript
description for very small values of x, adding 1 can reduce or eliminate precision. the double floats used in js give you about 15 digits of precision. ...
... + a number, that is ∀x>-1,math.log1p(x)=ln(1+x)\forall x > -1, \mathtt{\operatorname{math.log1p}(x)} = \ln(1 + x) 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 math.log1p(x) parameters x a number. re
turn value the natural logarithm (base e) of 1 plus the given number. if the number is less than -1, nan is re
turned. description for very small values of x, adding 1 can reduce or eliminate precision. the double floats used in js give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits pas...
... up taking the logarithm of 1.00000000000000111022 (the roundoff is in binary so sometimes it gets ugly), so you get the answer 1.11022...e-15, with only 3 correct digits. if, instead, you calculate math.log1p(1.1111111111e-15) you will get a much more accurate answer 1.1111111110999995e-15 with 15 correct digits of precision (actually 16 in this case). ...
...And 2 more matches
Math.max() - JavaScript
description because math is not a constructor, max() is a static method of math (you always use it as math.max(), rather than as a method of an instanced math object). ...
... description because math is not a constructor, max() is a static method of math (you always use it as math.max(), rather than as a method of an instanced math object). ...
... 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 math.max([value1[, value2[, ...]]]) parameters value1, value2, ... numbers. re
turn value the largest of the given numbers. if at least one of the arguments cannot be converted to a number, nan is re
turned. description because math is not a constructor, max() is a static method of math (you always use it as math.max(), rather than as a method of an instanced math object). -infinity is the initial comparant because almost every other value is bigger, that's why when no arguments are given, -infinity is re
turned. if at least one of arguments cannot be converted to a number, the result is nan. ...
...And 2 more matches
Math.random() - JavaScript
the math.random() function re
turns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. the implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. math.random() does not provide cryptographically secure random numbers. do not use them for anything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues() method. syntax math.random() re
turn value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-t...
...e 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. ...
...d for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { re
turn math.random(); } getting a random number between two values this example re
turns a random number between the specified values. the re
turned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. function getrandomarbitrary(min, max) { re
turn math.random() * (max - min) + min; } getting a random integer between two values this example re
turns a random integer between the specified values. the value is no lower than min (or the next in...
...And 2 more matches
Math.random() - JavaScript
the math.random() function re
turns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. the implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. math.random() does not provide cryptographically secure random numbers. do not use them for anything related to security. use the web crypto api instead, and more precisely the window.crypto.getrandomvalues() method. syntax math.random() re
turn value a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). examples note that as numbers in javascript are ieee 754 floating point numbers with round-t...
...e 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. ...
...d for the functions below (excluding the one for math.random() itself) aren't exact. if extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { re
turn math.random(); } getting a random number between two values this example re
turns a random number between the specified values. the re
turned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. function getrandomarbitrary(min, max) { re
turn math.random() * (max - min) + min; } getting a random integer between two values this example re
turns a random integer between the specified values. the value is no lower than min (or the next in...
...And 2 more matches
Number.prototype.toFixed() - JavaScript
ive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax numobj.tofixed([digits]) parameters digits optional the number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. if this argument is omitted, it is treated as 0. ...
...ated as 0. re
turn value a string representing the given number using fixed-point notation. exceptions rangeerror if digits is too small or too large. values between 0 and 100, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as chosen. typeerror if this method is invoked on an object that is not a number. description tofixed() re
turns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place. the number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. ...
... tofixed() re
turns a string representation of numobj that does not use exponential notation and has exactly digits digits after the decimal place. the number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. if the absolute value of numobj is greater or equal to 1e+21, this method simply calls number.prototype.tostring() and re
turns a string in exponential notation. warning: floating point numbers cannot represent all decimals precisely in binary. this can lead to unexpected results, such as 0.1 + 0.2 === 0.3 re
turning false . ...
...And 2 more matches
Number.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string with a language-sensitive representation of this number. 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 numobj.tolocalestring([locales [, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent. see the intl.numberformat() constructor for details on these parameters and how to use ...
...tions arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent. see the intl.numberformat() constructor for details on these parameters and how to use them. re
turn value a string with a language-sensitive representation of the given number. ...
... var number = 3500; console.log(number.tolocalestring()); // displays "3,500" if in u.s. english locale checking for support for locales and options arguments the locales and options arguments are not supported in all browsers yet. ...
...And 2 more matches
Number.prototype.toString() - JavaScript
exceptions rangeerror if tostring() is given a radix less than 2 or greater than 36, a rangeerror is thrown. description the number object overrides the tostring() method of the object object. ...
...ject. 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 numobj.tostring([radix]) parameters radix optional. an integer in the range 2 through 36 specifying the base to use for representing numeric values. ...
...for radices above 10, the letters of the alphabet indicate numerals greater than 9. for example, for hexadecimal numbers (base 16), a through f are used. ...
...And 2 more matches
Object.create() - JavaScript
propertiesobject optional if specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. these properties correspond to the second argument of object.defineproperties(). re
turn value a new object with the specified prototype object and properties. exceptions the proto parameter has to be either null or an object excluding primitive wrapper objects. if proto is neither of these a typeerror is thrown. custom and null objects a new object created from a completely custom object (especially one created from the null object, which is basically a custom object with...
... as here, but also dynamically via whatever the order any such property-adding code-branches actually get executed at runtime as depends on inputs and/or random-variables. then again, the actual iteration order is not guaranteed no matter what the order members are added. be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being re
turned. var obj = object.create({ a: 1, b: 2 }); > console.log(object.entries(obj)); // shows "[]" some non-solutions a good solution for the missing object-methods is not immediately apparent. adding the missing object-method directly from the standard-object does not work: ocn = object.create( null ); // create "null" object (same as before) ocn.tostring = object.tostring; // since new objec...
...this is for a single inheritance, which is all that javascript supports. // shape - superclass function shape() { this.x = 0; this.y = 0; } // superclass method shape.prototype.move = function(x, y) { this.x += x; this.y += y; co...
...And 2 more matches
Object.freeze() - JavaScript
a frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. in addition, freezing an object also prevents its prototype from being changed. freeze() re
turns the same object that was passed in. 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 object.freeze(obj) parameters obj the object to freeze. re
turn value the object that was passed to the function. desc...
...figurable attributes are set to false. accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). note that values that are objects can still be modified, unless they are also frozen. as an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() re
turns the same object that was passed into the function. it does not create a frozen copy. in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply re
turned. > object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 ...
...eir existing properties changed. existing properties in objects frozen with object.freeze() are made immutable. examples freezing objects var obj = { prop: function() {}, foo: 'bar' }; // before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // freeze. var o = object.freeze(obj); // the re
turn value is just the same object we passed in. o === obj; // true // the object has become frozen. object.isfrozen(obj); // === true // now any changes will fail obj.foo = 'quux'; // silently does nothing // silently doesn't add the property obj.quaxxor = 'the friendly duck'; // in strict mode such attempts will throw typeerrors function fail(){ 'use strict'; obj.foo = 'sparky'; // throws a t...
...And 2 more matches
Object.prototype.valueOf() - JavaScript
a (unary) plus sign can sometimes be used as a shorthand for valueof, e.g. in +new number()). also see using unary plus. description javascript calls the valueof method to convert an object to a primitive value. you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. ...
...unary plus. description javascript calls the valueof method to convert an object to a primitive value. you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. by default, the valueof method is inherited by every object descended from object. every built-in core object overrides this method to re
turn an appropriate value. if an object has no primitive value, valueof re
turns the object itself. you can use valueof within your own code to convert a built-in object into a primitive value. when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method. overriding valueof for custom objects you can create a function to be...
...t object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and you want to create a valueof method for it. the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { re
turn customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code. an object's valueof method is usually invoked by javascript, but you can invoke it yourself as follows: mynumbertype.valueof() note: objects in str...
...And 2 more matches
handler.getPrototypeOf() - JavaScript
ored 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 p = new proxy(obj, { getprototypeof(target) { ... } }); parameters the following parameter is passed to the getprototypeof() method. this is bound to the handler. target the target object. re
turn value the getprototypeof() method must re
turn an object or null. description interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a typeerror: getprototypeof() method must re
turn an object or null. if ...
...escription interceptions this trap can intercept these operations: object.getprototypeof() reflect.getprototypeof() __proto__ object.prototype.isprototypeof() instanceof invariants if the following invariants are violated, the proxy will throw a typeerror: getprototypeof() method must re
turn an object or null. if target is not extensible, object.getprototypeof(proxy) method must re
turn the same value as object.getprototypeof(target). ...
...ror: getprototypeof() method must re
turn an object or null. if target is not extensible, object.getprototypeof(proxy) method must re
turn the same value as object.getprototypeof(target). ...
...And 2 more matches
Reflect - JavaScript
unction with arguments as specified by the argumentslist parameter. see also function.prototype.apply(). reflect.construct(target, argumentslist[, newtarget]) the new operator as a function. equivalent to calling new target(...argumentslist). also provides the option to specify a different prototype. reflect.defineproperty(target, propertykey, attributes) similar to object.defineproperty(). re
turns a boolean that is true if the property was successfully defined. reflect.deleteproperty(target, propertykey) the delete operator as a function. equivalent to calling delete target[propertykey]. reflect.get(target, propertykey[, receiver]) re
turns the value of the property. works like getting a property from an object (target[propertykey]) as a function. reflect.getownpropertydescriptor(targ...
... reflect.deleteproperty(target, propertykey) the delete operator as a function. equivalent to calling delete target[propertykey]. reflect.get(target, propertykey[, receiver]) re
turns the value of the property. works like getting a property from an object (target[propertykey]) as a function. reflect.getownpropertydescriptor(target, propertykey) similar to object.getownpropertydescriptor(). re
turns a property descriptor of the given property if it exists on the object, undefined otherwise. reflect.getprototypeof(target) same as object.getprototypeof(). reflect.has(target, propertykey) re
turns a boolean indicating whether the target has the property. either as own or inherited. works like the in operator as a function. reflect.isextensible(target) same as object.isextensible(). retur...
...d otherwise. reflect.getprototypeof(target) same as object.getprototypeof(). reflect.has(target, propertykey) re
turns a boolean indicating whether the target has the property. either as own or inherited. works like the in operator as a function. reflect.isextensible(target) same as object.isextensible(). re
turns a boolean that is true if the target is extensible. reflect.ownkeys(target) re
turns an array of the target object's own (not inherited) property keys. reflect.preventextensions(target) similar to object.preventextensions(). re
turns a boolean that is true if the update was successful. reflect.set(target, propertykey, value[, receiver]) a function that assigns values to properties. re
turns a boolean that is true if the update was successful. reflect.setprototypeof(target, pr...
...And 2 more matches
String.prototype.localeCompare() - JavaScript
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 new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent. ...
...comparestring[, locales[, options]]) parameters comparestring the string against which the referencestr is compared. locales and options these arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
... these arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent. see the intl.collator() constructor for details on these parameters and how to use them. re
turn value a negative number if referencestr occurs before comparestring; positive if the referencestr occurs after comparestring; 0 if they are equivalent. description re
turns an integer indicating whether the referencestr comes before, after or is equivalent to the comparestring. negative when the referencestr occurs before comparestring positive when the referencestr occurs after comparestri...
...And 2 more matches
WeakMap - JavaScript
rable. there is no method to obtain a list of the keys. if they were, the list would depend on the state of garbage collection, introducing non-determinism. if you want to have a list of keys, you should use a map. constructor weakmap() creates a new weakmap object. instance methods weakmap.prototype.delete(key) removes any value associated to the key. weakmap.prototype.has(key) will re
turn false afterwards. weakmap.prototype.get(key) re
turns the value associated to the key, or undefined if there is none. weakmap.prototype.has(key) re
turns a boolean asserting whether a value has been associated to the key in the weakmap object or not. weakmap.prototype.set(key, value) sets the value for the key in the weakmap object. re
turns the weakmap object. examples using weakmap const...
... ...
... ...
...And 2 more matches
encodeURIComponent() - JavaScript
nly be four escape sequences for characters composed of two "surrogate" characters). 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 encodeuricomponent(str); parameters str string. a component of a uri. re
turn value a new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ! ~ * ' ( ) encodeuricomponent() differs from encodeuri as follows: var set1 = ";,/?:@&=+$"; // reserved characters var set2 = "-_.!~*'()"; // unescaped characters var set3 = "#"; // number sign var...
...n/x-www-form-urlencoded, spaces are to be replaced by "+", so one may wish to follow a encodeuricomponent() replacement with an additional replacement of "%20" with "+". ...
... wish to follow a encodeuricomponent() replacement with an additional replacement of "%20" with "+". ...
...And 2 more matches
globalThis - JavaScript
different syntax in different javascript environments. on the web you can use window, self, or frames - but in web workers only self will work. in node.js none of these work, and you must instead use global. the this keyword could be used inside functions running in non–strict mode, but this will be undefined in modules and inside functions running in strict mode. you can also use function('re
turn this')(), but environments that disable eval(), like csp in browsers, prevent use of function in this way. the globalthis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. in this way, you can access the global o...
...g several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. see the language proposal's "naming" document for more details. ...
...l's "naming" document for more details. examples search for the global across environments prior to globalthis, the only reliable cross-platform way to get the global object for an environment was function('re
turn this')(). ...
...And 2 more matches
void operator - JavaScript
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 void expression description this operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired. the void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). in these cases, the global variable undefined can be used. ...
...sed merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). in these cases, the global variable undefined can be used. it should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', re
turns false void (2 == '2'); // void (2 == '2'), re
turns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }(); // output: "executed!" executing the above function without th...
...function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }(); // output: "executed!" executing the above function without the void keyword will result in an uncaught syntaxerror. javascript uris when a browser follows a javascript: uri, it evaluates the code in the uri and then replaces the contents of the page with the re
turned value, unless the re
turned value is undefined. the void operator can be used to re
turn undefined. for example: <a href="javascript:void(0);"> click here to do nothing </a> <a href="javascript:void(document.body.style.backgroundcolor='green');"> click here for green background </a> note: javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handle...
...And 2 more matches
Expressions and operators - JavaScript
rement postfix/prefix increment and postfix/prefix decrement operators. a++ postfix increment operator. a-- postfix decrement operator. ++a prefix increment operator. --a prefix decrement operator. unary operators a unary operation is operation with only one operand. delete the delete operator deletes a property from an object. void the void operator discards an expression's re
turn value. typeof the typeof operator determines the type of a given object. + the unary plus operator converts its operand to number type. - the unary negation operator converts its operand to number type and then negates it. ~ bitwise not operator. ! logical not operator. arithmetic operators arithmetic operators take numerical values (either literals or variables) as their operands an...
...ue. typeof the typeof operator determines the type of a given object. + the unary plus operator converts its operand to number type. - the unary negation operator converts its operand to number type and then negates it. ~ bitwise not operator. ! logical not operator. arithmetic operators arithmetic operators take numerical values (either literals or variables) as their operands and re
turn a single numerical value. + addition operator. - subtraction operator. / division operator. * multiplication operator. % remainder operator. ** exponentiation operator. relational operators a comparison operator compares its operands and re
turns a boolean value based on whether the comparison is true. in the in operator determines whether an object has a given property. inst...
...== equality operator. != inequality operator. === identity operator. !== nonidentity operator. bitwise shift operators operations to shift all bits of the operand. << bitwise left shift operator. >> bitwise right shift operator. >>> bitwise unsigned right shift operator. ...
...And 2 more matches
for await...of - JavaScript
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. ...
...ned to variable. variable may be declared with const, let, or var. iterable object whose iterable properties are to be iterated over. ...
... object whose iterable properties are to be iterated over. examples iterating over async iterables you can also iterate over an object that explicitly implements async iterable protocol: const asynciterable = { [symbol.asynciterator]() { re
turn { i: 0, next() { if (this.i < 3) { re
turn promise.resolve({ value: this.i++, done: false }); } re
turn promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asynciterable) { console.log(num); } })(); // 0 // 1 // 2 iterating over async generators since the re
turn values of async generators conform to the async iterable protocol, they can be looped using for await...of. async function* asyncgenerator() { let i = 0; while (i < 3) { ...
...And 2 more matches
throw - JavaScript
e userexception and uses it in a throw statement. ...
... * * if the argument passed to the zipcode constructor does not * conform to one of these patterns, an exception is thrown. ...
...nform to one of these patterns, an exception is thrown. */ function zipcode(zip) { zip = new string(zip); pattern = /[0-9]{5}([- ]?[0-9]{4})?/; if (pattern.test(zip)) { // zip code value will be the first match in the string this.value = zip.match(pattern)[0]; this.valueof = function() { re
turn this.value }; this.tostring = function() { re
turn string(this.value) }; } else { throw new zipcodeformatexception(zip); } } function zipcodeformatexception(value) { this.value = value; this.message = 'does not conform to the expected format for a zip code'; this.tostring = function() { re
turn this.value + this.message; }; } /* * this could be in a script that validates address data * for us addresses. */ ...
...And 2 more matches
Performance fundamentals - Web Performance
ormance means efficiency. in the context of open web apps, this document explains in general what performance is, how the browser platform helps improve it, and what tools and processes you can use to test and improve it. what is performance? ultimately, user-perceived performance is the only performance that matters. users provide inputs to the system through touch, movement, and speech. in re
turn, they perceive outputs through sight, touch, and hearing. performance is the quality of system outputs in response to user inputs. all other things being equal, code optimized for some target besides user-perceived performance (hereafter upp) loses when competing against code optimized for upp. users prefer, say, a responsive, smooth app that only processes 1,000 database transactions per second...
...ser's eyes, by delivering photons to them that mimic reality. for example, paper covered with printed text reflects photons to the user's eyes in some pattern. by manipulating pixels, a reader app emits photons in a similar pattern to "fool" the user's eyes. as your brain infers, motion is not jerky and discrete, but rather "updates" smoothly and continuously. (strobe lights are fun because they
turn that upside down, starving your brain of inputs to create the illusion of discrete reality). on a computer display, a higher framerate simply makes for a more faithful imitation of reality. note: humans usually cannot perceive differences in framerate above 60hz. that's why most modern electronic displays are designed to refresh at that rate. a television probably looks choppy and unrealistic t...
... would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware. complex scenes are rendered using the device's gpu for maximum performance. ...
...And 2 more matches
XPath snippets - XPath
function the following custom utility function can be used to evaluate xpath expressions on given xml nodes. the first argument is a dom node or document object, while the second is a string defining an xpath expression. example: defining a custom node-specific evaluatexpath() utility function // evaluate an xpath expression aexpression against a given dom node // or document object (anode), re
turning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work. function evaluatexpath(anode, aexpr) { var xpe = new xpathevaluator(); var nsresolver = xpe.creatensresolver(anode.ownerdocument == null ? anode.documentelement : anode.ownerdocument.documentelement); var result = xpe.evaluate(aexpr, anode, nsresolver, 0, null); var found = [];...
...il dot com for the // initial work. function evaluatexpath(anode, aexpr) { var xpe = new xpathevaluator(); var nsresolver = xpe.creatensresolver(anode.ownerdocument == null ? anode.documentelement : anode.ownerdocument.documentelement); var result = xpe.evaluate(aexpr, anode, nsresolver, 0, null); var found = []; var res; while (res = result.iteratenext()) found.push(res); re
turn found; } this function uses the new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer. scripts in a web document which might be accessed by edge or internet explorer users should replace the call to new xpathevaluator() with the following fragment: // xpathevaluator is implemented on objects that implement document v...
...contains(@street, 'south')]"); alert(results.length); docevaluatearray the following is a simple utility function to get (ordered) xpath results into an array, regardless of whether there is a special need for namespace resolvers, etc. it avoids the more complex syntax of document.evaluate() for cases when it is not required as well as the need to use the special iterators on xpathresult (by re
turning an array instead). example: defining a simple docevaluatearray() utility function // example usage: // var els = docevaluatearray('//a'); // alert(els[0].nodename); // gives 'a' in html document with at least one link function docevaluatearray (expr, doc, context, resolver) { var i, result, a = []; doc = doc || (context ? context.ownerdocument : document); resolver = resolver...
...And 2 more matches
panel - Archive of obsolete content
he script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. getting user input note: this example uses the action button api, which is only available from firefox 29 onwards. the following add-on adds a button which displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the re
turn key, the contents of the <textarea> is sent to the main add-on code. the add-on consists of six files: main.js: the main add-on code, that creates the button and panel get-text.js: the content script that interacts with the panel content text-entry.html: the panel content itself, specified as html icon-16.png, icon-32.png, and icon-64.png: icons for the button in three different sizes ...
...mit("show"); }); // listen for messages called "text-entered" coming from // the content script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. textentrypanel.port.on("text-entered", function (text) { console.log(text); textentrypanel.hide(); }); the content script "get-text.js" looks like this: // when the user hits re
turn, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; }...
...nt script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. textentrypanel.port.on("text-entered", function (text) { console.log(text); textentrypanel.hide(); }); the page script is exactly the same as the content script above, except that instead of self, we use addon to access the messaging apis: // when the user hits re
turn, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); addon.port.emit("text-entered", text); textarea.value = ''; ...
...k/panel").panel({ position: { top: 40, bottom: 100, }, height: 400 }).show(); // this is equivalent to: require("panel").panel({ position { top: 40 }, height: 400 }).show(); the same principle is applied in the horizontal axis with width, left and right. focus boolean set to false to prevent taking the focus away when the panel is shown. only
turn this off if necessary, to prevent accessibility issue. optional, default to true. contenturl string,url the url of the content to load in the panel. that is, they can't refer to remote scripts. the urls are usually constructed using self.data.url(). from firefox 34, you can use "./my-file.html" as an alias for self.data.url("my-file.html"). allo...
content/mod - Archive of obsolete content
page we want to modify attachto(style, window); // ... detachfrom(style, window); parameters modification : object the modification we want to remove from the target window : nsidomwindow the window to be modified. if window is not provided modification is removed from all targets it's being attached to. ...
...rs modification : object the modification we want to remove from the target window : nsidomwindow the window to be modified. if window is not provided modification is removed from all targets it's being attached to. gettargetwindow(target) function takes target, value representing content (page) and re
turns nsidomwindow for that content. if target does not represents valid content null is re
turned. for example target can be a content window itself in which case it's will be re
turned back. parameters target : object the object for which we want to obtain the window represented or contained. if a nsidomwindow is given, it works as an identify function, re
turns target itself. re
turns nsidomwindow|null : the window represented or contained by the target, if any. re
turns null otherwise. ...
... detach(modification, target) function removes attached modification. if target is specified modification is removed from that target only, otherwise modification is removed from all the targets it's being attached to. ...
...nction removes attached modification. if target is specified modification is removed from that target only, otherwise modification is removed from all the targets it's being attached to. parameters modification : object the modification we want to remove from the target target : object target is a value that representing content to be modified. it is valid only when gettargetwindow(target) re
turns nsidomwindow of content it represents. if target is not provided modification is removed from all targets it's being attached to. ...
preferences/service - Archive of obsolete content
application preference name to value. parameters name : string preference name. value : string,number,boolean preference value. example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").set(name, false); get(name, defaultvalue) gets the application preference name. parameters name : string defaultvalue : string,number,boolean preference value. ...
...name : string preference name. value : string,number,boolean preference value. example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").set(name, false); get(name, defaultvalue) gets the application preference name. parameters name : string defaultvalue : string,number,boolean preference value. re
turns string,number,boolean : preference value, re
turns defaultvalue if no preference is set, re
turns undefined if defaultvalue is not provided. example: var name = "extensions.checkcompatibility.nightly"; var nightlycompatchk = require("sdk/preferences/service").get(name); has(name) parameters name : string preference name. re
turns boolean : re
turns whether or not the application preference name exists. defaultvalue example: var name = "e...
...mpatchk = require("sdk/preferences/service").get(name); has(name) parameters name : string preference name. re
turns boolean : re
turns whether or not the application preference name exists. defaultvalue example: var name = "extensions.checkcompatibility.nightly"; if (require("sdk/preferences/service").has(name)) { // ... } keys(root) parameters root : string preference root name. re
turns array : re
turns an array of strings representing the child preferences of the root of this branch. isset(name) parameters name : string preference name. re
turns boolean : re
turns whether or not the application preference name both exists and has been set to a non-default value by the user (or a program acting on the user's behalf). example: var name = "extensions.checkcompatibility.nigh...
...oes nothing. if no default value exists the preference will cease to exist. parameters name : string preference name. example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").reset(name); getlocalized(name, defaultvalue) gets the localized value for an application preference name. parameters name : string defaultvalue : string preference value. re
turns string : localized preference value, re
turns a default value if no preference is set. some preferences refer to a properties file. so that prefs.get re
turns the properties file url whereas prefs.getlocalized re
turns the value defined in the properties file. example: var prefs = require("sdk/preferences/service"); var name = "general.useragent.locale"; prefs.get(name); // is equal to "chrome:/...
Creating annotations - Archive of obsolete content
the page element is eligible for annotation, then the selector highlights that element and binds a click handler to it. the click handler sends a message called show back to the main add-on code. the show message contains: the url for the page, the id attribute value, and the text content of the page element. ...
...because cfx run doesn't preserve browsing history, if you want to play along it's worth taking a note of the url. save the file and execute cfx run again. activate the annotator by clicking the widget and load a page: the screenshot below uses http://blog.mozilla.com/addons/2011/02/04/ overview-amo-review-process/. you should see ...
...height: 180px; margin: 10px; padding: 0px; } </style> </head> <body> <textarea rows='10' cols='20' id='annotation-box'> </textarea> </body> </html> save this inside data/editor as annotation-editor.html. annotation editor content script in the corresponding content script we do two things: handle a message from the add-on code by giving the text area focus listen for the re
turn key and when it is pressed, send the contents of the text area to the add-on. here's the code: var textarea = document.getelementbyid('annotation-box'); textarea.onkeyup = function(event) { if (event.keycode == 13) { self.postmessage(textarea.value); textarea.value = ''; } }; self.on('message', function() { var textarea = document.getelementbyid('annotation-box'); textarea.va...
...ion(data) { annotationeditor.annotationanchor = data; annotationeditor.show(); }); worker.on('detach', function () { detachworker(this, selectors); }); } }); execute cfx run again, activate the annotator, move your mouse over an element and click the element when it is highlighted. you should see a panel with a text area for a note: enter the note and press the re
turn key: you should see console output like this: info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a new add-on, you will have to choose between 2 review tracks: full review and preliminary review. info: we should ask for full review if possible. that's a complete annotation, and in the next section we'll deal with storing it. ...
Forms related code snippets - Archive of obsolete content
ppendchild(odecryear); ocapt.appendchild(odecrmonth); ocapt.appendchild(oincryear); ocapt.appendchild(oincrmonth); ocapt.appendchild(this.display); this.container.appendchild(ocapt); this.container.appendchild(othead); this.current.setdate(1); this.writedays(); otarget.onclick = function () { if (otable.parentnode) { otable.parentnode.removechild(otable); re
turn; } otable.style.zindex = nzindex++; otable.style.position = "absolute"; otable.style.left = otarget.offsetleft + "px"; otable.style.top = (otarget.offsettop + otarget.offsetheight) + "px"; otarget.parentnode.insertbefore(otable, otarget); }; ainstances.push(this); } datepicker.prototype.writedays = function () { const nendblanks = (th...
...-1 : 1, othiscal = ainstances[this.id.replace(rbgnnan, "")]; othiscal.current[bismonth ? "setmonth" : "setyear"](othiscal.current[bismonth ? "getmonth" : "getfullyear"]() + ndelta); othiscal.writ...
...ces[onode.id.replace(rbgnnan, "")].container.style.zindex = nzindex++; } function onheadclick () { const bismonth = rmonth.test(this.id), ndelta = rdecrease.test(this.id) ? -1 : 1, othiscal = ainstances[this.id.replace(rbgnnan, "")]; othiscal.current[bismonth ? "setmonth" : "setyear"](othiscal.current[bismonth ? ...
..."getfullyear"]() + ndelta); othiscal.writedays(); re
turn false; } function ondayclick () { const othiscal = ainstances[this.id.replace(rbgnandend, "")]; othiscal.target.value = (this.innerhtml / 100).tofixed(2).substr(-2) + "\/" + (othiscal.current.getmonth() + 1) + "\/" + othiscal.current.getfullyear(); othiscal.container.parentnode.removechild(othiscal.container); re
turn false; } function buildcalendars () { const afields = document.getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen; new datepicker(afields[nitem++])); } const /* customizable by user */ sprefs = "zdp"; sdpclass = "date-picker", smonthsnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"...
HTML to DOM - Archive of obsolete content
although you can now natively parse html using domparser and xmlhttprequest, this is a new feature that is not yet supported by all browsers in use in the wild. the code snippets on this page will let your site work until these new features are more widely available. safely parsing simple html to dom when using xmlhttprequest to get the html of a remote webpage, it is often advantageous to
turn that html string into dom for easier manipulation. however, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the html safely. the function below will safely parse simple html and re
turn a dom object which can be manipulated like web page elements. this will remove tags like <script>, <style>, <head>, <body>, ...
...ument.implementation.createdocument("http://www.w3.org/1999/xhtml", "html", null), body = document.createelementns("http://www.w3.org/1999/xhtml", "body"); html.documentelement.appendchild(body); body.appendchild(components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(ahtmlstring, false, null, body)); re
turn body; } it works by creating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the html fragment and attaching that fragment to the <div>. the <div> is re
turned, and it is never actually appended to the current page. the re
turned <body> object is of type element here is a sample that counts the number of paragraphs in a string: var dompars = htmlparser(...
... current page, then parsing the html fragment and attaching that fragment to the <div>. the <div> is re
turned, and it is never actually appended to the current page. ...
... frame.webnavigation.allowmetaredirects = true; frame.webnavigation.allowplugins = false; frame.webnavigation.allowsubframes = false; // listen for load frame.addeventlistener("load", function (event) { // the document of the html in the dom var doc = event.originaltarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultview.frameelement) re
turn; // do something with the dom of doc alert(doc.location.href); // when done remove frame or set location "about:blank" settimeout(function (){ var frame = document.getelementbyid("sample-frame"); // remove frame // frame.destroy(); // if using browser element instead of iframe frame.parentnode.removechild(frame); // or set location "about:blank" ...
LookupPrefix - Archive of obsolete content
nippets/lookupnamespaceuri // http://www.w3.org/tr/dom-level-3-core/core.html#node3-lookupnamespaceprefix // http://www.w3.org/tr/dom-level-3-core/namespaces-algorithms.html#lookupnamespaceprefixalgo // (the above had a few apparent 'bugs' in the pseudo-code which were corrected here) if (node.lookupprefix && htmlmode !== 'text/html') { // shouldn't use this in text/html for mozilla as will re
turn null re
turn node.lookupprefix(namespaceuri); } if (namespaceuri === null || namespaceuri === '') { re
turn null; } switch (node.nodetype) { case 1: // node.element_node re
turn _lookupnamespaceprefix(namespaceuri, node); case 9: // node.document_node re
turn _lookupnamespaceprefix(namespaceuri, node.documentelement); case 6: // node.entity_node case 12: // node.notation_node ...
...mespaceuri === '') { re
turn null; } switch (node.nodetype) { case 1: // node.element_node re
turn _lookupnamespaceprefix(namespaceuri, node); case 9: // node.document_node re
turn _lookupnamespaceprefix(namespaceuri, node.documentelement); case 6: // node.entity_node case 12: // node.notation_node case 11: // node.document_fragment_node case 10: // node.document_type_node re
turn null; // type is unknown case 2: // node.attribute_node if (node.ownerelement) { re
turn _lookupnamespaceprefix(namespaceuri, node.ownerelement); } re
turn null; default: if (node.parentnode) { // entityreferences may have to be skipped to get to it re
turn _lookupnamespaceprefix(namespaceuri, node.parentnode); } re
turn null; } } // private function for lookuppr...
...mespaceuri, node.parentnode); } re
turn null; } } // private function for lookupprefix only function _lookupnamespaceprefix (namespaceuri, originalelement) { var xmlnspattern = /^xmlns:(.*)$/; if (originalelement.namespaceuri && originalelement.namespaceuri === namespaceuri && originalelement.prefix && originalelement.lookupnamespaceuri(originalelement.prefix) === namespaceuri) { re
turn originalelement.prefix; } if (originalelement.attributes && originalelement.attributes.length) { for (var i=0; i < originalelement.attributes.length; i++) { var att = originalelement.attributes[i]; xmlnspattern.lastindex = 0; var localname = att.localname || att.name.substr(att.name.indexof(':')+1); // latter test for ie which doesn't support localname if (localname.indexof(':') !
...lname || att.name.substr(att.name.indexof(':')+1); // latter test for ie which doesn't support localname if (localname.indexof(':') !== -1) { // for firefox when in html mode localname = localname.substr(att.name.indexof(':')+1); } if ( xmlnspattern.test(att.name) && att.value === namespaceuri && lookupnamespaceuri(originalelement, localname) === namespaceuri ) { re
turn localname; } } } if (originalelement.parentnode) { // entityreferences may have to be skipped to get to it re
turn _lookupnamespaceprefix(namespaceuri, originalelement.parentnode); } re
turn null; } ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
height="100"/> listing 6: setting the size of a button also, as shown in listing 7, you can embed css inline into elements via the style attribute, which allows you to set sizes using units other than pixels. <button label="button" style="min-width: 10em;"/> listing 7: setting the size of a button using css markup hidden and collapsed the hidden and collapsed attributes act as switches to
turn off the display of elements. setting hidden="true" disables display of that element. this has the same effect as setting display: none in css. you would use this to set a hidden or absent state, for example items that aren't displayed in contextual menus. setting collapsed="true" sets an element's height and width to 0, but the element is treated as being present. this is equivalent to setting ...
.... but both these functions are handled by textbox as shown in listing 16, which produces output as shown in figure 13. the textbox element uses the value attribute to set its default content; content entered by the user also can be captured using the value attribute. to set a maximum length in characters, declare the maxlength attribute with a positive integer value. setting type="password" will
turn the textbox into a special password-entry field, in which characters are hidden as they're typed. every character entered into a textbox generates an input event. if you use the oninput event handler, you can implement commands that reflect user input in real time. <vbox align="start"> <textbox/> <textbox multiline="true" rows="5" cols="15"/> </vbox> listing 16: textbox examples figure...
... triggers, declare that character as the key attribute’s value. you can use either uppercase and lowercase letters and they will be handled the same. for triggers on other special keys, use the keycode attribute with the appropriate keycode name value. in general you can use the keycode name for any key; the most commonly used ones are shown in table 3. ...
...clare that character as the key attribute’s value. you can use either uppercase and lowercase letters and they will be handled the same. for triggers on other special keys, use the keycode attribute with the appropriate keycode name value. in general you can use the keycode name for any key; the most commonly used ones are shown in table 3. ...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
when the file is read in, its contents are converted from utf-8 to unicode. listing 22: content for _readfile method _readfile: function(afile) { try { var stream = components.classes["@mozilla.org/network/file-input-stream;1"]. createinstance(components.interfaces.nsifileinputstream); stream.init(afile, 0x01, 0, 0); var...
...tl/converter-input-stream;1"]. createinstance(components.interfaces.nsiconverterinputstream); cvstream.init(stream, "utf-8", 1024, components.interfaces.nsiconverterinputstream.default_replacement_character); var content = ""; var data = {}; while (cvstream.readstring(4096, data)) { content += data.value; } cvstream.close(); re
turn content.replace(/\r\n?/g, "\n"); } catch (ex) { } re
turn null; }, _writefile method creates a new file for the nslfile object passed as a parameter, and writes the text string, also passed as a parameter. upon writing, the text is converted from unicode to utf-8. listing 23: content for _writefile method _writefile: function(afile, adata) { // init stream var stream =...
...s compreg.dat and xpti.dat inside the profile folder and relaunch firefox. default preferences file inside the defaults\preferences directory you will need to relaunch firefox. chrome.manifest you will need to relaunch firefox. install.rdf you will need to temporarily uninstall the extension and then reinstall it. in practice, what you’ll do is remove the pointer file, relaunch firefox, re
turn the pointer file, and relaunch firefox again. on a linux system, use the touch command on the directory pointed at by the pointer file to change its “last changed” date, and avoid the relaunching. the session store api the session store api4 is one of the new developer-oriented features in firefox 2. using the various methods in the nslsessionstore interface, which is an xpcom service, you ...
...e various methods in the nslsessionstore interface, which is an xpcom service, you can easily save and restore session states. functions in firefox that let you reopen the last closed tab, or restore to your previous state after a crash, are all implemented through this api. we used two methods in the nslsessionstore interface in this project. let’s look at how they work. getbrowserstate() re
turns a json-formatted5 text string representing the state of every currently open browser window. this string includes extensive information regarding every open window and tab, the forward/back history for each tab, page scroll position, text zoom, contents of form elements, etc. setwindowstate(awindow, astate, aoverwrite) restores the browser window indicated by the parameter awindow to the state...
Dehydra Function Reference - Archive of obsolete content
once and subsequent include calls are ignored. this is accomplished by recording every included file into the _includedarray in the current namespace. include example include("map.js") // includes map.js into toplevel var map = {} include("map.js", map) // includes map.js into the map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime execution flags. ...
...it is a mainly useful for debugging dehydra for rooting bugs. gczeal is only enabled when spidermonkey and dehydra are compiled with debug macro defined. ...
...es of these flags. require supports optional named arguments via javascript object where each parameter is a property. if a property is not specified then it will not be passed to the runtime. version integer: this sets js version similar to version() in js 1.7. strict boolean: controls js strict mode werror boolean:
turns js warnings into errors gczeal int: this is a write-only parameter to set
turn on frequent garbage collection. it is a mainly useful for debugging dehydra for rooting bugs. gczeal is only enabled when spidermonkey and dehydra are compiled with debug macro defined. require() example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism. if -werror is specified this ...
...ror mechanism. this will cause compilation to fail. msg is a string to be presented as a gcc error optional: loc is the location that should be reported for the warning. if no location is provided, the location is inferred from the last process_type or process_function. _print(msg, ...) the low level function called by print(). it does not print the location. read_file(filename) read a file a re
turn it as a string. write_file(filename, data) write a string to a file. builtin objects sys this.sys is a container for miscellaneous properties exposes by dehydra sys.gcc_version is a gcc version string sys.include_path exposes the search path used by include(). the default value is the following directories: the directory of the dehydra script being processed the libs directory next to the gcc_d...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
hen something should happen on a drag exit. it has two arguments, the event object and the drag session. ondrop(event, dropdata, session) this function should be defined when you want something to happen when an object is dropped. the first argument is the event object and the second is the data being dragged. the third argument is the drag session. getsupportedflavours() this function should re
turn a list of flavors that the object being dragged over can accept. this function takes no arguments. this function is necessary so that the wrapper can determine the best flavour to pass to the other functions. for an observer that is observing an element that can start a drag, you should define at least the ondragstart function. for elements that can have objects dropped on them, you should defin...
...n element that can start a drag, ondragstart is all that is necessary to implement. for an element that can be dropped on, the observer will need to implement at least the getsupportedflavours, ondragover and ondrop functions. some elements may be able to initiate a drag and accept a drop. in this case, the ondragstart function will be necessary as well. the getsupportedflavours function should re
turn a list of flavours that the element being dragged over can accept for dropping. a file system directory view might accept files and perhaps text, but wouldn't accept html text. below, we'll define a getsupportedflavours function. we'll allow only one flavour here, that for a string. var textobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appen...
...ment being dragged over can accept for dropping. a file system directory view might accept files and perhaps text, but wouldn't accept html text. below, we'll define a getsupportedflavours function. we'll allow only one flavour here, that for a string. var textobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("text/unicode"); re
turn flavours; } } the flavours list contains only one flavour, which is 'text/unicode'. the flavourset object can be used to hold a list of flavours. in some cases, you must provide the xpcom interface as well. for example, for files: var textobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("application/x-moz-file","nsifile"); ...
...nly one flavour, which is 'text/unicode'. the flavourset object can be used to hold a list of flavours. in some cases, you must provide the xpcom interface as well. for example, for files: var textobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("application/x-moz-file","nsifile"); flavours.appendflavour("text/unicode"); re
turn flavours; } } the ondragover function defines what happens when an object is dragged over. you might use it to change the appearance of the element as it is being dragged over. in many cases the function can do nothing. it must be defined for elements that accept dragged data however. next, the ondrop function should be created. its second argument is the transfer data object that holds the da...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
the load is not aborted, we create an nsdocumentopeninfo object for this load, passing it the "this is a link click" boolean and the window context. we then set the channel's nsiloadgroup to the one from the window context. nsdocumentopeninfo::prepare is passed the channel to open. it calls getinterface on the window context to get and save that context's nsiuricontentlistener. openchannel re
turns to openuri which just opens the channel, setting the nsdocumentopeninfo as the stream listener. onstartrequest notification comes back from necko nsdocumentopeninfo::onstartrequest checks the response status code on the channel for http channels and drops the load on the floor if warranted (e.g. 204 or 205 responses). then it calls nsdocumentopeninfo::dispatchcontent nsdocumentopeninfo::di...
...it checks whether the channel has "content-disposition: attachment" set. if so, it skips trying to find an internal viewer and goes right over to looking for a stream converter. otherwise, dispatchcontent goes through a three-step process to try to find the correct listener. ...
...istener on various content listeners; if that re
turns true, we have found the right listener and we are done. trycontentlistener makes use of the ispreferred and canhandlecontent functions on nsiuricontentlistener and calls docontent() on the listener if it claims to handle the data, as well as hooking up a stream converter if the listener asks for one. if any of those steps fails, the function re
turns false so that another content listener will be looked for. the first content listener we check is the content listener associated with our window context (the docshell that initiated the load). if this can't handle the content type, we loop over our stored list of possible listeners (previously registered via registercontentlistener) and ask each one in
turn whether it can handle the data. if ...
...tempt to redispatch it. if a converter is found, we hook that up as our stream listener and are done -- we just need to pump data into it and let the downstream nsdocumentopeninfo handle the final dispatch. if we still do not have a stream listener, that means that we failed to find an nsiuricontentlistener or nsicontenthandler for this type. give the load to the helper app service; this will re
turn an nsistreamlistener that we can use. original document information author(s): boris zbarsky last updated date: october 24, 2003 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Style System Overview - Archive of obsolete content
tation problem: the rule structures use too much memory (a few hundred kilobytes for all our chrome), and require large numbers of allocations to construct. detail: !important declarations cause an extra rule object cssimportantrule to be created since they are in a separate part of the cascade other nsistylerule implementations nshtmlmappedattributes represents stylistic html attributes
turned into a style rule (one instance per unique set of attributes) bodyrule handles marginwidth/marginheight mixes on body and on frame. various rules in nshtmlstylesheet.cpp do other things with presentational color-related attributes and with tables. content nodes (instead of stylesheets) also hold onto cssstyleruleimpl objects that represent their style attributes. the cascade stylesetimp...
...t struct. a rule node that uses the same struct as its parent is marked with a “dependent bit” for that struct, which tells nsrulenode::getstyledata to just get the struct from the parent. style data computation all the style struct computation described in the previous few slides happens lazily. first, nsstylecontext::getstyledata checks for a cached struct on the style context, and re
turns it if present. then, nsrulenode::getstyledata checks for a cached struct or a dependent bit on the rule node, and re
turns the struct if present. otherwise, we need to compute the struct, so nsrulenode::getstyledata calls nsrulenode::get*data, which initializes the correct one of the data structs on the stack (the structs used by nscssdeclaration) style data computation get*data calls nsru...
...ementations must check that the property is not filled in before filling it in. walkruletree stops walking up when it finds either a none bit, a cached struct, a dependent bit, or all the properties have been filled in. walkruletree also remembers the first rule that contributed non-empty data. style data computation after walkruletree stops walking up, it calls nsrulenode::compute*data to
turn the specified values into the mostly-computed style data in the style struct. compute*data use either a default or a start struct as the basis for the computation. a start struct is a cached struct in the rule tree that we can just copy and add to. if the computation in compute*data used any data from the parent style context, we cache the struct on the style context. otherwise, we cache the s...
...isting frames (rule node pointer immutable). reresolvestylecontext is messy because it needs to create and parent style contexts correctly (sibling sharing may not be the same) rather than just changing data. [design flaw, again] any specially-parented style contexts (not along frame parents, which need not be content parents) are reconstructed using nsiframe::getparentstylecontextframe. can re
turn same style context due to sibling sharing unless we're destroying the rule tree for a style sheet/rule removal. dynamic changes to content reresolvestylecontext calculates differences (repaint, reflow, reframe, etc.) between style old and new style contexts and does appropriate cleanup it uses nsistylecontext::calcstyledifference, which only computes differences for structs that have been r...
Nanojit - Archive of obsolete content
ard = (guardrecord *) rec_ins->payload(); memset(guard, 0, sizeof(*guard)); sideexit *exit = (sideexit *)(guard + 1); guard->exit = exit; guard->exit->target = f; f->lastins = out.insguard(lir_loop, out.insimm(1), rec_ins); // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->error() != none) { fprintf(stderr, "error compiling fragment\n"); re
turn 1; } printf("compilation successful.\n"); // call the compiled function. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 = %d\n", fn(5)); re
turn 0; } code explanation interesting part are the lines 46-50: // write a few lir instructions to the buffer: add the first parameter // to the constant 2. out.ins0(lir_start)...
... the lirwriter's writer object. from an operational point of view, it is creating a function, which takes an integer input, and adds it to two, and outputs the result. the function is created here on lines 57-69: // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->error() != none) { fprintf(stderr, "error compiling fragment\n"); re
turn 1; } printf("compilation successful.\n"); // call the compiled function. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 = %d\n", fn(5)); re
turn 0;</addtwofn> this upper half of this snippet includes code where the raw lir is first converted into machine code.(where compile(fragmento->assm(), f); is called basically). th...
...tion. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 = %d\n", fn(5)); re
turn 0;</addtwofn> this upper half of this snippet includes code where the raw lir is first converted into machine code.(where compile(fragmento->assm(), f); is called basically). then a pointer to a function is used, which takes an int as input and re
turns the sum of that parameter with two. (typedef js_fastcall int32_t (*addtwofn)(int32_t); ) then, printf is hardcoded to call it with a parameter 5, and on linking with nanojit library, the following program will display 2+5=7 now, what i need to do is generate output for this: start two = int 2 twoplustwo = add two, two ret twoplustwo this adds two and two in the most hardcoded way possibl...
...ey leave the jit code entirely, and stop the trace. need guards are required in a cross platform dynamic language like javascript. certain assumptions are made when a particular jit code is generated. for example, in an instruction inr x, a guard would check that x doesn't overflow the range for a 32 bit integer. the jit code would have a guard checking this condition(an xt guard), and would re
turn to the interpreter if the condition
turns out to be true. the interpreter is then equipped to handle the overflow. hence, guards are needed to prevent certain erroneous behaviour that might result from the assumptions that are generally made while jit is generated. todo: explain guards, guard records, vmsideexit, fragmento, verbosewriter::formatguard... ...
Using XPInstall to Install Plugins - Archive of obsolete content
e installation .... var pluginfolder = getfolder("plugins"); // verify disk space is appropriate .... err = addfile("@myplugin.com/myplugin,version=2.5.0.0", "2.5.0.0", plugin_file, pluginsfolder, null); if (err != 0) { //alert("installation of myplugin plug-in failed. error code "+err); logcomment("adding file "+plugin_file+" failed. ...
...installation of myplugin plug-in failed. error code "+err); logcomment("adding file "+plugin_file+" failed. errror conde: " + err); re
turn err; } err = addfile(null, cult_version, component_file, componentsfolder, null); if (err != 0) { alert("installation of myplugin component failed. error code "+err); logcomment("adding file "+component_file+" failed. error conde: " + err); re
turn err; } installing to a secondary location for the purposes of solving the first install problem, it is necessary to install to a secondary location to ensure discoverability of the plugin by other netscape gecko browser in addition to the current browser. a good choice for this secondary location might be the windows directory on windows machines. caveat: because of possible administrator ...
...ystem directory e.g. ...
...this is accomplished with the winreg object that is exposed to xpinstall. ...
Windows Install - Archive of obsolete content
// subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name ...
... // subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want...
...0; i < listlongfilepaths.length; i++) { flongfilepath = getfolder(fprogram, listlongfilepaths[i]); sshortfilepath = file.windowsgetshortname(flongfilepath); if(sshortfilepath) { fren8dot3ini.writestring("rename", sshortfilepath, flongfilepath); binicreated = true; } } if(binicreated) updatewinreg4ren8dot3() ; } re
turn(0); } // main var srdest; var err; var fprogram; srdest = 449; err = initinstall(prettyname, regname, "6.0.0.2000110801"); logcomment("initinstall: " + err); fprogram = getfolder("program"); logcomment("fprogram: " + fprogram); if(verifydiskspace(fprogram, srdest)) { setpackagefolder(fprogram); err = adddirectory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fpr...
...est = 449; err = initinstall(prettyname, regname, "6.0.0.2000110801"); logcomment("initinstall: " + err); fprogram = getfolder("program"); logcomment("fprogram: " + fprogram); if(verifydiskspace(fprogram, srdest)) { setpackagefolder(fprogram); err = adddirectory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fprogram, // where to put this file // (re
turned from getfolder) "", // subdir name to create relative to fprogram true); // force flag logcomment("adddirectory() re
turned: " + err); // check re
turn value if(err == success) { err = performinstall(); logcomment("performinstall() re
turned: " + err); } else cancelinstall(err); } else cancelinstall(insufficient_disk_space); // end main ...
XUL Events - Archive of obsolete content
contextmenu this event is sent to an element when the user requests to open the context menu for the element. the action to do this varies by platform, but it will typically be a right click. this handler is usually used to dynamically set the commands on a menu when the user requests to display it, or you can use popupshowing event. re
turning false from this event handler prevents the popup from appearing. attribute: oncontextmenu drag the drag event is sent to the source node (the node that was dragged) several times a second while the drag is occurring. attribute: ondrag ...
...phiding this event is sent to a popup when it is about to be hidden. attribute: onpopuphiding popupshowing this event is sent to a popup just before it is popped open. this handler is usually used to dynamically set the contents when the user requests to display it. re
turning false from this event handler prevents the popup from appearing. attribute: onpopupshowing popupshown this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. attribute: onpopupshown ...
... syncfrompreference this event is sent when the element is being changed because a preference changed, or when an element is initialized from a preference. this event will only be sent to elements connected to a preference and in a prefwindow. this is not a real event instead it is just a function call and must use the attribute syntax. the script may re
turn a value to set the element to a specific value rather than the value of the preference. this event is usually used to adjust the preference value so that it is more suitable for display in the user interface. attribute: onsyncfrompreference synctopreference this event is sent when the element connect...
...onsyncfrompreference synctopreference this event is sent when the element connected to a preference has changed. this event will only be sent to elements connected to a preference and in a prefwindow. this is not a real event instead it is just a function call and must use the attribute syntax. the script may re
turn a value to set the preference to a specific value rather than the value of the element. attribute: onsynctopreference underflow this event is sent to an element when there becomes enough space to display it at full size. this applies to boxes and other layout elements with a css overflow property oth...
Accessing Files - Archive of obsolete content
getfile(). the following example will retrieve a reference to a file named sample.txt located in the profile directory. var file = io.getfile("profile", "sample.txt"); the nsiscriptableio object is a global object always available within an application or extension which provides a number of useful functions for dealing with files. one such method it provides is nsiscriptableio.getfile() which re
turns a new nsifile object. the first argument to nsiscriptableio.getfile() is the starting directory from which to locate a file. in the example above the word 'profile' is used, which means start from within the user's profile directory. the actual location of this directory will vary by user and system, so this is a convenient means to refer to a common directory without having to locate it yoursel...
...t yourself. for a full list of starting directories, see starting directories below. the second argument to nsiscriptableio.getfile() is the filename to locate, which, here, is 'sample.txt'. the result is that a reference is made to the 'sample.txt' file. it is important to note that this file does not have to exist for a file reference to be valid. ...
...if the file does not exist, you may wish to create it. the file object has a nsifile.create() method which may be used to create an empty file, or you can open a writing stream and write to the file. nsiscriptableio.getfile() may only be used to retrieve files that are directly within one of the starting directories. ...
...ould use this as the default directory for saving files. components the components directory where xpcom components are installed. temp the temporary directory. you would store any temporary or cache files here. there are a number of other values that may be used, most of which are platform specific. for instance, on windows, the value 'strt' re
turns the start directory, where applications which run when the system starts up are placed. on other platforms, using this value will just result in an error. ...
MenuModification - Archive of obsolete content
argument is the index where the new item should be inserted. in this case, 0 is supplied as the index, which means before the first item. indicies are counted starting at 0, so to insert an item before the fourth item pass 3 as the argument. the second and third arguments to insertitemat are the label and value for the new item, as with appenditem. both the appenditem and insertitemat methods re
turn the new menuitem, so you can further modify it, for instance to add an access key, as in the following example: var item = menu.appenditem("insert", "insert"); item.accesskey = "i"; appending submenus there is no built-in method to append submenus to a menu. to do this, we instead need to use the inherited node modification methods available for all elements. first, we need to retrieve the me...
...ent listener. otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. another possibility is to ensure that the menu is only added once. the following shows how the addsubmenu function above might be rewritten to handle this case. ...
... removing items from a menu to remove an item from the menu, use the removeitemat method. it takes a single argument, the index of the item to remove. in this example, an item is appended to a menu, and then immediately removed again. ...
... var newmenu = document.createelement("menu"); popup.appendchild(newmenu); newmenu.label = "new"; newmenu.appenditem("document", "doc"); newmenu.appenditem("image", "image"); } </script> the haschildnodes method may be used to check if a node has any children. the first time the function is called, the haschildnodes method will re
turn false, however the second time, the method will re
turn true as the items have already been added to the menu. removing items from a menu to remove an item from the menu, use the removeitemat method. it takes a single argument, the index of the item to remove. in this example, an item is appended to a menu, and then immediately removed again. menu.appenditem("open", ""); menu.removeitemat(menu.itemcount - 1); the itemcount property holds the numb...
Tree Widget Changes - Archive of obsolete content
nscomptr<nsiatom> atom; acol->getatom(getter_addrefs(atom)); if (atom = kmycol) ... one feature that has been added is restorenaturalorder which may be used to restore the original order of the columns before the user moved them around. tree.columns.restorenaturalorder() there is also a command on the end of the tree's column pic...
...ot the box object, meaning use tree.view.selection instead of tree.treeboxobject.selection. use tree.columns[1].id instead of tree.treeboxobject.getcolumnid(1) to get the id of a column, in this case column 1. use tree.columns.getkeycolumn().index instead of tree.treeboxobject.getkeycolumnindex(). the nsitreeboxobject.getpagecount() method has been renamed to make it clearer what it does. it re
turns the number of rows that can be displayed in the tree. this should correspond to the rows attribute on the tree if it was specified. tree.treeboxobject.getpagecount() is now tree.treeboxobject.getpagelength(). the invalidateprimarycell(row) method has been removed, instead use nsitreeboxobject.invalidatecell() like this invalidatecell(row, tree.columns.getprimarycolumn()). this may be used to r...
... (1) nsitreeview.progressnormal -> nsitreeview.progress_normal (1) nsitreeview.progressundetermined -> nsitreeview.progress_undetermined (2) nsitreeview.progressnode -> nsitreeview.progress_none (3) as well, the drag and drop methods candropon and candropbeforeafter have been replaced with a single method candrop(idx,orientation) which handles both. it should re
turn true if a drop is allowed on a row. checkbox columns tree columns now implement the checkbox type. previously the value existed but was not implemented. now it is. you can create a checkbox column by setting the type attribute of a column to checkbox. <treecol type="checkbox"> you can then set or clear the checkbox for a particular cell in that column by setting the value attribute to true, ...
...the tree must also be marked as editable using the editable attribute in order for this to work. this is shown in the example above. sometimes, you might have a particular row or cell which you do not want to be editable. in this case, disable editing for that cell by setting editable to false for that cell, as in the following: <treecell value="true" editable="false"/> or, for custom views, re
turn false from the iseditable method. currently, only checkbox columns support editing, although the content-based tree handles the nsitreeview.setcellvalue() and nsitreeview.setcelltext() functions to change the tree content with a script for other types of cells. for instance: var col = tree.columns.getprimarycolumn(); treecell.setcelltext(5, col, "banana"); this will change the label of the ce...
Document Object Model - Archive of obsolete content
st.xul","_new"); open("test.xul","_new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. in xul, each function you declare will be set as a property of the window object. for example, the following code will display the text 'message' in an alert twice. function gettext(){ re
turn "message"; } alert(gettext()); alert(window.gettext()); thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. for example, if we combined the last two examples into a single file, we might want to call the gettext() function from within the other window (for example, the test.xul ...
...window). to do this, we can do the following: alert(window.opener.gettext()); each window has an opener property which holds the window object that opened this one. in this example, we retrieve the opener window and call the gettext() function declared in a script used there. note that we qualified the property with the 'window' identifier just to be clearer. the window's open() method also re
turns a reference to the new window so you can call functions of the new window from the opener. it is important to note, however, that the open() method re
turns before the window has fully loaded, so functions will not typically be available yet. the window object isn't defined by any dom specification, but in mozilla is sometimes considered part of dom level 0, a name used by some developers to ref...
...dom methods. it is important to note that attributes and properties are separate things. just because there is an attribute with a given name does not mean that there is a corresponding property with the same name. however, it will often be the case that such a property will exist. for example, to get the flex of an element, you can use the flex property. in this case, the underlying code just re
turns the value of the attribute. for other properties, xul will perform more complex calculations. you can manipulate the attributes of an element using any of the following methods: getattribute ( name ) re
turn the value of the attribute with the given name. hasattribute ( name ) re
turn true if the attribute with the given name has a value. setattribute ( name , value ) set the value of the...
...ence to an element, you can call the properties of that element. for example, to get the hidden property for an element, you can use the syntax element.hidden where 'element' is a reference to the element. you might note that most of the properties listed in the reference correlate to common attributes on elements. there are differences, of course, for example, while getattribute("hidden") will re
turn the string 'true' for a hidden element, whereas the hidden property re
turns a boolean true value. in this case, the type conversion is done for you so the property is more convenient. as with each document, there is a different element object for xul elements as for html and xml elements. every xul element implements the xulelement (reference broken) interface. a xul element is any element decla...
Styling a Tree - Archive of obsolete content
ill be set. setting properties for the rdf-built trees for rdf-built trees, you can use the same syntax. however, you will often set the properties based on values in the datasource. setting properties for the custom view for trees with a custom view script, you can set properties by supplying the functions getrowproperties(), getcolumnproperties() and getcellproperties() in the view. these re
turn information about an individual row, column and cell. arguments to these functions indicate which row and/or column. prior to gecko 22 the last argument to each of these functions is a properties list which the view is expected to fill with a list of properties. the function getcolumnproperties() also supplies the corresponding treecol element for the column. getrowproperties : function(row,pro...
...e last argument to each of these functions is a properties list which the view is expected to fill with a list of properties. the function getcolumnproperties() also supplies the corresponding treecol element for the column. getrowproperties : function(row,prop){} getcolumnproperties : function(column,columnelement,prop){} getcellproperties : function(row,column,prop){} from gecko 22 you can re
turn a string of space-separated property names from these functions. getrowproperties : function(row){ re
turn ''} getcolumnproperties : function(column,columnelement){ re
turn ''} getcellproperties : function(row,column){ re
turn ''} let's look at an example of changing a specific cell. let's make every fourth row have blue text, using the example from a previous section. we'll need to add code to t...
...nt(aserv.getatom("makeitblue")); } } the properties list requires an array of atom objects, which can be thought of as constant strings. we create them using the xpcom interface nsiatomservice and add them to the array using the appendelement() function. here, we create an atom 'makeitblue'. you can call appendelement() again to add additional properties. from gecko 22 your function should re
turn a string containing the property. getcellproperties: function(row,col){ if ((row %4) == 0){ re
turn "makeitblue"; } } to support gecko versions before and after this change use. getcellproperties: function(row,col,props){ if ((row %4) == 0){ if (props) { var aserv=components.classes["@mozilla.org/atom-service;1"]. getservice(components.interfaces.nsiatomservi...
...it first checks to see which row is being requested and sets a property for cells in every fourth row. ...
menu - Archive of obsolete content
he contents, as visible to the user, are read and set using the menulist.value syntax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. properties accessibletype type: integer a value indicating the type of accessibility object for the element. control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu. itemcount type: integer read only property holding the number of child items. menupopup type: menupopup element a reference to the menupopup used by the menu or menulist. this property is read-only. open type: boolean this property will be set to true when the menu i...
...d items. menupopup type: menupopup element a reference to the menupopup used by the menu or menulist. this property is read-only. open type: boolean this property will be set to true when the menu is open. the menu may be opened by setting the open property to true and closed by setting it to false. parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu. selected type: boolean this property's value is true if this element is selected, or false if it is not. this property is read only. this property is available for menuitem and menuseparator elements in firefox 3. value type: string gets and sets the value of the value attribute. for textb...
... isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) re
turn type: element creates a new item and adds it to the end of the existing list of items. you may optionally set a value. the function re
turns the newly created element. getindexofitem( item ) re
turn type: integer re
turns the zero-based position of the specified item. items are numbered starting at the first item displayed in the list. getitematindex( index ) re
turn type: element retu...
...y optionally set a value. the function re
turns the newly created element. getindexofitem( item ) re
turn type: integer re
turns the zero-based position of the specified item. items are numbered starting at the first item displayed in the list. getitematindex( index ) re
turn type: element re
turns the element that is at the specified index. insertitemat( index, label, value ) re
turn type: element this method creates a new item and inserts it at the specified position. you may optionally set a value. the new item element is re
turned. removeitemat( index ) re
turn type: element removes the child item in the element at the specified index. the method re
turns the removed item. style classes menu-iconic use this class to have an image appear on the...
preference - Archive of obsolete content
however, the value may still be modified by a script. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a higher tabindex are later in the tab seque...
.... usually a checkbox would be connected to these preferences. int an integer string a string unichar a unicode string wstring a localized string. in this situation the preference will save the path to a property file which contains the actual value of the preference. file a file. the file path will be stored in the preferences. properties defaultvalue (readonly) re
turns the default value of the preference. the type of the property depends on the value of the type property. if the preference has no default value, this property re
turns null. disabled type: boolean gets and sets the value of the disabled attribute. hasuservalue type: boolean true if the preference has been changed from its default value. instantapply (readonly...
...the preference does not have a user-set value (hasuservalue == false). in this case the actual value to be displayed in the ui is obtained from the defaultvalue property. valuefrompreferences gets and sets the value stored in the user preference, specified in name. (this always accesses the nsiprefbranch apis regardless of the instantapply mode in effect). methods reset() re
turn type: no re
turn value resets the preference to its default value. for a textbox it also clears the undo transaction list (gecko 1.9). type getelementvalue(in domelement element); retrieves the value that should be written to preferences based on the current state of the supplied element. this function calls onsynctopreference. boolean iselementeditable(in domelement element) ...
... void setelementvalue(in domelement element); initializes the supplied element from the value stored in the preference. this function calls onsyncfrompreference. void updateelements(); update all elements that observe this preference. ...
radio - Archive of obsolete content
a label, specified with the label attribute may be added beside the radio button. more information is available in the xul tutorial. ...
...a label, specified with the label attribute may be added beside the radio button. more information is available in the xul tutorial. ...
...a label, specified with the label attribute may be added beside the radio button. more information is available in the xul tutorial. ...
...attribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. properties accesskey type: character gets and sets the value of the accesskey attribute. accessibletype type: integer a value indicating the type of accessibility object for the element. control type: radiogroup element re
turns the enclosing radiogroup that the radio element is contained within, which may or may not be its direct parent. crop type: string gets and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. image type: image url gets and sets the value of the image attribute. ...
CommandLine - Archive of obsolete content
onents.id("178cfbb6-503c-11dc-8314-0800200c9a66"); const class_name = "applicationnameclh"; const contract_id = "@example.com/applicationname/clh;1"; const cld_category = "m-applicationname"; var apphandler = { /* nsisupports */ queryinterface : function clh_qi(aiid) { if (aiid.equals(nsicommandlinehandler) || aiid.equals(nsifactory) || aiid.equals(nsisupports)) re
turn this; throw components.results.ns_error_no_interface; }, /* nsicommandlinehandler */ handle : function clh_handle(acmdline) { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(acmdline, "commandline-args-changed", null); }, ...
... .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(acmdline, "commandline-args-changed", null); }, helpinfo : " -test <value> a test attribute\n", /* nsifactory */ createinstance : function mdh_ci(aouter, aiid) { if (aouter != null) { throw components.results.ns_error_no_aggregation; } re
turn this.queryinterface(aiid); }, lockfactory : function mdh_lock(alock) { /* no-op */ } }; var apphandlermodule = { /* nsisupports */ queryinterface : function mod_qi(aiid) { if (aiid.equals(nsimodule) || aiid.equals(nsisupports)) re
turn this; throw components.results.ns_error_no_interface; }, /* nsimodule */ getclassobject : function mod_gch(acompmg...
... mdh_lock(alock) { /* no-op */ } }; var apphandlermodule = { /* nsisupports */ queryinterface : function mod_qi(aiid) { if (aiid.equals(nsimodule) || aiid.equals(nsisupports)) re
turn this; throw components.results.ns_error_no_interface; }, /* nsimodule */ getclassobject : function mod_gch(acompmgr, acid, aiid) { if (acid.equals(class_id)) re
turn apphandler.queryinterface(aiid); throw components.results.ns_error_failure; }, registerself : function mod_regself(acompmgr, afilespec, alocation, atype) { var compreg = acompmgr.queryinterface(nsicomponentregistrar); compreg.registerfactorylocation(class_id, class_name, contract_id, afilespec, alocation, atype); var catman = component...
... alocation, atype) { var compreg = acompmgr.queryinterface(nsicomponentregistrar); compreg.unregisterfactorylocation(class_id, alocation); var catman = components.classes["@mozilla.org/categorymanager;1"] .getservice(nsicategorymanager); catman.deletecategoryentry("command-line-handler", cld_category); }, canunload : function (acompmgr) { re
turn true; } }; function nsgetmodule(acompmgr, afilespec) { re
turn apphandlermodule; } create an observer that will get notified when arguments change: chrome/content/cmdline.js function commandlineobserver() { this.register(); } commandlineobserver.prototype = { observe: function(asubject, atopic, adata) { var cmdline = asubject.queryinterface(components.interfaces.nsicommandline); ...
calICalendarView - Archive of obsolete content
ll not provide its own controller, but rather rely on other code to set this attribute. implementations should therefore be wary to check whether a controller has been assigned to the view, before calling any of the methods it implements.note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. startdate re
turns a calidatetime corresponding to the first date shown by the view enddate re
turns a calidatetime corresponding to the last date shown by the view. note that this date is typically not immediately useful for querying for the events and tasks shown in the calicalendarview. typically, one more day must be added to it, in order to make it exclusive. supportsdisjointdates consumers of calicalend...
...by the view. note that this date is typically not immediately useful for querying for the events and tasks shown in the calicalendarview. typically, one more day must be added to it, in order to make it exclusive. supportsdisjointdates consumers of calicalendarview should check this attribute to determine whether or not the implementation allows for calls to setdatelist. if an implementation re
turns true for this attribute, it must allow for any arbitrary set of dates to be displayed. hasdisjointdates re
turns false if the dates being displayed represent a continuous list, and true if certain dates in between startdate and enddate may not be displayed. selecteditem re
turns a caliitembase corresponding to the currently active item in the view. other areas of the code may use this attrib...
... selectedday the currently selected day in the display. ...
... unsigned long acount, [array,size_is(acount)] in calidatetime adates); this function can only be called if supportsdisjointdates is true and will throw an error if it is not. if supported, the dates in the adates array will become the only dates shown in the view. getdatelist void getdatelist(out unsigned long acount, [array,size_is(acount),retval] out calidatetime adates); this function re
turns a list of all dates currently being shown in the view. history calicalendarview was introduced as part of the 'backend rewrite' that occurred prior to lightning 0.1 and between sunbird 0.2 and sunbird 0.3. it remains unfrozen today. related interfaces calicalendarviewcontroller calidecoratedview example code both calendar-multiday-view and calendar-month-view show examples, albeit compl...
NPN_GetAuthenticationInfo - Archive of obsolete content
er scheme http authentication scheme name realm http authentication realm username out parameter. the browser passes back the http username. if the function succeeds, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the username may have internal null bytes and may not be null-terminated. ulen out parameter. ...
...for possible values, see error codes. ...
...for possible values, see error codes. description plugin which implement their own http networking stack (such as the java plugin) may want to use the standard http auth prompts and password managed of the browser. ...
...ername buffer. password out parameter. the browser passes back the http password. if the function succeed, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the password may have internal null bytes and may not be null-terminated. plen out parameter. the length of the re
turned password buffer. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description plugin which implement their own http networking stack (such as the java plugin) may want to use the standard http auth prompts and password managed of the browser. this function allows the plugin to ask the browser for http authentication information for a domain. unless the p...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
backwards compatibility reasons if you don't tell mozilla that you support it it will try to hand you an xt widget as a parent. however, before you do so you should make sure that the browser also supports xembed when the plugin is first initialized. if you've built your plugin so that it will support either xt or xembed you can include a fallback for older style hosting. if you haven't you can re
turn an error and the plugin will be ignored. it's good practice to do this in case people try to install your plugin for older versions of the browser that don't support xembed functionality. this is an incomplete example of what a piece of code might look like that tries to check for the proper mozilla version. this would be included in your np_initialize function. nperror np_initialize(npnetscapefu...
... [ other standard checks ] /* * make sure that the browser supports functionality we care * about. ...
...embedbool, (void *)&supportsxembed); if (err != nperr_no_error || supportsxembed != pr_true) re
turn nperr_incompatible_version_error; err = callnpn_getvalueproc(gnetscapefuncs.getvalue, null, npnvtoolkit, (void *)&toolkit); if (err != nperr_no_error || toolkit != npnvgtk2) re
turn nperr_incompatible_version_error; [ the rest of initialization ] re
turn err; } as you can see, if the browser says that it doesn't support xembed and doesn't use gtk2 as a toolkit we re
turn an error. if you re
turn with an error from your initialization function the plugin will not be used which avoids crashes and other problems. once you've verified that the browser has the compatibili...
...ms. once you've verified that the browser has the compatibility you require, you can modify your npp_getvalue call like so: nperror npp_getvalue(void *future, nppvariable variable, void *value) { nperror err = nperr_no_error; switch (variable) { case nppvpluginneedsxembed: *((prbool *)value) = pr_true; break; default: err = nperr_generic_error; } re
turn err; } once you have set those variables, it should be relatively easy to set up a plugin. just create a gtkplug that is the child of the xid passed in and it's just like using a standard gtk widget. other toolkits and out of process plugins it should be possible to use this interface to build a plugin that would run out of process as well as using other toolkits like qt to build plugins. since ...
Processing XML with E4X - Archive of obsolete content
th more than one matching element, you get back an xmllist: alert(person.likes.language.length()); // 2 as with the dom, * can be used to access all child nodes: alert(person.likes.*.length()); // 4 while the . operator accesses direct children of the given node, the .. operator accesses all children no matter how deeply nested: alert(person..*.length()); // 11 the length() method here re
turns 11 because both elements and text nodes are included in the resulting xmllist. objects representing xml elements provide a number of useful methods, some of which are illustrated below: todo: add all of the methods to the javascript reference, link from here alert(person.name.text()) // bob smith var xml = person.name.toxmlstring(); // a string containing xml var personcopy = person.copy(); ...
...s strongly discouraged. it is possible to create an xmllist using xml literal syntax without needing to create a well-formed xml document, using the following syntax: var xmllist = <> <lang>javascript</lang> <lang>python</lang> </>; the += operator can be used to append new elements to an xmllist within a document: languages.lang += <lang>ruby</lang>; note that unlike node lists re
turned by regular dom methods, xmllists are static and are not automatically updated to reflect changes in the dom. if you create an xmllist as a subset of an existing xml object and then modify the original xml object, the xmllist will not reflect those changes; you will need to re-create it to get the most recent updates: var languages = <languages> <lang>javascript</lang> <lang>python</lang...
... default default xml namespace = "http://www.w3.org/1999/xhtml"; // no need now to specify a namespace in the html...
... <age>46</age> </person> </people>; alert(people.person.(name == "joe").age); // alerts 46 filter expressions can even use javascript functions: function over40(i) { re
turn i > 40; } alert(people.person.(over40(parseint(age))).name); // alerts joe handling namespaces e4x is fully namespace aware. any xml object that represents a node or attribute provides a name() method which re
turns a qname object, allowing easy inspection of namespaced elements. default default xml namespace = "http://www.w3.org/1999/xhtml"; // no need now to specify a namespace in the html tag var xhtml = <html><head><title></title></head><body> <p>text</p></body></html>; alert(xhtml.head); // no need to specify a namespace on subelements here either non-default var xhtml = <html xmlns="ht...
Accessing XML children - Archive of obsolete content
nodes var elem1 = <foo> <bar/> </foo>; var elem2 = <red> <blue/> </red>; elem1.bar = elem2; replaces the <bar/> element with all of the content in elem2, giving: <foo> <red> <blue/> </red> <foo> xml lists many times, however, a single element will have two or more children of the same type. in this case, accessing foo.bar will re
turn an xml list object, of all child elements of the type "bar". important it is your responsibility to determine whether you have an xml list or a single element when using the . operator. e4x behaves no differently when re
turning these properties. the xml list behaves much like an array. var element = <foo> <bar baz="1">red</bar> <bar baz="2">blue</bar> ...
...e "bar". important it is your responsibility to determine whether you have an xml list or a single element when using the . operator. e4x behaves no differently when re
turning these properties. the xml list behaves much like an array. var element = <foo> <bar baz="1">red</bar> <bar baz="2">blue</bar> </foo>; var list = element.bar; list.length(); // re
turns 2 list[0]; // the first bar element list[1]; // the second bar element notice further that this list is "live" in the sense that changes made to the list are reflected back in the element that the list originally came from. list[1] = "green"; changes the xml document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> special types of nodes xml objects have methods for a...
...lected back in the element that the list originally came from. list[1] = "green"; changes the xml document to read <foo> <bar baz="1">red</bar> <bar baz="2">green</bar> </foo> special types of nodes xml objects have methods for accessing xml lists of certain common types of nodes as well. var a = <foo> some text <bar>not text</bar> more text </foo>; var list = a.text(); list.length(); // re
turns 2 list[0]; // re
turns " some text " list[1]; // re
turns " more text " you can similarly access comment nodes: xml.ignorecomments = false; var a = <foo> some <!-- abc --> text </foo>; var comments = a.comments(); alert(comments[0]); // re
turns <!-- abc --> the * selector will re
turn all child nodes in an xml list. var a = <foo> <bar/> <baz/> </foo>; var list = a.*; ...
...for instance <pets> <dog color="brown">fido</dog> <cat color="grey">fluffy</cat> </pets> e4x allows you to access the attributes of a particular element with the .@ operator. the most basic case would look something like. ...
ArrayBuffer.transfer() - Archive of obsolete content
description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. ...
...ffer's data and then is either truncated or zero-extended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state. syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer. newbytelength the byte length of the new arraybuffer object. re
turn value a new arraybuffer object. description the arraybuffer.transfer() method allows you to grow and detach arraybuffer objects. the ability to grow an arraybuffer without copying has the advantage of being much faster for large buffers (similar to realloc). the ability to detach an arraybuffer gives the developer explicit control over when the underlying memory is released. this avoids havin...
...ch always copies the whole thing to a new space of memory, but this function transfers data from one arraybuffer to another arraybuffer. ...
...sfer = function(source, length) { if (!(source instanceof arraybuffer)) throw new typeerror('source must be an instance of arraybuffer'); if (length <= source.bytelength) re
turn source.slice(0, length); var sourceview = new uint8array(source), destview = new uint8array(new arraybuffer(length)); destview.set(sourceview); re
turn destview.buffer; }; } specifications specification status comment arraybuffer.prototype.transfer proposal draft stage 2 draft ...
GetObject - Archive of obsolete content
syntax getobject([pathname] [, class]) parameters pathname full path and name of the file containing the object to retrieve. if pathname is omitted, class is required. class optional class of the object. the class argument uses the syntax appname.objectype and has these parts: appname name of the application providing the object. objectype type or class of object to create. ...
...rts: appname name of the application providing the object. objectype type or class of object to create. remarks the getobject function is not supported in internet explorer 9 standards mode, internet explorer 10 standards mode, internet explorer 11 standards mode, and windows store apps or later. use the getobject function to access an automation object from a file. assign the object re
turned by getobject to the object variable. for example: var cadobject; cadobject = getobject("c:\\cad\\schema.cad"); when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject re
turns a new object instance of the specified type. if the pathnameargument is omitt...
...to the object variable. for example: var cadobject; cadobject = getobject("c:\\cad\\schema.cad"); when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject re
turns a new object instance of the specified type. if the pathnameargument is omitted, getobject re
turns a currently active object of the specified type. if no object of the specified type exists, an error occurs. some applications allow you to activate part of a file. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. for information on how to create this string, see the documentation for the ap...
...t, or if you want to create the object with a file already loaded. if there is no current instance, and you don't want the object started with a file loaded, use the activexobject object. if an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times activexobject is executed. with a single-instance object, getobject always re
turns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, and internet explorer 8 standards. ...
Object.prototype.watch() - Archive of obsolete content
l objects, such as window. you can usually use setters and getters or proxies instead. the watch() method watches for a property to be assigned a value and runs a function when that occurs. syntax obj.watch(prop, handler) parameters prop the name of a property of the object on which you wish to monitor changes. handler a function to call when the specified property's value changes. re
turn value undefined. description watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the re
turn value in that property. a watchpoint can filter (or nullify) the value assignment, by re
turning a modified newval (or by re
turning oldval). if you delete a property for which a watchpoint has been set, that watchpoint do...
...ink to an anchor within the current document. however, window.location += '#myanchor' will call myhandler. note: calling watch() on an object for a specific property overrides any previous handler attached for that property. examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); re
turn newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an object's properties you can use watch to test any assignment to an object's properties. this example ensures that every person always has a valid name and an age between ...
...perties you can use watch to test any assignment to an object's properties. this example ensures that every person always has a valid name and an age between 0 and 200. ...
... ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
-side javascript functions to the browser. jaxer manages ajax calls behind the scenes to accomplish this. while most of the runat attribute values above are self explanatory, the server-proxy concept is best explained through example. consider the code in listing 4. listing 4 - demonstration of server and client context <script runat="server"> function exposed() { re
turn "exposed to the browser"; } function notexposed() { re
turn "can't see me!"; } </script> <script runat="client"> alert( exposed() ); alert( notexposed() ); </script> there are two blocks of scripts defined, one with runat set to server and the other set to client. this creates a strict separation of the two environments. as it stands, the code in the client block would throw an error since t...
...n the jaxer.proxies array. generally it's a best practice to use either the second or third strategy since in this case you are exposing only what's needed to the client. see listing 5 for an update to listing 1 to reflect this. ...
...ategy since in this case you are exposing only what's needed to the client. see listing 5 for an update to listing 1 to reflect this. ...
..._message, btn_comments ], renderto: "form-comments" }); }); </script> the code in listing 6 starts by hooking in the ext js library which is used to produce the ui elements of the form. next a script named validatecomments.js is hooked in with the runat attribute set to both. the function defined within this file checks the form to make sure it is complete, re
turning a boolean. the both context it operates within is a very powerful concept as we are able to use this code to check values entered in the form on both the client and server side. no custom validation libraries for each environment makes for rapid development with less risk for error. towards the bottom of the code are two div tags with ids form-comments and out-logger.
Plug-in Development Overview - Gecko Plugin API Reference
ngual" in your development environment. the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser loads each library and calls into the np_getmimedescription entry point. this exported c function should re
turn a string containing the type, extension list, and type description separated by colons. each mime types should be separated by semicolons. for example: image/xbm:xbm:x bitmap or for 2 mime types: image/xbm:xbm:x bitmap;image/png:png:portable network graphics. this information will then appear in the navigator.mimetypes dom object. npp_getvalue is called after the plug-in is initialized to get th...
...raphics. this information will then appear in the navigator.mimetypes dom object. npp_getvalue is called after the plug-in is initialized to get the scripting interface while np_getvalue is called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins. caution: gecko caches the values re
turned by these functions and will only call it if the plug-in's timestamp has changed. see bug 125469. mac os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmi...
...'s timestamp has changed. see bug 125469. mac os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information re
turned by this function. note: the resource method described below is deprecated. plugins should use the info.plist approach, and only use the following method as a supplement to support older browsers. if neither is present, gecko will check the plugins resources. 'str#' 128 should contain a list of mime types and file extensions in alternating strings. for example: str 128 mime type...
...ction operates like npn_posturl, except that it notifies the plug-in of the result when the operation completes. for information about using these methods, see urls. starting in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), you can get the origin of the document in a secure, convenient way by calling npn_getvalue() to retrieve the value of the variable npnvdocumentorigin. the re
turned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8. your plug-in must free the re
turned string's memory by calling npn_memfree() when you're done with it. getting version and ui information the netscape group of plug-in api methods provides some basic services to the plug-in. you can use these netscape methods: to identify the ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
child is allowed if (href === '' || href === null) { // points to same document if empty (null is equivalent to empty string) href = null; // set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('there must be an xpointer attribute present if "href" is empty an parse is "xml"'); re
turn false; } } else if (href.match(/#$/, '') || href.match(/^#/, '')) { alert('fragment identifiers are disallowed in an xinclude "href" attribute'); re
turn false; } var j; var xincludeparent = xinclude.parentnode; try { netscape.security.privilegemanager.enableprivi...
... switch (parse) { case 'text': // priority should be on media type: var contenttype = request.getresponseheader('content-type'); //text/xml; charset="utf-8" // send to get headers first? // fix: we test for file extensions as well in case file:// doesn't re
turn content type (as seems to be the case); can some other tool be uesd in ff (or ie) to detect encoding of local file? probably just need bom test since other encodings must be specified var patternxml = /\.(svg|xml|xul|rdf|xhtml)$/; if ((contenttype && contenttype.match(/[text|application]\/(.*)\+?xml/)) || (href.indexof('file://') === 0 && hr...
... responsetype = 'responsetext'; break; case null: case 'xml': responsetype = 'responsexml'; break; default: alert('xinclude element contains an invalid "parse" attribute value'); re
turn false; break; } request.send(null); if((request.status === 200 || request.status === 0) && request[responsetype] !== null) { response = request[responsetype]; if (responsetype === 'responsexml') { // apply xpointer (only xpath1() subs...
...trieval above failed var xifallbackchildren = xifallback.childnodes; // prepend any node(s) then remove xinclude for (j=0; j < xifallbackchildren.length ; j++) { xincludeparent.insertbefore(xifallbackchildren[j], xinclude); } xincludeparent.removechild(xinclude); } } } re
turn docu; } ...
HTML: A good basis for accessibility - Learn web development
semantic html doesn't take any longer to write than non-semantic (bad) markup if you do it consistently from the start of your project. even better, semantic markup has other benefits beyond accessibility: easier to develop with — as mentioned above, you get some functionality for free, plus it is arguably easier to understand. better on mobile — semantic html is arguably light...
...ty.html example (see the source code). open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/re
turn to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input. other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. note: different browsers may have different keyboard control options avail...
...indicated above, this value allows elements that are not normally tabbable to become tabbable. this is the most useful value of tabindex. tabindex="-1" — this allows not normally tabbable elements to receive focus programmatically, e.g., via javascript, or as the target of links. whilst the above addition allows us to tab to the buttons, it does not allow us to activate them via the enter/re
turn key. to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.keycode === 13) { // the enter/re
turn key document.activeelement.click(); } }; here we add a listener to the document object to detect when a button has been pressed on the keyboard. we check what button was pressed via the event object's keycode property; if it is the keycod...
...activeelement which gives us the element that is currently focused on the page. this is a lot of extra hassle to build the functionality back in. ...
HTML: A good basis for accessibility - Learn web development
semantic html doesn't take any longer to write than non-semantic (bad) markup if you do it consistently from the start of your project. even better, semantic markup has other benefits beyond accessibility: easier to develop with — as mentioned above, you get some functionality for free, plus it is arguably easier to understand. better on mobile — semantic html is arguably light...
...ty.html example (see the source code). open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements. the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/re
turn to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input. other form elements have different controls, for example, the <select> element can have its options displayed and cycled between using the up and down arrow keys. note: different browsers may have different keyboard control options avail...
...indicated above, this value allows elements that are not normally tabbable to become tabbable. this is the most useful value of tabindex. tabindex="-1" — this allows not normally tabbable elements to receive focus programmatically, e.g., via javascript, or as the target of links. whilst the above addition allows us to tab to the buttons, it does not allow us to activate them via the enter/re
turn key. to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.keycode === 13) { // the enter/re
turn key document.activeelement.click(); } }; here we add a listener to the document object to detect when a button has been pressed on the keyboard. we check what button was pressed via the event object's keycode property; if it is the keycod...
...activeelement which gives us the element that is currently focused on the page. this is a lot of extra hassle to build the functionality back in. ...
The HTML5 input types - Learn web development
a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server. but it should not be considered an exhaustive security measure! your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to
turn off, so malicious users can still easily send bad data through to your server. read website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. note that a@b is a valid email address according to the default provided constraints. this is because the email input type allows intranet email addre...
... allows intranet email addresses by default. to implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the client-side form validation article later on. note: if the data entered is not an email address, the :invalid pseudo-class will match, and the validitystate.typemismatch property will re
turn true. search field search fields are intended to be used to create search boxes on pages and apps. this type of field is set by using the value search for the type attribute: <input type="search" id="search" name="search"> the main difference between a text field and a search field is how the browser styles its appearance. often, search fields are rendered with rounded corners; they also som...
...display and pick a date with time with no specific time zone information. <input type="datetime-local" name="datetime" id="datetime"> month <input type="month"> creates a widget to display and pick a month with a year. <input type="month" name="month" id="month"> time <input type="time"> creates a widget to display and pick a time value. while time may display in 12-hour format, the value re
turned is in 24-hour format. <input type="time" name="time" id="time"> week <input type="week"> creates a widget to display and pick a week number and its year. weeks start on monday and run to sunday. additionally, the first week 1 of each year contains the first thursday of that year—which may not include the first day of the year, or may include the last few days of the previous year. <input...
...nt with its type attribute set to the value color: <input type="color" name="color" id="color"> when supported, clicking a color control will tend to display the operating system's default color picking functionality for you to actually make your choice with. the following screenshot taken on firefox for macos provides an example: and here is a live example for you to try out: the value re
turned is always a lowercase 6-value hexidecimal color. note: color inputs are not supported in internet explorer. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: html5 controls. summary that brings us to the ...
Video and audio content - Learn web development
rmat for the codec used to encode that media. different formats are used for audio tracks versus video tracks. each audio track is encoded using an audio codec, while video tracks are encoded using (as you probably have guessed) a video codec. as we talked about before, different browsers support different video and audio formats, and different container formats (like mp3, mp4, and webm, which in
turn can contain different types of video and audio). for example: a webm container typically packages vorbis or opus audio with vp8/vp9 video. this is supported in all modern browsers, though older versions may not work. an mp4 container often packages aac or mp3 audio with h.264 video. this is also supported in all modern browsers, as well as internet explorer. the ogg container tends to use v...
...k stored within an mpeg or mpeg-2 container. this is especially interesting since while most browsers don't support using mpeg media in the <video> and <audio> elements, they may still support mp3 due to its popularity. an audio player will tend to play an audio track directly, e.g. an mp3 or ogg file. these don't need containers. media file support in browsers why do we have this problem? it
turns out that several popular formats, such as mp3 and mp4/h.264, are excellent but are encumbered by patents; that is, there are patents covering some or all of the technology that they're based upon. in the united states, patents covered mp3 until 2017, and h.264 is encumbered by patents through at least 2027. because of those patents, browsers that wish to implement support for those codecs must ...
... autoplay makes the audio or video start playing right away, while the rest of the page is loading. you are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying. loop makes the video (or audio) start playing again whenever it finishes. this can also be annoying, so only use if really necessary. muted causes the media to play with the sound
turned off by default. poster the url of an image which will be displayed before the video is played. it is intended to be used for a splash screen or advertising screen. preload used for buffering large files; it can take one of three values: "none" does not buffer the file "auto" buffers the media file "metadata" buffers only the metadata for the file you can find the above exam...
...srclang="en"> </video> this will result in a video that has subtitles displayed, kind of like this: for more details, please read adding captions and subtitles to html5 video. you can find the example that goes along with this article on github, written by ian devlin (see the source code too.) this example uses some javascript to allow users to choose between different subtitles. note that to
turn the subtitles on, you need to press the "cc" button and select an option — english, deutsch, or español. note: text tracks also help you with seo, since search engines especially thrive on text. text tracks even allow search engines to link directly to a spot partway through the video. active learning: embedding your own audio and video for this active learning, we'd (ideally) like you to...
Introduction to events - Learn web development
eady seen events and event handlers used in many of the examples, but let's recap just to cement our knowledge. in the following example, we have a single <button>, which when pressed, makes the background change to a random color: <button>change color</button> button { margin: 10px }; the javascript looks like so: const btn = document.queryselector('button'); function random(number) { re
turn math.floor(math.random() * (number+1)); } btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } in this code, we store a reference to the button inside a constant called btn, using the document.queryselector() function. we also define a function that re
turns a random number. the third par...
...ent programming environments. ways of using web events there are a number of ways to add event listener code to web pages so it runs when the associated event fires. in this section, we review the various mechanisms and discuss which ones you should use. event handler properties these are the properties that exist to contain event handler code we have seen most frequently during the course. re
turning to the above example: const btn = document.queryselector('button'); btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } the onclick property is the event handler property being used in this situation. it is essentially a property like any other available on the button (e.g. btn.text...
...; document.body.style.backgroundcolor = rndcol; } btn.onclick = bgchange; there are many different event handler properties available. let's experiment. first, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. it's just a copy of the simple random color example we've played with already. now try changing btn.onclick to the following different values in
turn, and observing the results in the example: btn.onfocus and btn.onblur — the color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button. these are often used to display information about filling in form fields when they are focused, or displaying an error message if a form field is filled with an in...
...it is not a good idea to mix up your html and your javascript, as it becomes hard to parse — keeping your javascript separate is best practice; if it is in a separate file you can apply it to multiple html documents. even in a single file, inline event handlers are not a good idea. one button is ok, but what if you had 100 buttons? you'd have to add 100 attributes to the file; it would quickly
turn into a maintenance nightmare. with javascript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this: const buttons = document.queryselectorall('button'); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = bgchange; } note that another option here would be to use the foreach() built-in method availa...
Introduction to web APIs - Learn web development
, this complexity is abstracted away from you by the api. third-party apis are not built into the browser by default, and you generally have to retrieve their code and information from somewhere on the web. for example, the twitter api allows you to do things like displaying your latest tweets on your website. it provides a special set of constructs you can use to query the twitter service and re
turn specific information. relationship between javascript, apis, and other javascript tools so above, we talked about what client-side javascript apis are, and how they relate to the javascript language. let's recap this to make it clearer, and also mention where other javascript tools fit in: javascript — a high-level scripting language built into browsers that allows you to implement func...
...n objects your code interacts with apis using one or more javascript objects, which serve as containers for the data the api uses (contained in object properties), and the functionality the api makes available (contained in object methods). note: if you are not already familiar with how objects work, you should go back and work through our javascript objects module before continuing. let's re
turn to the example of the web audio api — this is a fairly complex api, which consists of a number of objects. the most obvious ones are: audiocontext, which represents an audio graph that can be used to manipulate audio playing inside the browser, and has a number of methods and properties available to manipulate that audio. mediaelementaudiosourcenode, which represents an <audio> element cont...
...eparate "event handlers" sections. we already saw a number of event handlers in use in our web audio api example above. to provide another example, instances of the xmlhttprequest object (each one represents an http request to the server to retrieve a new resource of some kind) has a number of events available on them, for example, the load event is fired when a response has been successfully re
turned containing the requested resource, and it is now available. the following code provides a simple example of how this would be used: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.responsetype = 'json'; request.send(); request.onload = function() { const superheroes = ...
...nes specify the location of the resource we want to fetch, create a new instance of a request object using the xmlhttprequest() constructor, open an http get request to retrieve the specified resource, specify that the response should be sent in json format, then send the request. the onload handler function then specifies what we do with the response. we know the response will be successfully re
turned and available after the load event has fired (unless an error occurred), so we save the response containing the re
turned json in the superheroes variable, then pass it to two different functions for further processing. they have additional security mechanisms where appropriate webapi features are subject to the same security considerations as javascript and other web technologies (for example...
Video and Audio APIs - Learn web development
this article shows you how to do common tasks such as creating custom playback controls. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to use browser apis to control video and audio playback. ...
...usemedia); now to define playpausemedia() — add the following, again at the bottom of your code: function playpausemedia() { if(media.paused) { play.setattribute('data-icon','u'); media.play(); } else { play.setattribute('data-icon','p'); media.pause(); } } here we use an if statement to check whether the video is paused. the htmlmediaelement.paused property re
turns true if the media is paused, which is any time the video is not playing, including when it is set at 0 duration after it first loads. if it is paused, we set the data-icon attribute value on the play button to "u", which is a "paused" icon, and invoke the htmlmediaelement.play() method to play the media. on the second click, the button will be toggled back again — the "play" icon will be sh...
...ment to check whether the active class has been set on the rwd button, indicating that it has already been pressed. the classlist is a rather handy property that exists on every element — it contains a list of all the classes set on the element, as well as methods for adding/removing classes, etc. we use the classlist.contains() method to check whether the list contains the active class. this re
turns a boolean true/false result. if active has been set on the rwd button, we remove it using classlist.remove(), clear the interval that has been set when the button was first pressed (see below for more explanation), and use htmlmediaelement.play() to cancel the rewind and start the video playing normally. if it hasn't yet been set, we add the active class to the rwd button using classlist.a...
...isplay currently breaks if the video is an hour long or more (well, it won't display hours; just minutes and seconds). can you figure out how to change the example to make it display hours? because <audio> elements have the same htmlmediaelement functionality available to them, you could easily get this player to work for an <audio> element too. try doing so. ...
Object-oriented JavaScript for beginners - Learn web development
pace), making it easy to structure and access; objects are also commonly used as data stores that can be easily sent across the network. defining an object template let's consider a simple program that displays information about the students and teachers at a school. here we'll look at oop theory in general, not in the context of any specific programming language. to start this off, we could re
turn to our person object type from our first objects article, which defines the generic data and functionality of a person. there are lots of things you could know about a person (their address, height, shoe size, dna profile, passport number, significant personality traits ...) , but in this case we are only interested in showing their name, age, gender, and interests, and we also want to be able to...
...l, we'd like you to make a new local copy of the oojs.html file we saw in our first objects article. a simple example let's start by looking at how you could define a person with a normal function. ...
...\'m ' + obj.name + '.'); }; re
turn obj; } you can now create a new person by calling this function — try the following lines in your browser's javascript console: const salva = createnewperson('salva'); salva.name; salva.greeting(); this works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and re
turn it? fortunately, javascript provides us with a handy shortcut, in the form of constructor functions — let's make one now! replace your previous function with the following: function person(name) { this.name = name; this.greeting = function() { alert('hi! i\'m ' + this.name + '.'); }; } the constructor function is javascript's version of a class. notice that it has all the featu...
...shortcut, in the form of constructor functions — let's make one now! replace your previous function with the following: function person(name) { this.name = name; this.greeting = function() { alert('hi! i\'m ' + this.name + '.'); }; } the constructor function is javascript's version of a class. notice that it has all the features you'd expect in a function, although it doesn't re
turn anything or explicitly create an object — it basically just defines properties and methods. notice also the this keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's name property will be equal to the name value passed to the constructor call, and the greeting() method will use the name value passed to the constructor ca...
Vue conditional rendering: editing existing todos - Learn web development
">editing {{label}}</span> </button> <button type="submit" class="btn btn__primary"> save <span class="visually-hidden">edit for {{label}}</span> </button> </div> </form> </template> <script> export default { props: { label: { type: string, required: true }, id: { type: string, required: true } }, data() { re
turn { newlabel: this.label }; }, methods: { onsubmit() { if (this.newlabel && this.newlabel !== this.label) { this.$emit("item-edited", this.newlabel); } }, oncancel() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing:...
...to first define it inside our data() property. the "delete" button, when clicked, will delete the todo item via an event handler function called deletetodo(). in this handler we’ll emit an item-deleted event to our parent component so the list can be updated. let's define our click handlers, and the necessary isediting flag. ...
...operty — another advantage of computed properties is that they preserve reactivity, meaning (among other things) that their state is saved when the template changes like ours is now doing. so, let's implement the fix: remove the following line from inside our data() property: isdone: this.done, add the following block below the data() { } block: computed: { isdone() { re
turn this.done; } }, now when you save and reload, you'll find that the problem is solved — the checkbox state is now preserved when you switch between todo item templates. understanding the tangle of events one of the most potentially confusing parts is the tangle of standard and custom events we've used to trigger all the interactivity in our app. to understand this better, it is a good id...
...ide app.vue, see above), and finally clears the new label <input>. todoitem.vue checkbox <input> listens for change event. result: checkbox-changed event emitted when the checkbox is checked/unchecked (which is then listened for inside app.vue; see above). "edit" <button> listens for click event. result: toggletoitemeditform() method is invoked, which toggles this.isediting to true, which in
turn displays the todo item's edit form on re-render. "delete" <button> listens for click event. result: deletetodo() method is invoked, which emits the item-deleted event (which is then listened for inside app.vue; see above) <to-do-item-edit-form> listens for: item-edited event emitted by the onsubmit() method inside the todoitemeditform component when the form is successfully submitted. res...
Adding a new todo form: Vue events, methods, and models - Learn web development
u can see the results of the console.log() we added inside our onsubmit() method. binding data to inputs with v-model next up, we need a way to get the value from the form's <input> so we can add the new to-do item to our todoitems data list. the first thing we need is a data property in our form to track the value of the to-do. add a data() method to our todoform component object that re
turns a label field. we can set the initial value of the label to an empty string. your component object should now look something like this: export default { methods: { onsubmit() { console.log("form submitted"); } }, data() { re
turn { label: "" }; } }; we now need some way to attach the value of the new-todo-input <input> field to the label field. vue ...
.... replace the console.log() in the onsubmit() method with the following: this.$emit("todo-added"); next, go back to app.vue and add a methods property to your component object containing an addtodo() method, as shown below. for now, this method can just log to-do added to the console. ...
...t added to the list. to fix that, we can prevent the todo-added event from firing when name is empty. since name is already being trimmed by the .trim directive, we only need to test for the empty string. go back to your todoform component, and update the onsubmit() method like so. if the label value is empty, let's not emit the todo-added event. onsubmit() { if(this.label === "") { re
turn; } this.$emit('todo-added', this.label); } try your form again. now you will not be able to add empty items to the to-do list. using v-model to update an input value there's one more thing to fix in our todoform component — after submitting, the <input> still contains the old value. but this is easy to fix — because we're using v-model to bind the data to the <input> in todof...
... thing to fix in our todoform component — after submitting, the <input> still contains the old value. but this is easy to fix — because we're using v-model to bind the data to the <input> in todoform, if we set the name parameter to equal an empty string, the input will update as well. update your todoform component’s onsubmit() method to this: onsubmit() { if(this.label === "") { re
turn; } this.$emit('todo-added', this.label); this.label = ""; } now when you click the "add" button, the "new-todo-input" will clear itself. summary excellent. we can now add todo items to our form! our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now. in the next article, we'll concentrate on fixing this, looking at the diff...
Rendering a list of Vue components - Learn web development
ile we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. each to-do item will be represented by an object with a name and a done property. add a few sample to-do items, along the lines of those seen below. this way you have some data available for rendering using v-for. export default { name: 'app', components: { todoitem }, data() { re
turn { todoitems: [ { label: 'learn vue', done: false }, { label: 'create a vue project with the cli', done: true }, { label: 'have fun', done: true }, { label: 'create a to-do list', done: false } ] }; } }; now that we have a list of items, we can use the v-for directive to display them. directives are applied to elements like other attributes. in ca...
...niqueid from 'lodash.uniqueid'; next, add an id field to each element in your todoitems array, and assign each of them a value of uniqueid('todo-'). ...
.../ul> now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique ids, taken from the object in the app component. chance for a slight refactor there's one little bit of refactoring we can do here. instead of generating the id for the checkboxes inside your todoitem component, we can
turn the id into a prop. while this isn't strictly necessary, it makes it easier for us to manage since we already need to create a unique id for each todo item anyway. add a new prop to your todoitem component — id. make it required, and make its type a string. to prevent name collisions, remove the id field from your data attribute. you are no longer using uniqueid, so you need to remove the...
..., so you need to remove the import uniqueid from 'lodash.uniqueid'; line, otherwise your app will throw an error. the <script> contents in your todoitem component should now look something like this: export default { props: { label: {required: true, type: string}, done: {default: false, type: boolean}, id: {required: true, type: string} }, data() { re
turn { isdone : this.done, } }, } now, over in your app.vue component, pass item.id as a prop to the todoitem component. your app.vue template should now look like this: <template> <div id="app"> <h1>my to-do list</h1> <ul> <li v-for="item in todoitems" :key="item.id"> <to-do-item :label="item.label" :done="item.done" :id="item.id"></to-do-item> <...
Application cache implementation overview
ens in nshttpchannel::opencacheentry(). all top level document loading (navigation) channels are set chooseapplicationcache flag, which happens in nsdocshell::douriload(). channels having that flag set are searching for nsiapplicationcache object prior inspecting normal http cache. nsiapplicationcacheservice::chooseapplicationcache is given the url the channel is about to load. it synchronously re
turns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace. if no nsiapplicationcache object has been found, there is no offline cache to load from and the load continues a usual way by loading from normal http cache, further steps are not executed. the channel remembers the nsiapplicationca...
...ache group. loading subresources of a document using offline cache each sub resource loading channel is set inheritapplicationcache flag. this flag is by default true, but it is dropped by nsdocshell::douriload() to false only for top level document loading channels. the inheritapplicationcache flag instructs the channel to do getinterface on its callbacks for nsiapplicationcachecontainer. this re
turns the top level document the whole load group is bound to. this is the same document object that is associated the nsiapplicationcache object during the “cache selection algorithm” in nscontentsink::processofflinemanifest() described in “associating the top level document with offline cache” chapter above. nsiapplicationcachecontainer is then queried for nsiapplicationcache object. if foun...
......
...redirected, the original update invokes onerror and 'finishes'. on canceled state loadcompleted invokes onerror event and 'finishes' the update (what transits the state to finished). canceled can be set only by call to nsofflinecacheupdate::cancel() public method that also cancels all running items downloads immediately. on finished state loadcompleted just early re
turns. finished state is set when updated is 'finished' and is the last state the update transits to after invoking one of the final dom notifications (onnoupdate, onupdaterady or onerror.) ...
Performance
ce(); main.onchange(statechange); function statechange() { services.ppmm.broadcastasyncmessage("my-addon:update-configuration", {newconfig: main.serialize()}) } // processmodule.jsm const exported_symbols = ['getmaincopy']; var maincopy; services.cpmm.addmessagelistener("my-addon:update-configuration", function(message) { maincopy = message.data.newconfig; }) funtion getmaincopy() { re
turn maincopy; } // framescript.js components.utils.import("resource://my-addon/processmodule.jsm") // getmaincopy() used by other functions don't register observers (and other callbacks to global services) in a frame script bad: //framescript.js services.obs.addobserver("document-element-inserted", { observe: function(doc, topic, data) { if(doc.ownerglobal.top != content) ret...
...since the code calls to the parent process to check whether a specific request can be allowed it would slow down all pag...
...since the code calls to the parent process to check whether a specific request can be allowed it would slow down all page loads, as web pages generally issue dozen...
...chitecture where the parent has the authoritative state and replicates it to the child processes in advance so they can act based on their local copy. see the previous chapter on how to efficiently replicate addon state to each process. clean up on addon unload bad: all the previous examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user
turning it off and on will load to unload/reload events. not handling those properly can lead to duplicate or conflicting code execution, especially when messages are sent. it can also lead to conflicts between the old and new code. under some circumstances it may even cause exceptions when attempting to register something twice under the same id. better: // addon.js function onunload() { services...
Using the Browser API
in and out of the page. to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one. in any case, you should at least download the repo and refer to the code as you read the sections below. the html an <iframe> is
turned into a browser iframe by setting the mozbrowser attribute on it: <iframe src="http://mozilla.org" mozbrowser> in addition, the <iframe> can be loaded in its own child process — separate to the page embedding this frame — by including the remote attribute. <iframe src="http://hostname.tld" mozbrowser remote> warning: this last attribute is necessary for security reasons if you plan to l...
...lse; console.log("it's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("it's not possible to navigate the history forward."); } } } so here we have functions to detect whether we can navigate forwards/backwards in the history at any point. these use htmliframeelement.getcangoback() and htmliframeelement.getcangoforward(), which re
turn a boolean defining whether backward/forward navigation is possible at this point in the history. if true is re
turned, the relevant button is disabled, and if false is re
turned, 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.getcangob...
...ossible to navigate the history backward."); } }); } implementing the url bar the url bar for our simple browser is a <form> containing a single text <input>. when you tap the url bar, you can enter a url using the built-in firefox os keyboard (although note that we haven't implemented anything sophisticated in this app, like autofilling the http://, etc.). when you press the keyboard's re
turn button, the 'submit' event is fired, which we handle like this: urlform.addeventlistener('submit',function(e) { e.preventdefault(); browser.src = urlbar.value; urlbar.blur(); }); we first call preventdefault() to stop the form just submitting and reloading the page — which is really not what we want. we then set the browser iframe's src attribute to equal the value of the url bar, which...
...h the following function, which runs the htmliframeelement.stop() method to stop the page loading if the button is displaying a cross, and the htmliframeelement.reload() method to reload the page otherwise. stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); implementing the search bar let's now
turn our attention to implementing browser search using the browser api. tap the "s" button and try it out. try searching for "firefox" on the default page when the app first loads. so how do we do this? first, we declare a searchactive variable as false, which influences behaviour later on. then, we disable the "previous" and "next" search item buttons so that they don't run anything unless there ...
IPDL Type Serialization
essage type declared in ipc_message.h. each type specializes ipc::paramtraits as follows: namespace ipc { template <> struct paramtraits<mytype> { typedef mytype paramtype; static void write(message* amsg, const paramtype& aparam) { // implement serialization here } static bool read(const message* amsg, void** aiter, paramtype* aresult) { // implement deserialization here. re
turn false if deserialization failed } }; } // namespace ipc the standard ipdl types (integers, floats, and xpcom strings) already have serializers. other types need to have serializers written for them explicitly. in many cases a serializer can be written by combining existing serializers. most structures can be serialized in this manner: struct examplestruct { int i; nscstring j; int k[4...
... serializers and deseriali...
... serializers and deserializers are security-sensitive and must always receive two reviews from module owners who understand ipc serial...
... serializers and deserializers are security-sensitive and must always receive two reviews from module owners who understand ipc serialization well. if in...
DeferredTask.jsm
ess 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(); re
turn value re
turns 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 pending task. void cancel(); arm request the execution of the task after the delay specified on construction. multiple calls don't intr...
...ll restart from its original value in case the "arm" method is called again. void disarm(); finalize ensure that any pending task is executed from start to finish, while preventing any attempt to arm the timer again. ...
...; finalize ensure that any pending task is executed from start to finish, while preventing any attempt to arm the timer again. if the task is running and the timer is armed, then one last execution from start to finish will happen again, immediately after the current execution terminates; then the re
turned promise will be resolved. if the task is running and the timer is not armed, the re
turned promise will be resolved when the current execution terminates. if the task is not running and the timer is armed, then the task is started immediately, and the re
turned promise resolves when the new execution terminates. if the task is not running and the timer is not armed, the method re
turns a resolved promise. promise finalize(); example firefox 28 note this section describe...
..., the task cannot be canceled anymore. it is, however, possible to arm the timer again during the execution of the task, in which case the task will need to finish before the timer is started again, thus guaranteeing a time of inactivity between executions that is at least equal to the provided delay. the "finalize" method can be used to ensure that the task terminates properly. the promise it re
turns is resolved only after the last execution of the task is finished. to guarantee that the task is executed for the last time, the method prevents any attempt to arm the timer again. if the timer is already armed when the "finalize" method is called, then the task is executed immediately. if the task was already running at this point, then one last execution from start to finish will happen again...
FxAccountsOAuthClient.jsm
soauthclient.jsm javascript module provides a way for browser services to authenticate with the firefox accounts oauth server. components.utils.import("resource://gre/modules/fxaccountsoauthclient.jsm"); creating a new fxaccountsoauthclient new fxaccountsoauthclient(object options); method overview launchwebflow(); teardown(); attributes parameters object re
turns the set of parameters that initialized the firefox accounts oauth flow. oncomplete function gets called when the firefox accounts oauth flow successfully completes. first and only argument is an object that has "state" and "code" properties. constructor fxaccountsoauthclient() creates and re
turns a new fxaccountsoauthclient object. fxaccountsoauthclient fxaccountsoauthclien...
... oauth_uri - the fxa oauth api server uri, versioned. example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri. ...
...ect. fxaccountsoauthclient fxaccountsoauthclient( object options object parameters string client_id string state string oauth_uri string content_uri [optional] string scope [optional] string action [optional] string authorizationendpoint ); parameters client_id - oauth id re
turned from client registration. state - oauth state value that will be re
turned to the client as-is upon redirection. oauth_uri - the fxa oauth api server uri, versioned. example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri. example: "https://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized. [optional] action - if provided, should be either "signup" or "signin". parameters ...
...ample: "https://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized. [optional] action - if provided, should be either "signup" or "signin". parameters set of parameters to initialize the firefox accounts oauth flow. authorizationendpoint optional optional authorization endpoint for the oauth server. default: /authorization re
turn value a newly created fxaccountsoauthclient object implementing the methods described in this article. methods launchwebflow() opens a new tab at the firefox accounts oauth authorization url. registers a webchannel listener and sets up a callback if needed. parameters none teardown() call this function to manually release all channels and callbacks that are in use by this client. parame...
PopupNotifications.jsm
windows, so you don't have to do it yourself in most extensions. method overview void locationchange(); notification getnotification(id, browser); void remove(notification); notification show(browser, id, message, anchorid, mainaction, secondaryactions, options); properties attribute type description ispanelopen boolean re
turns true if the notification panel is currently visible, false if it is not. methods locationchange() the consumer can call this method to let the popup notification module know that the current browser's location has changed. this lets the notification service update the active notifications as appropriate. note: you shouldn't need to call this when using the popupnotifications object in ...
...ange(); parameters none. getnotification() retrieve a notification object associated with the browser/id pair. notification getnotification( string id xulelement browser ); parameters id the notification id to search for. browser the xul <xul:browser> element whose notifications should be searched. if null, the currently selected <xul:browser>'s notifications will be searched. re
turn value the corresponding notification object, or null if no such notification exists. remove() removes the specified notification. void remove( notification notification ); parameters notification the notification object representing the notification to remove. show() adds a new popup notification, displaying it to the user. notification show( browser, id, message, anchorid...
...iteral containing fields that define the button to draw in the notification panel. see notification actions below for details. secondaryactions an array of notification action objects; these are used to populate the drop-down menu on the notification panel's button. options a javascript object containing optional properties for the notification. see notification options below for details. re
turn value re
turns the notification object corresponding to the added notification. notification actions notification action objects describe the user interface for actions associated with the notification. the main action is used to describe the button presented in the notification panel, while secondary actions are displayed in the drop-down menu associated with the button. a notification action...
...ssage/actions if necessary during this notification. "shown" the notification has become visible. this can be fired multiple times as notifications are dismissed and redisplayed. the notification object each notification is represented by a notification object. this object contains all the data necessary to present and manage the notification, and has one method. the anchorelement property re
turns the notification's anchor element. the remove()method removes the notification. ...
Localization and Plurals
pluralform.jsm"); methods: get these methods make use of the browser's current locale specified by chrome://global/locale/intl.properties's pluralrule value. ...
...gs provided by your default extension locale. for example, your extension localized for english with plural rule #1, which expects 2 plural forms, is installed on a localized version of firefox with plural rule #4, which expects 3 forms: /** * create a pair of plural form functions for the given plural rule number. ...
...ish with plural rule #1, which expects 2 plural forms, is installed on a localized version of firefox with plural rule #4, which expects 3 forms: /** * create a pair of plural form functions for the given plural rule number. ...
...mynum = 10; // in the case of irish, the value 10 uses plural form #4, so "form 4" is printed print(get(dummynum, dummytext)); in this example, the irish plural rule was hardcoded, but this could be a value specified in the .properties file. so for your extension, specify a pluralrule value in the .properties, and call pluralform.makegetter(pluralrulefromproperties), making sure to save the 2 re
turned functions. (you can use destructured assignment in javascript 1.7 to keep things clean.) the re
turned functions act just like pluralform.get() and pluralform.numforms(), except for the specified plural rule instead of the default plural rule. credits plural form code first implemented for bug 394516 - figure out a remaining-time rounding scheme for minutes -> hours/days plural rules and fami...
Creating localizable web applications
ss on <html/> or <body/> as well, in order to easily change css rules like in the example below. snippet 1. bad: <html lang="en"> snippet 2. good: css: html[dir='rtl'] foo { /* rtl-specific rules for the foo element */ } body.rtl foo { /* rtl-specific rules for the foo element */ } html/php: <?php function isrtl($locale) { $rtl_locales = array('ar', 'fa', 'he'); re
turn in_array($locale, $rtl_locales); } ?> <html lang="<?= $locale?>" dir="<?= isrtl($locale) ? 'rtl' : 'ltr' ?>" > <body class="<?= $locale?> <?= isrtl($locale) ? 'rtl' : 'ltr' ?>"> </body> </html> notice that <body/> is given a class equal to the current locale. this is useful to add minor corrective rules to the css that apply only for selected locales. for example, for locales that te...
... structure. note that some strings might be hidden in libraries' code (e.g. error messages), or in javascript libraries and scripts. if you are using pure html instead of gettext to localize your webapp, consider using an additional gettext-like format such as .lang to streamline localizers' work with repeating content. this is useful for strings occurring in the webapp multiple times, like "re
turn to top", "comments", "click to see larger image" etc. might be also helpful for headers and footers, if you're not using templates to display them. in most of the cases though, you should use gettext whenever technically possible (i.e. the server's php has been built with gettext support). localize the date format localizing the date format is as easy as localizing any other string. just let t...
...zing the date format is as easy as localizing any other string. just let the localizers localize the format specification string. snippet 1. bad: $persona['date'] = date("n/j/y", strtotime($persona['approve'])); snippet 2. ...
...("n/j/y", strtotime($persona['approve'])); snippet 2. good: $persona['date'] = date(_("n/j/y"), strtotime($persona['approve'])); localize the number format you can make the number format localizable using the information re
turned by localeconv() in php. snippet 1. bad: printf(_("%s mb>"), $size); snippet 2. good: function num_format($num, $decimals) { $locale_info = localeconv(); re
turn number_format($num, $decimals, $locale_info['decimal_point'], $locale_info['thousands_sep']); } printf(_("%s mb"), num_format($size, 1)); wrap as few html tags as possible when wrapping the localizable content with the gettext function calls, put all the code that irrelevant to localization outside the function call. snippet 1. bad: <?= _("<a href=\"https://addons.mozilla.org/firefox/downlo...
Memory reporting
code that cannot be modified. a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ... methods ... } here are what the measurement functions (yes, functions) should look like for this class. size_t mystring::sizeofexcludingthis(mozilla::mallocsizeof amallocsizeof) const { re
turn amallocsizeof(mbuffer); } size_t mystring::sizeofincludingthis(mozilla::mallocsizeof amallocsizeof) const { re
turn amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } (note that sizeofexcludingthis and sizeofincludingthis aren't overrides of methods on a global base class that is common to all reporters. these names are just a convention that is commonly followed. that said, note that ...
...ngle global mystring object. mystring *gmystring; class mystringreporter moz_final : public nsimemoryreporter { moz_define_malloc_size_of(mallocsizeof) public: ns_decl_isupports ns_method collectreports(nsihandlereportcallback* ahandlereport, nsisupports* adata) { // btw: if gmystring wasn't a pointer, you'd use // |gmystring.sizeofexcludingthis(mallocsizeof)| instead. ...
...:mallocsizeof that is specific to this memory reporter (and will be identified as such in dmd's output). and moz_collect_report is a macro that makes things a bit shorter. an example involving inheritance things are a little trickier when inheritance is involved. an example: class b { virtual foo() { ... } virtual size_t sizeofexcludingthis(nsmallocsizeoffun amallocsizeof) const { re
turn ... // measure things pointed to by b-specific fields } virtual size_t sizeofincludingthis(nsmallocsizeoffun amallocsizeof) const { re
turn amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } // data members }; class d : public b { virtual foo() { ... } virtual size_t sizeofexcludingthis(nsmallocsizeoffun amallocsizeof) const override { size_t n = b::sizeofexclu...
...s(nsmallocsizeoffun amallocsizeof) const { re
turn amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } // data members }; class d : public b { virtual foo() { ... } virtual size_t sizeofexcludingthis(nsmallocsizeoffun amallocsizeof) const override { size_t n = b::sizeofexcludingthis(amallocsizeof); n += ... // measure things pointed to by d-specific fields re
turn n; } virtual size_t sizeofincludingthis(nsmallocsizeoffun amallocsizeof) const override { re
turn amallocsizeof(this) + sizeofexcludingthis(amallocsizeof); } // data members }; things to note about sizeofexcludingthis when it is virtual. if d has data members that point to other objects, then d::sizeofexcludingthis must override b::sizeofexcludingthis. otherwise, if we have a b...
NSPR Types
this chapter describes the most common nspr types. other chapters describe more specialized types when describing the functions that use them. calling convention types are used for externally visible functions and globals. algebraic types of various lengths are used for integer algebra. miscellaneous types are used for representing size, pointer difference, boolean values, and re
turn values. for information on naming conventions for nspr types, functions, and macros, see nspr naming conventions. calling convention types these types are used to support cross-platform declarations of prototypes and implementations: pr_extern is used for declarations of external functions or variables. pr_implement is used for definitions of external functions or variables. pr_callback is used for ...
...nitions and declarations of functions that are called via function pointers. a typical example is a function implemented in an application but called from a shared library. ...
...prfloat64 native os integer types these types are most appropriate for automatic variables. they are guaranteed to be at least 16 bits, though various architectures may define them to be wider (for example, 32 or even 64 bits). these types are never valid for fields of a structure. ...
...nce types boolean types status type for re
turn values size type prsize pointer difference types types for pointer difference. variables of these types are suitable for storing a pointer or pointer subtraction. these are the same as the corresponding types in libc. prptrdiff pruptrdiff boolean types type and constants for boolean values. ...
PR EnumerateAddrInfo
info( void *enumptr, const praddrinfo *addrinfo, pruint16 port, prnetaddr *result); parameters the function has the following parameters: enumptr the index pointer of the enumeration. to begin an enumeration, this argument is set to null. to continue an enumeration (thereby getting successive addresses from the praddrinfo structure), the value should be set to the function's last re
turned value. the enumeration is complete when a value of null is re
turned. addrinfo a pointer to a praddrinfo structure re
turned by pr_getaddrinfobyname. port the port number to be assigned as part of the prnetaddr structure. this parameter is not checked for validity. result on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the result of the...
... description pr_enumerateaddrinfo is a stateless enumerator. ...
... description pr_enumerateaddrinfo is a stateless enumerator. the principle input, the praddrinfo structure, is not modified. ...
...the port number to be assigned as part of the prnetaddr structure. this parameter is not checked for validity. result on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the result of the call is not null. re
turns the function re
turns the value you should specify in the enumptr parameter for the next call of the enumerator. if the function re
turns null, the enumeration is ended. description pr_enumerateaddrinfo is a stateless enumerator. the principle input, the praddrinfo structure, is not modified. ...
PR_Initialize
n. in addition to establishing the sequence of operations, pr_initialize implicitly calls pr_cleanup on exiting the primordial function. syntax #include <prinit.h> printn pr_initialize( prprimordialfn prmain, printn argc, char **argv, pruintn maxptds); parameters pr_initialize has the following parameters: prmain the function that becomes the primordial thread's root function. re
turning from prmain leads to termination of the process. argc the length of the argument vector, whether passed in from the host's program-launching facility or fabricated by the actual main program. this approach conforms to standard c programming practice. argv the base address of an array of strings that compromise the program's argument vector. this approach conforms to standard c programming ...
.... argc the length of the argument vector, whether passed in from the host's program-launching facility or fabricated by the actual main program. this approach conforms to standard c programming practice. argv the base address of an array of strings that compromise the program's argument vector. this approach conforms to standard c programming practice. maxptds this parameter is ignored. ...
... of the argument vector, whether passed in from the host's program-launching facility or fabricated by the actual main program. this approach conforms to standard c programming practice. argv the base address of an array of strings that compromise the program's argument vector. this approach conforms to standard c programming practice. maxptds this parameter is ignored. ...
...promise the program's argument vector. this approach conforms to standard c programming practice. maxptds this parameter is ignored. re
turns the value re
turned from the root function, prmain. description pr_initialize initializes the nspr runtime and places nspr between the caller and the runtime library. this allows main to be treated like any other function, signaling its completion by re
turning and allowing the runtime to coordinate the completion of the other threads of the runtime. pr_initialize does not re
turn to its caller until all user threads have terminated. the priority of the main (or primordial) thread is pr_priority_normal. the thread may adjust its own priority by using pr_setthreadpriority. ...
PR_WaitSemaphore
the "test and decrement" operation is performed atomically. ...
... the "test and decrement" operation is performed atomically. ...
... the "test and decrement" operation is performed atomically. ...
...syntax #include <pripcsem.h> nspr_api(prstatus) pr_waitsemaphore(prsem *sem); parameter the function has the following parameter: sem a pointer to a prsem structure re
turned from a call to pr_opensemaphore. re
turns prstatus description pr_waitsemaphore tests the value of the semaphore. if the value of the semaphore is > 0, the value of the semaphore is decremented and the function re
turns. if the value of the semaphore is 0, the function blocks until the value becomes > 0, then the semaphore is decremented and the function re
turns. the "test and decrement" operation is performed atomically. ...
NSS 3.12.4 release notes
ointexten the old documentation of the expression matching syntax rules was incorrect, and the new corrected documentation is as follows for public nssutil functions (see portreq.h): port_regexpvalid port_regexpsearch port_regexpcasesearch these functions will match a string with a shell expression. the expressions accepted are based loosely on the expressions accepted by zsh. expected re
turn values: non_sxp if exp is a standard string invalid_sxp if exp is a shell expression, but invalid valid_sxp if exp is a valid shell expression expression matching rules: * matches anything ? matches one character \ will escape a special character $ matches the end of the string bracketed expressions: [abc] matches one occurence of a, b, or c. [^abc] matches any character except a, b, or c. to...
...n changed to 1.75. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. ...
...bug 495717: unable to compile nss/cmd/certutil/keystuff.c on wince bug 496961: provide truncated hmac ...
...08: pkix_pl_crldp_create will always fail if dp->distpointtype != generalname bug 504456: exploitable heap overflow in nss shell expression (filename globbing) parsing bug 505559: need function to identify the one and only default internal private key slot. bug 505561: need a generic function a la secmod_openuserdb() that can be used on non-softoken modules. ...
NSS 3.12.5 release_notes
wed (see sslerr.h) new context initialization and shutdown functions see nss.h for details. the 2 new functions are: nss_initcontext nss_shutdowncontext parameters for these functions are used to initialize softoken. these are mostly strings used to internationalize softoken. memory for the strings are owned by the caller, who is free to free them once nss_contextinit re
turns. if the string parameter is null (as opposed to empty, zero length), then the softoken default is used. these are equivalent to the parameters for pk11_configurepkcs11(). see the following struct in nss.h for details: nssinitparametersstr other new functions in secmod.h: secmod_getskipfirstflag secmod_getdefaultmoddbflag in prlink.h nss_securememcmp ...
...this function is changed from unsigned char * to const unsigned char *. pk11_configurepkcs11 (see nss.h) the name of some parameters have been slightly changed ("des" became "desc"). deprecated headers the header file key.h is deprecated. please use keyhi.h instead. ...
... the name of some parameters have been slightly changed ("des" became "desc"). deprecated headers the header file key.h is deprecated. please use keyhi.h instead. additional documentation in pk11pub.h: the caller of pk11_derencodepublickey should free the re
turned secitem with a secitem_freeitem(..., pr_true) call. pk11_readrawattribute allocates the buffer for re
turning the attribute value. the caller of pk11_readrawattribute should free the data buffer pointed to by item using a secitem_freeitem(item, pr_false) or port_free(item->data) call. in secasn1.h: if both pool and dest are null, the caller should free the re
turned secitem with a secitem_freeitem(..., pr_true) call. if pool is null but dest is not null, the caller should free the data buff...
... bug 525056: timing attack against ssl3ext.c:ssl3_serverhandlesessionticketxtn() bug 5266...
FC_GetInfo
the version is 2.20 (major=0x02, minor=0x14). manufacturerid: the pkcs #11 library manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. flags: should be 0. ...
...the version is 2.20 (major=0x02, minor=0x14). manufacturerid: the pkcs #11 library manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. flags: should be 0. ...
...the version is 2.20 (major=0x02, minor=0x14). manufacturerid: the pkcs #11 library manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. flags: should be 0. ...
...spaces to 32 characters and not null-terminated. flags: should be 0. librarydescription: description of the library, "nss internal crypto services", padded with spaces to 32 characters and not null-terminated. libraryversion: pkcs #11 library version number, for example, 3.11 (major=0x03, minor=0x0b). a user may call fc_getinfo without logging into the token (to assume the nss user role). re
turn value fc_getinfo always re
turns ckr_ok. fc_getinfo should re
turn ckr_arguments_bad if pinfo is null. fc_getinfo should re
turn ckr_cryptoki_not_initialized if the library is not initialized. examples note the use of the %.32s format string to print the manufacturerid and librarydescription members of the ck_info structure. #include <assert.h> #include <stdio.h> ck_function_list_ptr pfunct...
ssltyp.html
are not shared objects. when an application makes a copy of a particular key structure that already exists in memory, ssl makes a deep copy--that is, it makes a whole new copy of that object. when you call seckey_destroyprivatekey, the function both frees the memory and sets all the bits to zero. never alter the contents of a key structure. treat the structure as read only. secstatus the re
turn value for many ssl functions. syntax #include <seccomon.h> typedef enum { secwouldblock = -2, secfailure = -1, secsuccess = 0 } secstatus; enumerators the enum includes the following enumerators: secwouldblock reserved for internal use. secfailure the operation failed. to fi...
...cstatus; enumerators the enum includes the following enumerators: secwouldblock reserved for internal use. secfailure the operation failed. to find out why, call pr_geterror. secsuccess the operation succeeded. in this case the value re
turned by pr_geterror is meaningless. managing secitem memory these functions are available for managing the memory associated with secitem structures and the structures to which they point. secitem_freeitem secitem_zfreeitem secitem_freeitem frees the memory associated with a secitem structure. syntax #include <prtypes.h> secstatus secitem_freeitem ( secitem *item, ...
...( secitem *item, prbool freeitem) parameter this function has the following parameter: item a pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description this function frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also frees the item structure itself. secitem_zfreeitem ze...
...( secitem *item, prbool freeitem) parameter this function has the following parameter: item a pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. re
turns the function re
turns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description this function is similar to secitem_freeitem, except that it overwrites the structures to be freed with zeroes before it frees them. zeros and frees the memory associated with the structure to which the specified item points, when...
Tutorial: Embedding Rhino
ing javascript "methods" adding counter to runscript runscript: a simple embedding about the simplest embedding of rhino possible is the runscript example. all it does it read a script from the command line, execute it, and print a result. here's an example use of runscript from a shell command line: $ java runscript "math.cos(math.pi)" -1 $ java runscript "function f(x){re
turn x+1} f(7)" 8 note that you'll have to have both the rhino classes and the runscript example class file in the classpath. let's step through the body of main one line at time. entering a context the code context cx = context.enter(); creates and enters a context. a context stores information about the execution environment of a script. initializing standard objects the code scriptable sc...
...code context cx = context.enter(); creates and enters a context. a context stores information about the execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and re
turn a scope object that we use in later calls. collecting the arguments this code is standard java and not specific to rhino. it just collects all the arguments and concatenates them together. string s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } evaluating a script the code object result = cx.evaluatestring(scope, s, "<cmd>", 1, null); uses the context cx to evaluate a st...
...es and functions, extracting values and calling javascript functions. this is illustrated in the runscript3 example. this example adds the ability to print the value of variable x and the result of calling function f. both x and f are expected to be defined by the evaluated script. for example, $ java runscript3 "x = 7" x = 7 f is undefined or not a function. $ java runscript3 "function f(a) { re
turn a; }" x is not defined. f("my args") = my arg using javascript variables to print out the value of x, we add the following code: object x = scope.get("x", scope); if (x == scriptable.not_found) { system.out.println("x is not defined."); } else { system.out.println("x = " + context.tostring(x)); } calling javascript functions to get the function f, call it, and print the result, we ...
...he implementation is empty. public counter () { } the method jsconstructor defines the javascript constructor that was called with the expression new counter(7) in the javascript code above. public void jsconstructor(int a) { count = a; } class name the class name is defined by the getclassname method. this is used to determine the name of the constructor. public string getclassname() { re
turn "counter"; } dynamic properties dynamic properties are defined by methods beginning with jsget_ or jsset_. the method jsget_count defines thecount property. public int jsget_count() { re
turn count++; } the expression c.count in the javascript code above results in a call to this method. defining javascript "methods" methods can be defined using the jsfunction_ prefix. here we define reset...
64-bit Compatibility
bit on 64-bit platforms: intn, uintn jsintn, jsuintn, jsbool general problems with pointers when performing bitwise operations on pointer values, make sure that both operands are 64-bit. the compiler can implicitly sign or zero extend operands with unintended side effects. for example, consider this code: #define pointer_tagbits 3 static inline uintptr_t unmaskpointer(uintptr_t v) { re
turn v & ~pointer_tagbits; } the value 3 will be inverted to 0xfffffffc, then zero-extended to 0x00000000fffffffc - a subtle and nasty bug, assuming it is unintended. the best way to fix this is to make types explicit, such as: const uintptr_t pointer_tagbits = 3 or by using a cast inside the macro. this sort of bug happens surprisingly often - see bug 501324, bug 512866 for example. amd64 pointers ...
...se lir_piadd (which will be lir_qiadd) needs both operands to be 64-bit. ...
... both operands to be 64-bit. ...
...s2(lir_piadd, arrayins, lir->ins_u2p(lir->ins2i(lir_mul, indexins, sizeof(int))) ), 0); what's pointer-width in tracerecorder? ...
JS::AutoVectorRooter
bool empty() const determines if the array is empty (length is zero). bool append(const t &v) appends an element v to the array. ...
...other) appends all elements of other to the array. bool insert(t *p, const t &val) inserts an element val at the position specified by p. void infallibleappend(const t &v) appends an element v to the array. for use when space has already been reserved. void popback() pops an element from the array. t popcopy() pops an element from the array and re
turns it. bool growby(size_t inc) grows the array by inc. bool resize(size_t newlength) resizes the array to newlength. void clear() clears all elements. bool reserve(size_t newlength) reserves the array with newlength. js::mutablehandle<t> operator[](size_t i) re
turns to the i-th element as js::mutablehandle<t>. js::handle<t> ...
...t inc) grows the array by inc. bool resize(size_t newlength) resizes the array to newlength. void clear() clears all elements. bool reserve(size_t newlength) reserves the array with newlength. js::mutablehandle<t> operator[](size_t i) re
turns to the i-th element as js::mutablehandle<t>. js::handle<t> operator[](size_t i) const re
turns to the i-th element as js::handle<t>. ...
... array to newlength. void clear() clears all elements. bool reserve(size_t newlength) reserves the array with newlength. js::mutablehandle<t> operator[](size_t i) re
turns to the i-th element as js::mutablehandle<t>. js::handle<t> operator[](size_t i) const re
turns to the i-th element as js::handle<t>. const t *begin() const re
turns a pointer to the first element. t *begin() re
turns a pointer to the first element. const t *end() const re
turns a pointer to the element next to the last element. t *end() re
turns a pointer to the element next to the last element. range all() re
turns the range of the array. const t &back() const re
turns the last element. descript...
JS::PersistentRooted
ontext* cx) initialize with optional initial value (if not provided, it will be initialized with the initial value of the type). added in spidermonkey 38 void init(jscontext* cx, t initial) void init(jsruntime* rt) void init(jsruntime* rt, t initial) void reset() reset the value to initial value of the type. added in spidermonkey 38 t& get() re
turns ptr. const t& get() const operator const t&() const const t& operator->() const t* address() re
turns a pointer to ptr. const t* address() const persistentrooted<t>& operator=(const t& p) sets the value of ptr. persistentrooted<t>& operator=(const persistentrooted<t>& other) bool operator!=(const t& other) const comp...
...f can be a global variable. // js::persistentrootedvalue persistentval; static bool setpersistent(jscontext* cx, unsigned argc, js::value* vp) { js::callargs args = callargsfromvp(argc, vp); // set persistent value. ...
... args.rval().setundefined(); re
turn true; } static bool getpersistent(jscontext* cx, unsigned argc, js::value* vp) { js::callargs args = callargsfromvp(argc, vp); // get persistent value. js::rootedvalue val(cx, persistentval.ref()); // or // js::rootedvalue val(cx, *persistentval); // [spidermonkey 38] // js::rootedvalue val(cx, persistentval); args.rval().set(val); re
turn true; } static const jsfunctionspec functions[] = { js_fn("getpersistent", getpersistent, 1, 0), js_fn("setpersistent", setpersistent, 0, 0), js_fs_end }; int main(int argc, const char* argv[]) { // initialize runtime // ... // initialize here persistentval.construct(rt, js::nullvalue()); // or // persistentval = new js::persistentrootedvalue(rt, js::nullvalue()); // [spi...
... int main(int argc, const char* argv[]) { // initialize runtime // ... // initialize here persistentval.construct(rt, js::nullvalue()); // or // persistentval = new js::persistentrootedvalue(rt, js::nullvalue()); // [spidermonkey 38] // persistentval.init(rt, js::nullvalue()); // initialize context and global // ... if (!js_definefunctions(cx, glob, functions)) re
turn 1; // use those function in javascript. // destroy context. // ... // destroy here // required because of maybe or pointer. // persistentrooted itself doesn't require explicit destruction. persistentval.destroy(); // or // delete persistentval; // [spidermonkey 38] // destruction is not required. // destroy runtime. // ... } see also mxr id search for js...
JSDeletePropertyOp
unicode property identifier) or an integer (element index). succeeded bool * out parameter. receives the result of deletion. description jsdeletepropertyop callback is a hook that applications may install to be called at some point during property access. a jsdeletepropertyop may be installed on a jsclass to hook property deletes. if a jsdeletepropertyop does nothing and re
turns true, then property delete is unaffected. it proceeds as normal. this callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then re
turning false. the operation then fails, and the error is propagated to the caller. otherwise the callback must re
turn true, and the property operation proceeds. jsclass hooks jsclass offers the following hoo...
...this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a typeerror in strict mode code. ...
...peration proceeds. jsclass hooks jsclass offers the following hook: jsclass.delproperty is called during most property deletions, even when obj has no property named id. if an error occurred, re
turn false as per normal jsapi error practice. if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and re
turn true. this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a typeerror in strict mode code. if no error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and re
turn true. t...
...etion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and re
turn true. this hook is not called when the target property is jsprop_permanent and is an own property of the target object. an attempt to delete such a property fails early, re
turning false, before the delproperty hook is reached. js_clearscope does not call this hook either. see also mxr id search for jsdeletepropertyop bug 858677 jsclass ...
JSFastNative
engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). argc unsigned int the number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its jsfunctionspec). vp jsval * the arguments, including the this argument, the re
turn-value slot, and the callee function object are accessible through this pointer using macros described below. description the callback should use the following macros to access the fields of vp: macro name description js_callee(cx, vp) re
turns the function object that was called, as a jsval. native methods must not call js_callee after calling js_set_rval. (t...
...e slot, and the callee function object are accessible through this pointer using macros described below. description the callback should use the following macros to access the fields of vp: macro name description js_callee(cx, vp) re
turns the function object that was called, as a jsval. native methods must not call js_callee after calling js_set_rval. (the re
turn value and the callee are stored in the same stack slot.) js_this(cx, vp) re
turns the this argument as a jsval, or jsval_null on error. native methods must not call js_this after calling js_set_rval. (js_this may call js_callee.) js_this_object(cx, vp) re
turns the this argument as a jsobject *, or null on error. native methods must not call js_this_object af...
...s the this argument as a jsval, or jsval_null on error. native methods must not call js_this after calling js_set_rval. (js_this may call js_callee.) js_this_object(cx, vp) re
turns the this argument as a jsobject *, or null on error. native methods must not call js_this_object after calling js_set_rval. (js_this_object may call js_callee.) js_argv(cx, vp) re
turns the argv pointer. this points to element 0 of an array of argc jsvals, the arguments supplied by the caller. js_rval(cx, vp) re
turns the jsval that is currently in the re
turn-value slot. ...
... native methods must not call js_this_object after calling js_set_rval. (js_this_object may call js_callee.) js_argv(cx, vp) re
turns the argv pointer. this points to element 0 of an array of argc jsvals, the arguments supplied by the caller. js_rval(cx, vp) re
turns the jsval that is currently in the re
turn-value slot. js_set_rval(cx, vp, value) sets the re
turn value of the native function. it is safe to call this multiple times within a single call to a jsfastnative. if the jsfastnative re
turns js_true, the last value passed to this macro will be re
turned to the caller. on success, the callback must call js_set_rval (at least once) and re
turn js_true. on error or exception, it must re
turn js_false. to create a jsfunctionspec that points to a js...
JSObjectOps.lookupProperty
dex of the property to look up. objp jsobject ** out parameter. if the property is found, the callback stores the object on which the property was found in *objp. propp jsproperty ** out parameter. on success, the callback stores in *propp a pointer to the property, if it exists, or null if it doesn't. ...
...ter. if the property is found, the callback stores the object on which the property was found in *objp. propp jsproperty ** out parameter. on success, the callback stores in *propp a pointer to the property, if it exists, or null if it doesn't. description look for id in obj and its prototype chain, re
turning js_false on error or exception, js_true on success. on success, re
turn null in *propp if id was not found. ...
...t on which the property was found in *objp. propp jsproperty ** out parameter. on success, the callback stores in *propp a pointer to the property, if it exists, or null if it doesn't. description look for id in obj and its prototype chain, re
turning js_false on error or exception, js_true on success. on success, re
turn null in *propp if id was not found. if id was found, re
turn the first object searching from obj along its prototype chain in which id names a direct property in *objp, and re
turn a non-null, opaque property pointer in *propp. if jslookuppropop succeeds and re
turns with *propp non-null, that pointer may be passed as the prop parameter to a jsattributesop, as a short-cut that bypasses id re-lookup. in any case, a non-null *propp result after a successful l...
... names a direct property in *objp, and re
turn a non-null, opaque property pointer in *propp. if jslookuppropop succeeds and re
turns with *propp non-null, that pointer may be passed as the prop parameter to a jsattributesop, as a short-cut that bypasses id re-lookup. in any case, a non-null *propp result after a successful lookup must be dropped via jsobjectops.dropproperty. note: a successful re
turn with non-null *propp means the implementation may have locked *objp and added a reference count associated with *propp, so callers should not risk deadlock by nesting or interleaving other lookups or any obj-bearing ops before dropping *propp. ...
JSPropertyOp
ropertyop callbacks are hooks that applications may install to be called at some point during property access. a jspropertyop may be installed on an individual property as a getter or setter; or it may be installed on a jsclass to hook property gets, sets, or adds. these different cases are described in more detail in the sections below. if a jspropertyop or jsstrictpropertyop does nothing and re
turns true, then property get, set, or add is unaffected. it proceeds as normal. each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then re
turning false. the operation then fails, and the error is propagated to the caller. otherwise the callback must re
turn true, and the property operation proceeds. getters and setters when a...
...time javascript code accesses the property's value using the syntax obj.prop or obj[propname]. it is also called when the property's value is accessed via jsapi functions such as js_getproperty or (less obviously) js_callfunctionname. on entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. the callback may modify *vp. on success, the callback re
turns true and the value left in *vp is re
turned to the script or jsapi caller. setters. the setter callback is called each time javascript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. it is also called when the property is set via jsapi functions such as js_setproperty. on entry, *vp contains the value being assigned to the property. the callbac...
...to the script or jsapi caller. setters. the setter callback is called each time javascript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. it is also called when the property is set via jsapi functions such as js_setproperty. on entry, *vp contains the value being assigned to the property. the callback may modify *vp. on success, the callback re
turns true. if the property has a stored value, it is then updated to the value left in *vp after the callback. as of spidermonkey 1.7, the value of a property assignment expression, like (a.length = x), is the value of *vp after the setter is called. this is typically the value of the left-hand side after assignment, as opposed to the value of the right-hand side, as required by ecma 262-3 §11.13. ...
...r for new properties. see the section on getters and setters above. jsclass.getproperty is also called when a program attempts to get a property that does not exist on obj or any prototype. on entry, *vp contains the property's stored value, or undefined if the property doesn't exist or doesn't have a stored value. the callback may modify *vp. on success, the post-callback value of *vp is re
turned to the caller. this value also becomes the property's new stored value, if the property exists and has a stored value. jsstrictpropertyop jsclass.setproperty is the default setter for new properties. see the section on getters and setters above. a property's setter is called each time the property is assigned. hence when a script assigns to a nonexisting property, first the object'...
JS_EncodeString
escription cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext.. str jsstring * / js::handlestring a string to encode. description js_encodestring and js_encodestringtoutf8 convert the specified javascript str to a c string (an array of 8-bit chars). if js_cstringsareutf8 is true, then the re
turned string of js_encodestring is utf-8, and the conversion is lossless. otherwise the high byte is simply dropped from each char16_t. js_encodestringtoutf8 encode the string to utf-8. the array re
turned by js_encodestring on success is allocated as though by a call to js_malloc. the caller may modify it and is responsible for freeing it. note that for non-ascii strings, if js_cstringsareutf8 is ...
...is utf-8, and the conversion is lossless. otherwise the high byte is simply dropped from each char16_t. js_encodestringtoutf8 encode the string to utf-8. the array re
turned by js_encodestring on success is allocated as though by a call to js_malloc. the caller may modify it and is responsible for freeing it. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can re
turn a corrupted copy of the contents of the string. use js_getstringchars to access the 16-bit characters of a javascript string without conversions or copying. ...
...s though by a call to js_malloc. the caller may modify it and is responsible for freeing it. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can re
turn a corrupted copy of the contents of the string. use js_getstringchars to access the 16-bit characters of a javascript string without conversions or copying. on success, js_encodestring and js_encodestringtoutf8 re
turn a pointer to the char array, which is null-terminated. ...
... strings, if js_cstringsareutf8 is false, these functions can re
turn a corrupted copy of the contents of the string. use js_getstringchars to access the 16-bit characters of a javascript string without conversions or copying. on success, js_encodestring and js_encodestringtoutf8 re
turn a pointer to the char array, which is null-terminated. ...
JS_PreventExtensions
ibit new properties. in javascript this may be accomplished using the object.preventextensions method. the similar jsapi method is js_preventextensions. the failure-mode information below is new as of spidermonkey 36. before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a typeerror and re
turn false. unlike object.preventextensions, js_preventextensions doesn't necessarily throw a typeerror if the object couldn't be made non-extensible. there are instead two modes of failure: through internal error, and because the object denied the attempt. the first case occurs when something went wrong internally, not necessarily because the object chose not to become non-extensible. for exampl...
...nsible. there are instead two modes of failure: through internal error, and because the object denied the attempt. the first case occurs when something went wrong internally, not necessarily because the object chose not to become non-extensible. for example, if making the object requires an allocation, and that allocation fails, out-of-memory might be reported, and js_preventextensions would re
turn false. this might also occur if the object is a proxy, and some internal state of the proxy means that no coherent behavior is possible. for example, if the object is a revocable proxy that has been revoked, it makes no sense to say that an attempt to prevent extensions either succeeded or failed: it's a category error. thus in this case js_preventextensions will throw an error. var target = ...
...textensions(cx, proxy, &succeeded); // // rv == false, succeeded is indeterminate the second case occurs when no internal error is encountered, but the object simply refuses to be made non-extensible. for example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-call value of *succeeded. ...
...nsible; this refusal would show up in the post-call value of *succeeded. var target = {}; var handler = { preventextensions: function(obj) { re
turn false; } }; var obj = new proxy(target, handler); // bool succeeded; // bool rv = js_preventextensions(cx, obj, &succeeded); // // rv == true, succeeded == false note that as with most jsapi methods, *succeeded is only set if js_preventextensions re
turns true (that is, does not fail). thus you should always check the re
turn value of js_preventextensions, and only if that is true check the value of *succeeded. see also mxr id search for js_preventextensions bug 1113369 -- added result parameter ...
JS_PropertyStub
ther, they are convenient stand-ins anywhere the jsapi requires callbacks of certain types. examples at jsclass illustrate how stub functions can be used. js_propertystub is of type jspropertyop, the type of getter callback. it can be used in jsclass.addproperty, and jsclass.getproperty. it behaves exactly like a property callback that accepts the default property behavior: it does nothing and re
turns true. js_strictpropertystub is of type jsstrictpropertyop, the type of setter callback. it can be used in jsclass.setproperty. it behaves exactly like a property callback that accepts the default property behavior: it does nothing and re
turns true. js_deletepropertystub is of type jsdeletepropertyop, the type of setter callback. it can be used in jsclass.delproperty. it behaves exactly like a ...
... js_convertstub is a stub for jsclass.convert. ...
... js_convertstub is a stub for jsclass.convert. its behavior is the same as the default conversion behavior for objects. ...
... js_convertstub is a stub for jsclass.convert. its behavior is the same as the default conversion behavior for objects. ...
JS_SameValue
uced in spidermonkey 1.8.1 determines if two jsvals are the same, as determined by the samevalue algorithm in ecmascript 262, 5th edition. samevalue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that nan is the same as nan. ...
...he same, as determined by the samevalue algorithm in ecmascript 262, 5th edition. samevalue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that nan is the same as nan. ...
...ermined by the samevalue algorithm in ecmascript 262, 5th edition. samevalue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that nan is the same as nan. the samevalue algorithm is equivalent to the following javascript: function samevalue(v1, v2) { if (v1 === 0 && v2 === 0) re
turn 1 / v1 === 1 / v2; if (v1 !== v1 && v2 !== v2) re
turn true; re
turn v1 === v2; } syntax // added in spidermonkey 45 bool js_samevalue(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *same); // obsolete since jsapi 39 bool js_samevalue(jscontext *cx, jsval v1, jsval v2, bool *same); name type description cx jscontext * pointer to a js context from which to derive runtime information. requir...
... jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1 js::handle<js::value> / jsval the first value. v2 js::handle<js::value> / jsval the second value. description js_samevalue determines whether two values are the same, re
turning true or false accordingly. this method is infallible. see also mxr id search for js_samevalue js_strictlyequal js_looselyequal bug 1132045 -- use handle ...
JS_SetContextCallback
pointer to a jscontext which the callback may use to call into jsapi functions. this is the context which was just created, or is about to be destroyed. for example, the callback my call js_getcontextprivate(cx) in order to free up resources previously allocated by js_setcontextprivate. contextop unsigned see jscontextop. for future compatibility the callback must do nothing and re
turn true if any other value is passed. data void * data specified in js_setcontextcallback. added in spidermonkey 31 typedef enum jscontextop { jscontext_new, jscontext_destroy } jscontextop; enumeration meaning jscontext_new js_newcontext successfully created a new jscontext instance. the callback can initialize the instance as required. if the c...
...ny other value is passed. data void * data specified in js_setcontextcallback. added in spidermonkey 31 typedef enum jscontextop { jscontext_new, jscontext_destroy } jscontextop; enumeration meaning jscontext_new js_newcontext successfully created a new jscontext instance. the callback can initialize the instance as required. ...
... in js_setcontextcallback. added in spidermonkey 31 typedef enum jscontextop { jscontext_new, jscontext_destroy } jscontextop; enumeration meaning jscontext_new js_newcontext successfully created a new jscontext instance. the callback can initialize the instance as required. if the callback re
turns js_false, the instance will be destroyed and js_newcontext re
turns null. in this case the callback is not called again. jscontext_destroy one of js_destroycontext, js_destroycontextnogc, or js_destroycontextmaybegc was called. the callback may perform its own cleanup and must always re
turn true. in a debug build, if the callback re
turns false, the js engine will halt with an assertion. description js_setcontextcallback specifies a callback fun...
...tmaybegc was called. the callback may perform its own cleanup and must always re
turn true. in a debug build, if the callback re
turns false, the js engine will halt with an assertion. description js_setcontextcallback specifies a callback function that is automatically called when jscontexts are created or destroyed. only one callback function may be specified per js runtime. this function re
turns the previous context callback, if any, else null. see also mxr id search for js_setcontextcallback js_newcontext js_destroycontext js_destroycontextnogc js_destroycontextmaybegc js_getcontextprivate js_setcontextprivate bug 845545 ...
JS_malloc
loc and js_free only) pointer to a previously allocated region of memory to resize or deallocate. nbytes size_t (js_malloc and js_realloc only) amount of space, in bytes, to allocate. s const char * (js_strdup only) pointer to a null-terminated string. s must not be null. description js_malloc allocates a region of memory nbytes in size. ...
...re
turns a pointer to the beginning of the region. as with the standard c function malloc, memory allocated by js_malloc is uninitialized. js_realloc tries to change the allocation size of the region of memory at p to nbytes. failing that, js_realloc allocates a new region of size nbytes and copies as much of the existing data in p as will fit to the new region. then it frees the region at p and re
turns a pointer to the new region. apart from whatever is copied, any newly allocated space is uninitialized. js_realloc(cx, null, nbytes) behaves exactly like js_malloc(cx, nbytes). when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and re
turns null. js_strdup allocates a copy of the null-terminated string s. on success, it re
turns a pointer to the copy. if any of these three functi...
...js_free deallocates a region of memory allocated a previous call to js_malloc, js_realloc, or js_strdup. if p is null, js_free does nothing. once the region of memory is freed, the application must not use it again. ...
...implementation detail. future releases may implement these functions differently. js_realloc code sample realloc is famously tricky to use correctly. ...
Using the Places history service
tle when displayed in the ui. this is used for bookmark titles.this function may be removed if the bookmark service is changed. nsinavhistoryservice.setpagedetails: used to set all of the global bits associated with a url. it is designed for synchronizing or backup services. basic querying of the history system nsiglobalhistory2.isvisited: called by gecko when rendering links. when isvisited re
turns true, the link gets the "visited" style. otherwise, the link is colored as unvisited. nsiglobalhistory3.getgeckoflags: retrieves information previously set using setgeckoflags. it is not yet implemented in the places history system. nsibrowserhistory.lastpagevisited: contains the uri of the last page visited. this is used when the preference is set that causes the last page in new windows. ns...
... nsibrowserhistory.lastpagevisited: contains the uri of the last page visited. this is used when the preference is set that causes the last page in new windows. nsibrowserhistory.count: the number of pages in history. this is used by the "clear history" button to determine if there are any pages in history. because actually counting all the pages in history is expensive,navhistory will always re
turn the value 0 or 1. 0 is re
turned when there is no history, 1 is re
turned when there are one or more pages in history.deprecated, use hashistoryentries instead. nsinavhistoryservice.hashistoryentries: exactly the same as nsibrowserhistory.count, except with a better name and actually re
turning a boolean. preferred over "count". nsinavhistory.canadduri: determines whether the given uri will be sto...
...uri: determines whether the given uri will be stored by the history system. many types of uris, such as "chrome:" uris, are not stored when adduri is called. this function allows you to determine whether it will be or not. advanced querying see querying places for more detailed examples on how to used the advanced querying functionality of navhistory. nsinavhistoryservice.getnewquery: re
turns a new query object initialized to the default values. you can pass this to executequeries(). nsinavhistoryservice.getnewqueryoptions: re
turns a new query options object initialized to the default values. you can pass this to executequeries(). nsinavhistoryservice.executequery: runs a query with a single query object and options. all the parameters set on the query object will be anded together...
...cutequery: runs a query with a single query object and options. all the parameters set on the query object will be anded together. nsinavhistoryservice.executequeries: runs multiple query objects as a query. the parameters within on query as anded together as in executequery(), then the results of the different queries in the array are ored together. nsinavhistoryservice.queriestoquerystring: re
turns a serialized version of the queries as a "place:" uri. you should not count on this format, always use this function instead of hard-coding your own query strings. nsinavhistoryservice.querystringtoqueries: converts a serialized query ("place:" uri) back to the actual query objects and options. miscellaneous nsinavhistoryservice.addobserver: adds a history observer, which will be notified of ...
extIPreferenceBranch
ring the name of the branch root. all readonly attribute nsivariant array of extipreference listing all preferences in this branch. events readonly attribute extievents the events object for the preferences supports: "change" methods has() check to see if a preference exists. boolean has(in astring aname) parameters aname the name of preference re
turn value true if the preference exists, false if not get() gets an object representing a preference extipreference get(in astring aname) parameters aname the name of preference re
turn value a preference object, or null if the preference does not exist getvalue() gets the value of a preference. re
turns a default value if the preference does not exist. nsivariant getvalue(in astring an...
...preference. re
turns a default value if the preference does not exist. nsivariant getvalue(in astring aname, in nsivariant adefaultvalue) parameters aname the name of a preference adefaultvalue the default value of a preference. this will be passed back to you without any processing and can be something which would not be valid as a preference. for example, null/undefined/an object. re
turn value the value of the preference or the given default value if preference does not exists. the use of a variant as the re
turn value means that to javascript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur. a quoted string in the preference file will always appear as a string, even if the value of the string is "true" or "fal...
...ing is "true" or "false". an integer preference appears as a javascript number, and a boolean appears as a javascript boolean. there are no other types supported by the preference subsystem. setvalue() sets the value of a preference with the given name. ...
...s the value of a preference with the given name. void setvalue(in astring aname, in nsivariant avalue) parameters aname the name of a preference avalue the value of a preference re
turn value reset() resets all preferences in a branch back to their default values. note: this function has not been implemented and will raise an exception. ...
Fun With XBL and XPConnect
ocompletesession"> <![cdata[ components.classes['component://netscape/messenger/autocomplete&type=addrbook']. getservice(components.interfaces.nsiautocompletesession); ]]> </property> so we've defined a property on the widget called autocompletesession. the initial value of this property evaluates to an xp-connect object. now accesses to autocompletesession will re
turn the xp-connect object. exposing the xpcom interfaces one somewhat nasty trick you need to do is to manually expose the interfaces of the xpcom object that you want your widget to support. all you have to do is specifically defining a method on the xbl widget which forwards the method call to the xpcom object. <method name="autocomplete"> <argument name="asearchstring"/> <argume...
...asty trick you need to do is to manually expose the interfaces of the xpcom object that you want your widget to support. all you have to do is specifically defining a method on the xbl widget which forwards the method call to the xpcom object. <method name="autocomplete"> <argument name="asearchstring"/> <argument name="resultlistener"/> <body> <![cdata[ re
turn this.autocompletesession.autocomplete(null, anonymouscontent[0], asearchstring, this.autocompletelistener); ]]> </body> </method> you can see that the body of the method is just getting the auto complete session object and calling the auto complete method on it. implementing a widget interface the next thing i needed to do was to implement an interface on the wid...
...istener is an object that implements my interface. now i can pass the result of autocompletelistener into methods that require an auto complete listener (like my auto complete session object). creating the event handler the last part is the easy part. i wanted a handler that would kick off the auto complete search. ...
...auto complete session object). creating the event handler the last part is the easy part. i wanted a handler that would kick off the auto complete search. the handler calls the auto complete method we've exposed on the widget which in
turn forwards the call to the xpcom object, passing in our implementation of nsiautocompletelistener. ...
Generic factory
ing a single interface that can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use. /** * provides a generic nsifactory implementation that can be used by * dlls with very simple factory needs. */ class nsigenericfactory : public nsifactory { public: static const nsiid& iid() { static nsiid iid = ns_igenericfactory_iid; re
turn iid; } typedef ns_callback(constructorprocptr) (nsisupports *aouter, refnsiid aiid, void **aresult); /** * establishes the generic factory's constructor function, which will be called * by createinstance. */ ns_imethod setconstructor(constructorprocptr constructor) = 0; }; using nsigenericfactory is simple. create a new instance from the repository with a cid of ns_...
... background (this is based on my original news posting <beard-2402991733140001@h-198-93-95-151.mcom.com>.) we seem to be creating a huge number of different factory implementations. it seems to me that we can cut down on code size (all those queryinterface, addref, release implement...
...genericfactory(creatorprocptr creator) : mcreator(creator) { ns_init_refcnt(); } nsgenericfactory::~nsgenericfactory() {} static ns_define_iid(kifactoryiid, ns_ifactory_iid); ns_impl_isupports(nsgenericfactory, kifactoryiid) ns_imethodimp nsgenericfactory::createinstance(nsisupports *aouter, refnsiid aiid, void **aresult) { re
turn mcreator(aouter, aiid, aresult); } ns_imethodimp nsgenericfactory::lockfactory(prbool alock) { re
turn ns_ok; } many of our classes already have a static entry point that serves as the creator function, so in most cases, creating a new factory for a class is just: nsifactory* newmallocfactory() { nsifactory* factory = new nsgenericfactory(&nsmalloc::create); factory->addref(); ...
...reator(aouter, aiid, aresult); } ns_imethodimp nsgenericfactory::lockfactory(prbool alock) { re
turn ns_ok; } many of our classes already have a static entry point that serves as the creator function, so in most cases, creating a new factory for a class is just: nsifactory* newmallocfactory() { nsifactory* factory = new nsgenericfactory(&nsmalloc::create); factory->addref(); re
turn factory; } talking to warren, he suggests that we even provide a shorthand for this, we should be able to register a factory with just a function pointer. original document information author: patrick beard last updated date: february 26, 1999 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative comm...
How to build an XPCOM component in JavaScript
tutorial for creating an xpcom component in javascript. this tutorial does not describe how and why xpcom works the way it does, or what every bit of the example code does. that's been detailed elsewhere. this tutorial will show you what you need to do to get a component working in as few and as simple steps as possible. implementation this example component will expose a single method, which re
turns the string "hello world!". defining the interface if you want to use your component in other xpcom components, you must define the interfaces that you want exposed. if you want to use your component only from javascript, you can skip to the next section. there are many interfaces already defined in mozilla applications, so you may not need to define a new one. you can browse existing xpcom in...
...elloworld.prototype = { // properties required for xpcom registration: classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", // [optional] custom factory (an object implementing nsifactory). if not // provided, the default factory is used, which re
turns // |(new mycomponent()).queryinterface(iid)| in its createinstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry(). 'true' is passed for both // apersist and areplace params. category: "some-catego...
...s.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", interfaces: [ci.nsihelloworld], flags: ci.nsiclassinfo.dom_object}), // ...component implementation... // define the function we want to expose in our interface hello: function() { re
turn "hello world!"; }, }; xpcomutils does the work of creating the module and factory for you after this. finally, you create an array of your components to be created: var components = [helloworld]; and replace nsgetfactory/nsgetmodule to use this array and xpcomutils: if ("generatensgetfactory" in xpcomutils) var nsgetfactory = xpcomutils.generatensgetfactory(components); // firefox 4...
...rt("resource://gre/modules/xpcomutils.jsm"); function helloworld() { } helloworld.prototype = { classdescription: "my hello world javascript xpcom component", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@dietrich.ganx4.com/helloworld;1", queryinterface: xpcomutils.generateqi([components.interfaces.nsihelloworld]), hello: function() { re
turn "hello world!"; } }; var components = [helloworld]; if ("generatensgetfactory" in xpcomutils) var nsgetfactory = xpcomutils.generatensgetfactory(components); // firefox 4.0 and higher else var nsgetmodule = xpcomutils.generatensgetmodule(components); // firefox 3.x note: starting with firefox 4.0 you will need to declare your component in chrome.manifest; classdescription and contractid...
Component Internals
ase. component manifests the component manifest is a mapping of files to components and components to classes. it specifies the following information: location on disk of registered components with file size class id to location mapping contract id to class id mapping the component manifest maps component files to unique identifiers for the specific implementations (class ids), which in
turn are mapped to more general component identifiers (contract ids). type library manifests another important file that xpcom reads in is the type library manifest file. this file is also located in the components directory and is named xpti.dat. it includes the location and search paths of all type library files on the system. this file also lists all known interfaces and links to the type librar...
... using your component. the shutdown process when the application is ready to shutdown xpcom, it calls ns_shutdownxpcom. when that method is called, the following sequence of events occurs: xpcom fires a shutdown notification to all registered observers. xpcom closes down the component manager, the service manager and associated services. xpcom frees all global services. ns_shutdownxpcom re
turns and the application may exit normally. the unstoppable shutdown note that shutdown observation is unstoppable. in other words, the event you observe cannot be used to implement something like a "are you sure you want to quit?" dialog. rather, the shutdown event gives the component or embedding application a last chance to clean up any leftovers before they are released. in order to support s...
... application a last chance to clean up any leftovers before they are released. in order to support something like an "are you sure you want to quit" dialog, the application needs to provide a higher-level event (e.g., startshutdown()) which allows for cancellation. note also that xpcom services may deny you access once you have received the shutdown notification. it is possible that xpcom will re
turn an error if you access the nsiservicemanager at that point, for example, so you may have to keep a reference-counted pointer to the service you are interested in using during this notification. component loaders components can be written in many languages. so far this book has been focusing on "native components," shared libraries exporting a nsgetmodule symbol. but if there is a component loa...
...vides (see xpcom/build/nsxpcom.h). when the glue library is initialized, it dynamically loads these symbols from the xpcom library, which allows the component to avoid linking directly with the xpcom library. you shouldn't have to link to the xpcom library to create a xpcom component - in fact, if your component has to, then something is wrong. « previousnext » copyright (c) 2003 by doug
turner and ian oeschger. this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
XPCOM Stream Guide
zip nsjarinputstream n/a nsiinputstream zipreader.getinputstream(zipentry); similarly, each of these implements nsioutputstream. ...
...erations, and all operations are queued zipwriter.processqueue(); // when we don't need the zipwriter anymore zipwriter.close(); concatenating input streams var stringstream = components.constructor("@mozilla.org/io/string-input-stream;1", "nsistringinputstream", "setdata"); function buildstream(data) { re
turn new stringstream(data, data.length); } function run_test() { var str1 = buildstream("we "); var str2 = buildstream("will "); var str3 = buildstream("rock "); var str4 = buildstream("you!"); var check = "we will rock you!"; var multi = components.classes["@mozilla.org/io/multiplex-input-stream;1"] .createinstance(components.interfaces.nsimultiplexinputstream)...
...tor("@mozilla.org/io/string-input-stream;1", "nsistringinputstream", "setdata"); var inputstream = components.constructor("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); function buildstream(data) { re
turn new stringstream(data, data.length); } components.utils.import("resource://gre/modules/netutil.jsm"); function run_test() { var check = "we will rock you!"; var baseinputstream = buildstream(check); var store = components.classes["@mozilla.org/storagestream;1"] .createinstance(components.interfaces.nsistoragestream); /* in practice, your storage streams shoul...
...stance(components.interfaces.nsistoragestream); /* in practice, your storage streams shouldn't be this small. the first argument, * which represents capacity per segment, is far too small for practical use. */ store.init(64, 64, null); var out = store.getoutputstream(0); netutil.asynccopy(baseinputstream, out, function(status) { if (status != components.results.ns_ok) re
turn; /* due to a crash, we can't create input streams until the storage output stream * has some data in it. * * also, baseinputstream has been completely consumed at this point, so we * shouldn't read from it anymore. (however, because baseinputstream is an * nsstringinputstream, it is also a seekable stream...so we could go to * the beginning if we wanted to.) ...
XPCShell Reference
the command line the command-line syntax for xpcshell is: xpcshell [-s] [-w] [-w] [-v version] [-f scriptfile] [scriptfile] [scriptarg...] -c this option
turns on the "compile-only" mode. (setting this option disables the "interactive" mode) -f this option specifies a script file to execute. xpcshell terminates upon script completion. you can specify multiple js files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered. furthermore, xpcshell looks for xpcshell.js in the current directory. if that file is found, it is executed before any other js files specified. ...
.... you can specify multiple js files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered. furthermore, xpcshell looks for xpcshell.js in the current directory. if that file is found, it is executed before any other js files specified. -g this option specifies which gecko runtime environment directory (gredir) to use for xpcom. -i this option
turns on the "interactive" mode -s this option toggles the javascript strict option on and off. by default it is off. -v version this allows you to specify a specific version of js to use, and should be set to an integral value specified by the jsversion enumerated type. for instance, specifying -v 180 will set the interpreter to use javascript version 1.8. -w (lower case) this option t...
... the javascript strict option on and off. by default it is off. -v version this allows you to specify a specific version of js to use, and should be set to an integral value specified by the jsversion enumerated type. for instance, specifying -v 180 will set the interpreter to use javascript version 1.8. -w (lower case) this option
turns on javascript warnings. -w (upper case) this
turns off javascript warnings. the last option listed is the one that takes effect. -x this option toggles the xml option on and off. by default it is off. [scriptfile] this is the file name of the script to execute. [scriptarg…] these are arguments to be passed to the script. these arguments are only passed to “scriptfile” and not the scripts designated by –f options. these argume...
...n arguments and appending a newline at the end. an example print(1, 2, 3) will print 1 2 3<newline>. dump(object) dump() is almost like print. it only handles one parameter and it doesn't append a newline. dumpxpc(depth) this function dumps the xpconnect object. see the documentation on debugdump() for the nsixpconnect interface for more information. version(newversion) version() re
turns the javascript engine version number. if you pass a number to it, it will set the version number (and re
turn the old version number). see the above documentation on the -v command-line argument for more information. quit(exitcode) quit() exits the shell. you can specify arguments that will get translated to an exit code. quit(5) will exit xpcshell with a result code of 5. original docume...
nsACString_internal
uint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. ...
...uffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the re
turned address. ...
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. ...
...haracters. parameters char** data getmutabledata pruint32 getmutabledata(char**, pruint32) - source get a pointer to the string's internal buffer, optionally resizing the buffer first. if size_type(-1) is passed for newlen, then the current length of the string is used. the caller may modify the characters at the re
turned address (up to but not exceeding the length of the string). @re
turns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(char, print32) - so...
nsAString_internal
2) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. ...
... sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the re
turned address. ...
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. ...
... parameters prunichar** data getmutabledata pruint32 getmutabledata(prunichar**, pruint32) - source get a pointer to the string's internal buffer, optionally resizing the buffer first. if size_type(-1) is passed for newlen, then the current length of the string is used. the caller may modify the characters at the re
turned address (up to but not exceeding the length of the string). @re
turns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(prunichar, pri...
nsDependentCSubstring
uint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. ...
...uffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the re
turned address. ...
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. ...
...haracters. parameters char** data getmutabledata pruint32 getmutabledata(char**, pruint32) - source get a pointer to the string's internal buffer, optionally resizing the buffer first. if size_type(-1) is passed for newlen, then the current length of the string is used. the caller may modify the characters at the re
turned address (up to but not exceeding the length of the string). @re
turns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(char, print32) - so...
nsDependentSubstring
2) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. ...
... sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer. the caller must not modify the characters at the re
turned address. ...
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. ...
... parameters prunichar** data getmutabledata pruint32 getmutabledata(prunichar**, pruint32) - source get a pointer to the string's internal buffer, optionally resizing the buffer first. if size_type(-1) is passed for newlen, then the current length of the string is used. the caller may modify the characters at the re
turned address (up to but not exceeding the length of the string). @re
turns the length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nstsubstring::isvoid parameters prbool <anonymous> stripchar void stripchar(prunichar, pri...
IAccessibleComponent
screen. the origin of the parent coordinate system is the upper left corner of the parent's bounding box. with no parent the screen coordinate system is used instead. method overview [propget] hresult background([out] ia2color background ); [propget] hresult foreground([out] ia2color foreground ); [propget] hresult locationinparent([out] long x, [out] long y ); methods background() re
turns the background color of this object. [propget] hresult background( [out] ia2color background ); parameters background the re
turned color is the background color of this object or, if that is not supported, the default background color. re
turn value s_ok. foreground() re
turns the foreground color of this object. [propget] hresult foreground( [out] ia2color foreground ); parameters foregr...
...round color of this object. [propget] hresult background( [out] ia2color background ); parameters background the re
turned color is the background color of this object or, if that is not supported, the default background color. re
turn value s_ok. foreground() re
turns the foreground color of this object. [propget] hresult foreground( [out] ia2color foreground ); parameters foreground the re
turned color is the foreground color of this object or, if that is not supported, the default foreground color. re
turn value s_ok. locationinparent() re
turns the location of the upper left corner of the object's bounding box relative to the immediate parent object. ...
... foreground the re
turned color is the foreground color of this object or, if that is not supported, the default foreground color. re
turn value s_ok. locationinparent() re
turns the location of the upper left corner of the object's bounding box relative to the immediate parent object. the coordinates of the bounding box are given relative to the parent's coordinate system. the coordinates of the re
turned position are relative to this object's parent or relative to the screen on which this object is rendered if it has no parent. if the object is not on any screen the re
turned position is (0,0). [propget] hresult locationinparent( [out] long x, [out] long y ); parameters x the x coordinate of the upper left corner of the object's bounding box relative to the immediate parent object. y the y...
... it has no parent. if the object is not on any screen the re
turned position is (0,0). [propget] hresult locationinparent( [out] long x, [out] long y ); parameters x the x coordinate of the upper left corner of the object's bounding box relative to the immediate parent object. y the y coordinate of the upper left corner of the object's bounding box relative to the immediate parent object. re
turn value s_ok. ...
IAccessibleRelation
[propget] hres...
...t target([in] long targetindex, [out] iunknown target ); [propget] hresult targets([in] long maxtargets, [out, size_is(maxtargets), length_is( ntargets)] iunknown targets, [out] long ntargets ); methods localizedrelationtype() re
turns a localized version of the relation type. [propget] hresult localizedrelationtype( [out] bstr localizedrelationtype ); parameters localizedrelationtype re
turn value s_ok. ntargets() re
turns the number of targets() for this relation. [propget] hresult ntargets( [out] long ntargets ); parameters ntargets re
turn value s_ok. relationtype() re
turns the type of the relation. [propget] hresult relationtype( [out] bstr relationtype ); parameters relationtype the strings re
turned are defined @ref grprelations "in this section of the documentation". r...
...value s_ok. ntargets() re
turns the number of targets() for this relation. [propget] hresult ntargets( [out] long ntargets ); parameters ntargets re
turn value s_ok. relationtype() re
turns the type of the relation. [propget] hresult relationtype( [out] bstr relationtype ); parameters relationtype the strings re
turned are defined @ref grprelations "in this section of the documentation". re
turn value s_ok. target() re
turns one accessible relation target. [propget] hresult target( [in] long targetindex, [out] iunknown target ); parameters targetindex 0 based index. target re
turn value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to re
turn, [out] value is null. s_ok. targets() re
turns multiple accessible relation targets. [propget] hresult targ...
...maxtargets maximum size of the array allocated by the client. targets the array of target objects. note that this array is to be allocated by the client and freed when no longer needed. refer to @ref _arrayconsideration "special consideration when using arrays" for more details. you will need to use queryinterface on the iunknown to get the iaccessible2. ntargets actual number of targets in the re
turned array (not more than maxtargets) re
turn value s_false if there is nothing to re
turn, ntargets() is set to 0. s_ok. see also iaccessible2 ...
amIInstallTrigger
gs); deprecated since gecko 2.0 boolean updateenabled(); deprecated since gecko 2.0 constants retained for backwards compatibility. constant value description skin 1 locale 2 content 4 package 7 methods enabled() tests if installation is enabled. boolean enabled(); parameters none. re
turn value install() starts a new installation of a set of add-ons. boolean install( in nsivariant aargs, in amiinstallcallback acallback optional ); parameters aargs the add-ons to install. this should be a js object, each property is the name of an add-on to be installed. the value of the property should either be a string url, or an object with the following properties: url for t...
...gs the add-ons to install. this should be a js object, each property is the name of an add-on to be installed. the value of the property should either be a string url, or an object with the following properties: url for the add-on's url iconurl for an icon for the add-on hash for a hash of the add-on. acallback optional a callback to call as each installation succeeds or fails. re
turn value true if the installations were successfully started. installchrome starts installing a new add-on. this method is deprecated, please use install() in the future. boolean installchrome( in pruint32 atype, in astring aurl, in astring askin ); parameters atype unused, retained for backwards compatibility. aurl the url of the add-on. askin unused, retained for backwards comp...
... the installations were successfully started. installchrome starts installing a new add-on. this method is deprecated, please use install() in the future. boolean installchrome( in pruint32 atype, in astring aurl, in astring askin ); parameters atype unused, retained for backwards compatibility. aurl the url of the add-on. askin unused, retained for backwards compatibility. re
turn value true if the installation was successfully started. startsoftwareupdate starts installing a new add-on. boolean startsoftwareupdate( in astring aurl, in print32 aflags optional ); parameters aurl the url of the add-on. aflags optional unused, retained for backwards compatibility. re
turn value true if the installation was successfully started. updateenabled tests if insta...
...wareupdate starts installing a new add-on. boolean startsoftwareupdate( in astring aurl, in print32 aflags optional ); parameters aurl the url of the add-on. ...
mozIStorageFunction
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 ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. re
turn value an nsivariant this is the re
turn value of the function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aargument...
...he function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); re
turn value * value; }); // run some query that uses the function. let stmt = dbconn.createstatement("select square(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } in earlier versions of gecko, however, you'll need to actually create an object containing the onfunctioncall method. this still works in gecko 1.9.1.4 and later, ...
...er versions of gecko, however, you'll need to actually create an object containing the onfunctioncall method. this still works in gecko 1.9.1.4 and later, so you may wish to do it this way for compatibility for the time being. // first, create our object that will represent our function. var squarefunction = { onfunctioncall: function(aarguments) { let value = aarguments.getint32(0); re
turn value * value; } }; // now, register our function with the database connection. dbconn.createfunction("square", 1, squarefunction); // run some query that uses the function. let stmt = dbconn.createstatement("select square(value) from some_table"); try { while (stmt.executestep()) { // handle the results } } finally { stmt.reset(); } c++ // first, create our class that will repre...
...nscomptr<mozistoragefunction> func = new squarefunction(); ns_ensure_true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("square"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function. nscomptr<mozistoragestatement> stmt; rv = dbconn->createstatemen...
nsIAccessibleSelectable
object is already selected, then it does nothing. void addchildtoselection( in long index ); parameters index the zero-based accessible child index. exceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the object so that no children in the object are selected. void clearselection(); parameters none. ...
...ndex the zero-based accessible child index. exceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the object so that no children in the object are selected. void clearselection(); parameters none. getselectedchildren() re
turns an nsiarray of the selected nsiaccessible children. nsiarray getselectedchildren(); parameters none. re
turn value an nsiarray. ischildselected() determines if the current child of this object is selected. boolean ischildselected( in long index ); parameters index the zero-based accessible child index. re
turn value true if the child is selected, false if not. refselection() re
turns a reference to the accessible object representing the specified selected child of the object. nsiaccessible refselecti...
...removechildfromselection() removes the specified child of the object from the object's selection. if the specified object was not selected, then it does nothing. ...
...specified child of the object from the object's selection. if the specified object was not selected, then it does nothing. void removechildfromselection( in long index ); parameters index zero-based accessible child index. exceptions thrown ns_error_failure if the specified object is not selectable. selectallselection() select all children. boolean selectallselection(); parameters none. re
turn value if the object does not accept multiple selection, re
turn false. otherwise, re
turns true. ...
nsIAppShellService
void toplevelwindowismodal(in nsixulwindow awindow, in boolean amodal); obsolete since gecko 1.9.1 void unregistertoplevelwindow(in nsixulwindow awindow); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindowinternal. attributes attribute type description applicationprovidedhiddenwindow boolean re
turn true if the application hidden window was provided by the application. if it was not, the default hidden window was used. this will usually be false on all non-mac platforms. read only. hiddendomwindow nsidomwindow re
turn the (singleton) application hidden window, automatically created and maintained by this appshellservice. read only. hiddenwindow nsixulwindow retu...
....0) creates the initial state of the application by launching tasks specfied by "general.startup.*" prefs. note: size_to_content may be used for width or height. boolean createstartupstate( in long awindowwidth, in long awindowheight ); parameters awindowwidth the width to make the initial window(s) opened. awindowheight the height to make the initial window(s) opened. re
turn value true if a window was opened. createtoplevelwindow() this method creates a window, which will be initially invisible. nsixulwindow createtoplevelwindow( in nsixulwindow aparent, in nsiuri aurl, in boolean ashowwindow, in boolean aloaddefaultpage, in pruint32 achromemask, in long ainitialwidth, in long ainitialheight, in nsiappshell aappshell ); parameters aparent th...
...overridden by the "width" tag in the xul. set to ns_sizetocontent to force the window to wrap to its contents. ainitialheight height, in pixels, of the window. height of window at creation. can be overridden by the "height" tag in the xul. set to ns_sizetocontent to force the window to wrap to its contents. aappshell a widget "appshell" (event processor) to associate with the new window. re
turn value re
turns the newly created window. destroyhiddenwindow() destroys a hidden window. void destroyhiddenwindow(); parameters none. doprofilestartup() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) starts up the profile manager with the given arguments. void doprofilestartup( in nsicmdlineservice acmdlineservice, in boolean canint...
...at do not normally quit when the last window has closed, call enter once, but not exit) void enterlastwindowclosingsurvivalarea(); parameters none. exitlastwindowclosingsurvivalarea() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void exitlastwindowclosingsurvivalarea(); parameters none. native code only!gethiddenwindowandjscontext re
turn the (singleton) application hidden window as an nsidomwindow, and, the corresponding javascript context pointer. this is useful if you'd like to subsequently call opendialog on the hidden window. void gethiddenwindowandjscontext( out nsidomwindow ahiddendomwindow, out jscontext ajscontext ); parameters ahiddendomwindow the hidden window queryinterface'd to type nsidomwindow. ajscontex...
nsIAppStartup
.0) creates the initial state of the application by launching tasks specfied by "general.startup.*" prefs. note: size_to_content may be used for width or height. boolean createstartupstate( in long awindowwidth, in long awindowheight ); parameters awindowwidth the width to make the initial window(s) opened. awindowheight the height to make the initial window(s) opened. re
turn value true if a window was opened. destroyhiddenwindow() destroys the hidden window. this will have no effect if the hidden window has not yet been created. void destroyhiddenwindow(); parameters none. doprofilestartup() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) starts up the profile manager with the given arguments. void doprof...
...ese. void enterlastwindowclosingsurvivalarea(); parameters none. exitlastwindowclosingsurvivalarea() this method serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void exitlastwindowclosingsurvivalarea(); parameters none. getstartupinfo() re
turns a javascript object with events from startup and the timestamps indicating when they occurred. parameters none. re
turn value a javascript object with the following fields. keys are the event names and their values are the times. events that didn't occur are not in the object. event identifier (key) description main time at which main application core was loa...
...rmation to the console. var aconsoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var startupinfo = components.classes["@mozilla.org/toolkit/app-startup;1"] .getservice(ci.nsiappstartup_mozilla_2_0).getstartupinfo(); var keys = object.keys(startupinfo); keys.sort(function(a, b) { re
turn startupinfo[a] - startupinfo[b]; }); for each (var name in keys) { aconsoleservice.logstringmessage(name + ": " + startupinfo[name]); } to calculate how long startup took, compute the difference between the event's timestamp and the timestamp of the process event. hidesplashscreen() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) remove ...
...e. void quit( in pruint32 aquitmode ); parameters aquitmode this parameter modifies how the app is shutdown. run() runs an application event loop: normally the main event pump which defines the lifetime of the application. if there are no windows open and no outstanding calls to enterlastwindowclosingsurvivalarea() this method will exit immediately. void run(); parameters none. re
turn value re
turns ns_success_restart_app code. this re
turn code indicates that the application should be restarted because quit was called with the erestart flag. see also nsicmdlineservice nsiappstartup_mozilla_2_0 ...
nsIAuthPrompt2
urity 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 re
turn immediately after calling and re
turn 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 nsicancelable.cancel() on the re
turned object should close the dialog and must call nsiauthpromptcallback.onauthcancelled() on the provided callback. this implementation may: ...
...nel, 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 information entered by the user before re
turning. re
turn value promptauth() requests a username and a password. implementations will commonly show a dialog with a username and password field, depending on flags also a domain field. note: exceptions thrown from this function will be treated like a re
turn value of false. boolean promptauth( in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo ); parameters ...
...true, authentication can proceed using the values in the authinfo object. ...
...true, authentication can proceed using the values in the authinfo object. ...
nsICacheSession
rbool isstorageenabled(); nsicacheentrydescriptor opencacheentry(in acstring key, in nscacheaccessmode accessrequested, in boolean blockingmode); void doomentry(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 re
turned (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 ...
...he listener to be notified (may be null). evictentries() this method evicts all entries for this session's clientid according to its storagepolicy. void evictentries(); parameters none. isstorageenabled() this method checks if the cache devices implied by the session storage policy are currently enabled for instantiation if they don't already exist. prbool isstorageenabled(); parameters none. re
turn value re
turns whether any of the cache devices implied by the session storage policy are currently enabled for instantiation or not, depending on their existence. opencacheentry() this method gives a synchronous cache access. it re
turns a unique descriptor each time it is called, even if the same key is specified. when called by multiple threads for write access, only one writable descriptor will...
...by the session storage policy are currently enabled for instantiation or not, depending on their existence. opencacheentry() this method gives a synchronous cache access. it re
turns a unique descriptor each time it is called, even if the same key is specified. when called by multiple threads for write access, only one writable descriptor will be granted. if blockingmode is set to false, it will re
turn ns_error_cache_wait_for_validation rather than block when another descriptor has been given write access but hasn't validated the entry yet. note: if at all possible, you should use asyncopencacheentry() instead of calling opencacheentry(), in order to avoid blocking on i/o on the calling thread. this will streamline overall application performance. a cache session can only give out one descripto...
... write access to a given cache entry at a time. until the client calls markvalid on its descriptor, other attempts to open the same cache entry will block. nsicacheentrydescriptor opencacheentry( in acstring key, in nscacheaccessmode accessrequested, in boolean blockingmode ); parameters key the key for cache entry. accessrequested the requested access. blockingmode true or false value to
turn blocking mode for calling the thread to on/off respectively. re
turn value re
turns a unique descriptor each time it is called. see also nsicache nsicacheentrydescriptor nsicachelistener nsicacheservice ...
nsICacheVisitor
eid, in nsicachedeviceinfo deviceinfo); boolean visitentry(in string deviceid, in nsicacheentryinfo entryinfo); methods visitdevice() this method is called to provide information about a cache device. boolean visitdevice( in string deviceid, in nsicachedeviceinfo deviceinfo ); parameters deviceid specifies the device being visited. deviceinfo specifies information about this device. ...
...chedeviceinfo deviceinfo); boolean visitentry(in string deviceid, in nsicacheentryinfo entryinfo); methods visitdevice() this method is called to provide information about a cache device. boolean visitdevice( in string deviceid, in nsicachedeviceinfo deviceinfo ); parameters deviceid specifies the device being visited. deviceinfo specifies information about this device. ...
... nsicacheentryinfo entryinfo); methods visitdevice() this method is called to provide information about a cache device. boolean visitdevice( in string deviceid, in nsicachedeviceinfo deviceinfo ); parameters deviceid specifies the device being visited. deviceinfo specifies information about this device. re
turn value re
turns true to start visiting all entries for this device, otherwise re
turns false to advance to the next device. ...
...e. re
turn value re
turns true to start visiting all entries for this device, otherwise re
turns false to advance to the next device. visitentry() this method is called to provide information about a cache entry. boolean visitentry( in string deviceid, in nsicacheentryinfo entryinfo ); parameters deviceid specifies the device being visited. entryinfo specifies information about this entry. re
turn value re
turns true to visit the next entry on the current device, or if the end of the device has been reached, advance to the next device, otherwise re
turns false to advance to the next device. see also nsicache nsicachedeviceinfo nsicacheentryinfo ...
nsIClassInfo
the class is a dom object. plugin_object 1 << 4 the class is a plugin object. content_node 1 << 6 specifies that this class implements nsicontent. note: this flag is private and is for use by the mozilla codebase only. reserved 1 << 31 the high order bit is reserved for consumers of these flags. no implementor of this interface should ever re
turn flags with this bit set. eager_classinfo 1 << 5 this flag is designed for use with nsgenericfactory and can be set in nsmodulecomponentinfo::mflags. it has no meaning when re
turned from the flags attribute of a nsiclassinfo implementation. obsolete since gecko 2.0 methods gethelperforlanguage() get a language mapping specific helper object that may assist in using objects ...
...t in nsmodulecomponentinfo::mflags. it has no meaning when re
turned from the flags attribute of a nsiclassinfo implementation. obsolete since gecko 2.0 methods gethelperforlanguage() get a language mapping specific helper object that may assist in using objects of this class in a specific lanaguage. for example, if asked for the helper for nsiprogramminglanguage::javascript this might re
turn an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be re
turned. nsiprogramminglanguage defines language ide...
...d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be re
turned. nsiprogramminglanguage defines language identifiers that may be passed for this parameter. re
turn value should re
turn null if no helper available for given language. ...
...lers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be re
turned. nsiprogramminglanguage defines language identifiers that may be passed for this parameter. re
turn value should re
turn null if no helper available for given language. getinterfaces() this method re
turns an ordered list of interfaces iids that instances of the class promise to implement. note that nsisupports is an implicit member of the implemented set of interfaces and need not be included. if this method is not supported by an implementation, then it should re
turn 0 for count and null for array. void getinterfaces( out pruint32 count, [array, size_is(count), retval] out nsiidptr array ...
nsIClipboardDragDropHooks
in nsitransferable trans); boolean onpasteordrop(in nsidomevent event, in nsitransferable trans); methods allowdrop() tells gecko whether a drop is allowed on this content area. boolean allowdrop( in nsidomevent event, in nsidragsession session ); parameters event the dom event (drag gesture). session the drag session from which client can get the flavors present or the actual data. ...
...otherwise, false to show the drag is canceled (does not go to operating system). oncopyordrag() alters the flavors or data presented to the os. used for drag and copy actions. because this can be called many times, it is highly recommended that the implementation be very efficient so user feedback is not negatively impacted. ...
...copy actions. because this can be called many times, it is highly recommended that the implementation be very efficient so user feedback is not negatively impacted. boolean oncopyordrag( in nsidomevent aevent, in nsitransferable trans ); parameters aevent the dom event (drag drop). null if triggered by copy. trans the transferable holding the list of flavors and the data for each flavor. re
turn value true to indicate that copy/drag can proceed. otherwise, false to indicate that the copy/drag is canceled, does not go to operating system. onpasteordrop() provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onpasteordrop( in nsidomevent event, in nsitransferable trans ); parameters event the dom event (drag drop); nu...
...d, does not go to operating system. onpasteordrop() provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onpasteordrop( in nsidomevent event, in nsitransferable trans ); parameters event the dom event (drag drop); null if triggered by paste. trans the transferable holding the list of flavors and the data for each flavor. re
turn value true to indicate the action was handled, do not perform built-in behavior. otherwise, false to indicate the action was not overridden, do built-in behavior. see also nsiclipboard ...
nsIComponentManager
r higher there should be no need to call this method, since the bootstrapped add-on's chrome.manifest is loaded automatically now. void addbootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters alocation the directory or xpi from which to load the chrome.manifest. createinstance() creates an instance of the class specified by classid. unlike getservice, this re
turns a new instance each time it is called. (see also nsifactory.createinstance.) void createinstance( in nscidref aclass, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the object instance that is being requested. adelegate the outer object used for aggregation. aiid the interface type to be re
turned. re...
...actid() creates an instance of the class specified by contractid. void createinstancebycontractid( in string acontractid, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters acontractid the contractid of the object instance that is being requested. adelegate the outer object used for aggregation. aiid the interface type to be re
turned. result the resulting interface pointer. exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getclassobject() re
turns the factory object for the class specified by classid. void getclassobject( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the facto...
...own ns_error_factory_not_registered indicates that the specified class is not registered. getclassobject() re
turns the factory object for the class specified by classid. void getclassobject( in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the factory that is being requested. aiid the interface type to be re
turned. result the resulting interface pointer. exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. getclassobjectbycontractid() re
turns the factory object for the class specified by contractid. void getclassobjectbycontractid( in string acontractid, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters ac...
... result the resulting interface pointer. exceptions thrown ns_error_factory_not_registered indicates that the specified class is not registered. removebootstrappedmanifestlocation() unregisters the chrome.manifest file previously registered with the addbootstrappedmanifestlocation() method. ...
nsIConsoleService
ure 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. void getmessagearray( [array, size_is(count)] out nsiconsolemessage messages, out pruint32 count ); parameters messages an array of logged messages. count the number of messages in the array. ...
... note: see the code samples below for how to call getmessagearray. logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. ...
...e nsiconsolelistener to remove. ...
... .getservice(components.interfaces.nsiconsoleservice); var array = {}; consoleservice.getmessagearray(array, {}); re
turn array.value; } to retrieve the message array in gecko 19 or later: function getconsolemessagearray() { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); re
turn consoleservice.getmessagearray(); } to retrieve the message array in a compatible way: function getconsolemessagearray() { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var array = {}; re
turn consoleservice.getmessagearray(array, {}) || array.value; } logging a simple messa...
nsIDNSService
l 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. 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 re
turn errors if prefetching is disabled by configuration. resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be re
turned by asyncresolve() and resolve(). methods asyncresolve() begins off an asynchronous host lookup. a specified nsidnslistener is invoked when the resolution process is completed. nsicancelable asyncresolve( in autf8string ahostname, in...
...lve flag constants. alistener the listener to be notified when the result is available. alistenertarget optional parameter (may be null). if not null, this parameter specifies the nsieventtarget of the thread on which the listener's onlookupcomplete should be called. if this parameter is null, then onlookupcomplete will be called on an unspecified thread (possibly recursively). re
turn value an object that can be used to cancel the host lookup. init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to initialize the dns service. void init(); parameters none. resolve() called to synchronously resolve a host name. warning this method may block the calling thread for a long period of time. it is extremely unwise to call th...
...host name. warning this method may block the calling thread for a long period of time. it is extremely unwise to call this function on the user interface thread of an application. nsidnsrecord resolve( in autf8string ahostname, in unsigned long aflags ); parameters ahostname the host name or ip-address-literal to resolve. aflags a bitwise or of the resolve flag constants. re
turn value dns record corresponding to the given host name. exceptions thrown ns_error_unknown_host if host could not be resolved. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to shutdown the dns service. any pending asynchronous requests will be canceled, and the local cache of dns records will be cleared. note: the ope...
... .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcomplete: function(request, record, status) { if (!components.issuccesscode(status)) { // handle error here re
turn; } let address = record.getnextaddrasstring(); console.log(host + " = " + address); } }; dnsservice.asyncresolve(host, 0, listener, thread); ...
nsIDOMEvent
t used to indicate the eventtarget to which the event was originally dispatched. read only. timestamp domtimestamp used to specify the time (in milliseconds relative to the epoch) at which the event was created. due to the fact that some systems may not provide this information the value of timestamp may be not available for all events. when not available, a value of 0 will be re
turned. examples of epoch time are the time of the system start or 0:0:0 utc 1st january 1970. read only. type domstring the name of the event (case-insensitive). the name must be an xml name. read only. constants constant value description none 0 the event is not being dispatched. capturing_phase 1 the current event phase is the cap...
...this method will be removed in future releases, see bug 691151. boolean getpreventde...
...lates the xpcom interface guidelines deserialize() boolean deserialize( in constipcmessageptr amsg, out voidptr aiter ); parameters amsg aiter re
turn value native code only!duplicateprivatedata void duplicateprivatedata(); parameters none. violates the xpcom interface guidelines getinternalnsevent() nseventptr getinternalnsevent(); parameters none. re
turn value getpreventdefault() note: use the defaultprevented attribute instead. this method will be removed in future releases, see bug 691151. boolean getpreventdefault(); parameters none. re
turn value initevent() this method is used to initialize the value of an event created through the documentevent interface. this method may only be called before the event has been dispatched via...
...s adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other new events. canbubblearg specifies whether or not the event can bubble. cancelablearg specifies whether or not the event's default action can be prevented. violates the xpcom interface guidelines isdispatchstopped() boolean isdispatchstopped(); parameters none. re
turn value preventbubble() note: use stoppropagation() instead. void preventbubble(); parameters none. preventcapture() note: use stoppropagation() instead. void preventcapture(); parameters none. preventdefault() if an event is cancelable, the preventdefault method is used to signify that the event is to be canceled, meaning any default action normally taken by the implementation ...
nsIDOMNode
t value description element_node 1 attribute_node 2 text_node 3 cdata_section_node 4 entity_reference_node 5 entity_node 6 processing_instruction_node 7 comment_node 8 document_node 9 document_type_node 10 document_fragment_node 11 notation_node 12 methods appendchild() nsidomnode appendchild( in nsidomnode newchild ); parameters newchild re
turn value clonenode() nsidomnode clonenode( in boolean deep ); parameters deep re
turn value hasattributes() boolean hasattributes(); parameters none. re
turn value haschildnodes() boolean haschildnodes(); parameters none. re
turn value insertbefore() nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild re
turn value issupported() b...
...ibutes() boolean hasattributes(); parameters none. re
turn value haschildnodes() boolean haschildnodes(); parameters none. re
turn value insertbefore() nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild re
turn value issupported() boolean issupported( in domstring feature, in domstring version ); parameters feature version re
turn value normalize() void normalize(); parameters none. ...
...) nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild re
turn value issupported() boolean issupported( in domstring feature, in domstring version ); parameters feature version re
turn value normalize() void normalize(); parameters none. ...
... boolean issupported( in domstring feature, in domstring version ); parameters feature version re
turn value normalize() void normalize(); parameters none. ...
nsIDOMOfflineResourceList
y 4 there is a new version of the application cache available. obsolete 5 the application cache group is now obsolete. methods mozadd() adds an item to the dynamically managed entries. the resource will be fetched and added to the application cache. void mozadd( in domstring uri ); parameters uri the uri of the resource to add to the list. ...
... note: this method is deprecated in firefox 3.5; you should instead access the list directly using the items attribute. ...
...m re
turns a boolean value indicating whether or not the specified uri represents a resource that's in the application cache's list. note: this method has been deprecated. you should use the mozitems attribute instead. void mozhasitem( in domstring uri ); parameters uri the uri of the resource to check. re
turn value true if the resource is in the list, otherwise false. mozitem re
turns the uri of the item at the specific offset into the list of cached resources. note: this method is deprecated in firefox 3.5; you should instead access the list directly using the items attribute. domstring mozitem( in unsigned long index ); parameters index the index of the cached item whose uri should be re
turned. ...
... mozremove() removes an item from the list of dynamically managed entries. if this was the last reference to the given uri in the application cache, the cache entry is removed. ...
nsIDOMXULElement
element's template builder, if it has a template. classname domstring gets/sets the value of the element's class attribute. collapsed boolean true if the element's collapsed attribute is the string "true", otherwise false. removes the attribute if you set it to false. contextmenu domstring gets/sets the value of the element's contextmenu attribute. controllers nsicontrollers read only. re
turns an nsicontrollers object that additional controllers may be appended to so as to provide focus-specific actions for commands. database nsirdfcompositedatasource read only. re
turns the template builder's database, if it is an rdf template. datasources domstring gets/sets the value of the element's datasources attribute. dir domstring gets/sets the value of the element's dir attribute. fle...
...rdinal domstring gets/sets the value of the element's ordinal attribute. orient domstring gets/sets the value of the element's orient attribute. pack domstring gets/sets the value of the element's pack attribute. persist domstring gets/sets the value of the element's persist attribute. ref domstring gets/sets the value of the element's ref attribute. resource nsirdfresource read only. re
turns the nsirdfresource corresponding to the element's ref or id attribute, if any. statustext domstring gets/sets the value of the element's statustext attribute. style nsidomcssstyledeclaration read only. obsolete since gecko 1.9 re
turns an object that may be used to read or write individual css style properties for the element. tooltip domstring gets/sets the value of the element's tooltip a...
...cus(); parameters none. getelementsbyattribute() searches the dom subtree for elements with the given attribute that are not in a namespace. nsidomnodelist getelementsbyattribute( in domstring name, in domstring value ); parameters name the name of the attribute to search for. value the value of the attribute to search for, or "*" to search for the attribute without regard to the value. re
turn value a list of elements with matching attributes that have no namespace. starting in gecko 1.8 this is a live list of elements rather than a snapshot. getelementsbyattributens() searches the dom subtree for elements with the given attribute in the given namespace. nsidomnodelist getelementsbyattributens( in domstring namespaceuri, in domstring name, in domstring value ); parameters names...
...ace. nsidomnodelist getelementsbyattributens( in domstring namespaceuri, in domstring name, in domstring value ); parameters namespaceuri the namespace of the attribute to search for, or "*" to search attributes in all namespaces. name the name of the attribute to search for. value the value of the attribute to search for, or "*" to search for the attribute without regard to the value. re
turn value a list of elements with matching attributes. ...
nsIDispatchSupport
sexists); boolean isobjectsafeforscripting(in voidptr theobject, in nsiidref id); void jsval2comvariant(in jsval var, out comvariant comvar); methods comvariant2jsval() converts a com variant to a jsval. void comvariant2jsval( in comvariantptr comvar, out jsval val ); parameters comvar the com variant to be converted. val the jsval to receive the converted value. gethostingflags() re
turn the activex security and hosting flags. see nsiactivexsecuritypolicy for list of flags. unsigned long gethostingflags( in string acontext ); parameters acontext re
turn value isclassmarkedsafeforscripting() test if the specified class is marked safe for scripting. boolean isclassmarkedsafeforscripting( in nscidref cid, out boolean classexists ); parameters cid the nsid representation ...
...ags. see nsiactivexsecuritypolicy for list of flags. unsigned long gethostingflags( in string acontext ); parameters acontext re
turn value isclassmarkedsafeforscripting() test if the specified class is marked safe for scripting. boolean isclassmarkedsafeforscripting( in nscidref cid, out boolean classexists ); parameters cid the nsid representation of the clsid to test. classexists re
turns containing pr_false if the class is not registered. re
turn value isclasssafetohost() test if the class is safe to host. ...
...out boolean classexists ); parameters cid the nsid representation of the clsid to test. classexists re
turns containing pr_false if the class is not registered. re
turn value isclasssafetohost() test if the class is safe to host. boolean isclasssafetohost( in jscontextptr cx, in nscidref cid, in boolean capscheck, out boolean classexists ); parameters cx cid capscheck classexists re
turns containing pr_false if the class is not registered. re
turn value isobjectsafeforscripting() test if the instantiated object is safe for scripting on the specified interface. ...
...void jsval2comvariant( in jsval var, out comvariant comvar ); parameters var the jsval to be converted. ...
nsIDroppedLinkHandler
pped. boolean candroplink( in nsidomdragevent aevent, in prbool aallowsamedocument ); parameters aevent a dragenter or dragover event. aallowsamedocument if false, drops are only allowed if the document of the source of the drag is different from the destination. this check includes any parent, sibling and child frames in the same content tree. if true, the source is not checked. re
turn value true if the link being dragged can be dropped. exceptions thrown missing exception missing description droplink() given a drop event, determines the link being dragged. if a uri is re
turned the caller can, for instance, load it. if null is re
turned, there is no valid link to be dropped. astring droplink( in nsidomdragevent aevent, out astring aname, [optional] in boolean adi...
... exceptions thrown ns_error_dom_security_err error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. this will occur if the source of the drag initiated a link for dragging that it itself cannot access. ...
... thrown and the event canceled if the receiving target should not load the uri for security reasons. this will occur if the source of the drag initiated a link for dragging that it itself cannot access. this prevents a source document from tricking the user into a dragging a chrome url for example. droplinks() given a drop event, determines the link being dragged. if non-empty links array is re
turned the caller can, for instance, load it. if empty links array is re
turned, there is no valid link to be dropped. void droplinks( in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks ); parameters aevent a drop event. adisallowinherit acount receives the count of a...
... valid link to be dropped. void droplinks( in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks ); parameters aevent a drop event. adisallowinherit acount receives the count of alinks array alinks recives an array of objects with nsidroppedlinkitem interface re
turn value nothing. see also nsidroppedlinkitem ...
nsIEventListenerService
aeventtarget will be at index 0. the objects are the ones that would be used as event.currenttarget while dispatching an event to aeventtarget. note: some event...
... void removesystemeventlistener(in nsidomeventtarget target, in domstring type, in nsidomeventlistener listener, in boolean usecapture); attributes attribute type description systemeventgroup nsidomeventgroup re
turns system event group. read only. obsolete since gecko 7.0 methods geteventtargetchainfor() re
turns an array of event targets indicating all the targets that will receive the same events that are delivered to the specified target. aeventtarget will be at index 0. the objects are the ones that would be used as event.currenttarget while dispatching an event to aeventtarget. note: some events, especially 'load', may actually have a shorter event target chain than what this methods re
turns. void g...
...hing an event to aeventtarget. note: some events, especially 'load', may actually have a shorter event target chain than what this methods re
turns. void geteventtargetchainfor( in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidomeventtarget aoutarray ); parameters aeventtarget the nsidomeventtarget for which to re
turn the event target chain. acount on re
turn, contains the number of elements in the re
turned array. aoutarray the array into which to store the event targets. getlistenerinfofor() re
turns an array of nsieventlistenerinfo objects describing everyone listening to the specified event target. if aeventtarget doesn't have any listeners, this re
turns null. void getlistenerinfo...
...ening to the specified event target. if aeventtarget doesn't have any listeners, this re
turns null. void getlistenerinfofor( in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsieventlistenerinfo aoutarray ); parameters aeventtarget the nsieventtarget for which to obtain a list of listeners. acount on re
turn, the number of re
turned listener descriptors. aoutarray an array of nsieventlistenerinfo objects describing the listeners. haslistenersfor() re
turns true if a event target has any listener for the given type. boolean haslistenersfor( in nsidomeventtarget aeventtarget, in domstring atype ); parameters aeventtarget the nsidomeventtarget for which to check if this...
nsIFormHistory2
read only. methods addentry() adds a name and value pair to the form history. void addentry( in astring name, in astring value ); parameters name value entryexists() gets whether a name and value pair exists in the form history. boolean ent...
...); void removeallentries(); void removeentriesbytimeframe(in long long abegintime, in long long aendtime); void removeentriesforname(in astring name); void removeentry(in astring name, in astring value); attributes attribute type description dbconnection mozistorageconnection re
turns the underlying db connection the form history module is using. read only. hasentries boolean re
turns true if the form history has any entries. read only. ...
...void removeallentries(); parameters none. removeentriesbytimeframe() removes entries that were created between the specified times. ...
...rue if the form history has any entries. read only. methods addentry() adds a name and value pair to the form history. void addentry( in astring name, in astring value ); parameters name value entryexists() gets whether a name and value pair exists in the form history. boolean entryexists( in astring name, in astring value ); parameters name value re
turn value nameexists() re
turns true if there is no entry that is paired with a name. boolean nameexists( in astring name ); parameters name re
turn value removeallentries() removes all entries in the entire form history. void removeallentries(); parameters none. removeentriesbytimeframe() removes entries that were created between the specified times. void removeentriesbytimeframe( in long long abegintime, in long l...
nsIInstallLocation
em_user 100 priority_app_system_global 1000 priority_xre_system_global 10000 methods getidforlocation() retrieves the guid for an item at the specified location. note: this function makes no promises about whether or not this path is actually maintained by this install location. astring getidforlocation( in nsifile file ); parameters file the location where an item might live. re
turn value the id for an item that might live at the location specified. getitemfile() gets a nsifile object for a file within an item's directory structure. nsifile getitemfile( in astring id, in astring path ); parameters id the guid of the item. path the path to the file beneath an extension's directory. re
turn value a file object at the requested location. the file does not necessarily have...
...ifile getitemfile( in astring id, in astring path ); parameters id the guid of the item. path the path to the file beneath an extension's directory. re
turn value a file object at the requested location. the file does not necessarily have to exist. getitemlocation() gets the directory that contains an item. nsifile getitemlocation( in astring id ); parameters id the guid of the item. re
turn value the location of the item. getstagefile() re
turns the most recently staged package (for example the last xpi or jar in a directory) for an item and removes items that do not qualify. nsifile getstagefile( in astring id ); parameters id the id of the staged package. re
turn value an nsifile if the package exists otherwise null. itemismanagedindependently() determines whether or not an ite...
...endently() determines whether or not an item's resources are managed by the extension system or by some other user or process. for example, items linked to by text links are managed by the user, and items linked to from registry install locations are usually managed by other applications or installers. boolean itemismanagedindependently( in astring id ); parameters id the guid of the item. re
turn value true if the item's resources are managed independently of the extension system, false otherwise. removefile() removes a file from the stage. this cleans up the stage if there is nothing else left after the remove operation. void removefile( in nsifile file ); parameters file the file to remove. stagefile() stages the specified file by copying it to some location from where it can be re...
...is nothing else left after the remove operation. void removefile( in nsifile file ); parameters file the file to remove. stagefile() stages the specified file by copying it to some location from where it can be retrieved later to complete installation. nsifile stagefile( in nsifile file, in astring id ); parameters file the file to stage. id the guid of the item the file represents. re
turn value the staged file. ...
nsIJSID
an unnamed jsid also results when you implement a function that is passed an nsiidref parameter, such as queryinterface(). ...
...); violates the xpcom interface guidelines void initialize(in string idstring); string tostring(); attributes attribute type description id nsidptr read only. native code only! obsolete since gecko 1.9 the internal nsid. name string read only. the name of the jsid, if it was set. number string read only. the string representation of the internal nsid. valid boolean read only. re
turns true if the jsid has been initialised. methods equals() this method determines if this nsijsid has the same nsid as another nsijsid. boolean equals( in nsijsid other ); parameters other the other nsijsid to compare to. re
turn value true if the nsijsid's are valid and have the same nsid, otherwise false. violates the xpcom interface guidelines getid() const nsid* getid(); paramete...
...he jsid has been initialised. methods equals() this method determines if this nsijsid has the same nsid as another nsijsid. boolean equals( in nsijsid other ); parameters other the other nsijsid to compare to. re
turn value true if the nsijsid's are valid and have the same nsid, otherwise false. violates the xpcom interface guidelines getid() const nsid* getid(); parameters none. re
turn value a pointer to the internal nsid structure. initialize() initializes the jsid. ...
...es the xpcom interface guidelines getid() const nsid* getid(); parameters none. re
turn value a pointer to the internal nsid structure. initialize() initializes the jsid. void initialize( in string idstring ); parameters idstring the number to initialize the jsid, in string format, e.g. {00000000-0000-0000-c000-000000000046}. a jsid can only be initialized once. tostring() this methods re
turns a string representation of the object. string tostring(); parameters none. re
turn value the name of the jsid if it has one, otherwise the string representation of its nsid. ...
nsIMemory
xpcom/base/nsimemory.idlscriptable this interface represents a generic memory allocator. inherits from: nsisupports last changed in gecko 0.9.6 nsimemory is used to allocate and deallocate memory segments from a heap. the implementation is free to define the heap. ns_getmemorymanager re
turns the global nsimemory instance. method overview voidptr alloc(in size_t size); violates the xpcom interface guidelines void free(in voidptr ptr); violates the xpcom interface guidelines void heapminimize(in boolean immediate); boolean islowmemory(); deprecated since gecko 2.0 voidptr realloc(in voidptr ptr, in size_t newsize); violates the xpcom interface guidelines methods alloc allocates a block of memory of a particular size. voidp...
...nterface guidelines void heapminimize(in boolean immediate); boolean islowmemory(); deprecated since gecko 2.0 voidptr realloc(in voidptr ptr, in size_t newsize); violates the xpcom interface guidelines methods alloc allocates a block of memory of a particular size. voidptr alloc( in size_t size ); parameters size the size of the block to allocate. re
turn value if the memory cannot be allocated (because of an out-of-memory condition), null is re
turned. otherwise, it re
turns a pointer to the newly allocated memory segment. the result must be freed with a call to free() when it is no longer needed. free frees a previously allocated block of memory. void free( in voidptr ptr ); parameters ptr the address of the memory block to free. this ...
...memory determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). this can be used to trigger the memory pressure observers. note: this method was deprecated in gecko 2.0. if you need to monitor low memory conditions, you should watch for the low memory notifications "memory-pressure" notifications instead. boolean islowmemory(); parameters none. re
turn value true if we are in a low-memory situation. otherwise false. note: from gecko 2.0 always re
turns false. see bug 592308. realloc() reallocates a block of memory to a new size. voidptr realloc( in voidptr ptr, in size_t newsize ); parameters ptr the address of the memory block to reallocate. this may be null, in which case realloc behaves like alloc(). newsize specifies the ne...
... bug 592308. realloc() reallocates a block of memory to a new size. voidptr realloc( in voidptr ptr, in size_t newsize ); parameters ptr the address of the memory block to reallocate. this may be null, in which case realloc behaves like alloc(). newsize specifies the new size in bytes of the block of memory to allocate. this may be 0, in which case realloc behaves like alloc(). re
turn value null if the memory allocation fails. otherwise, it re
turns a pointer to the newly allocated memory segment. the result must be freed with a call to free() when it is no longer needed. low memory notifications an nsimemory implementation may be capable of monitoring heap usage. moreover, a mechanism exists by which a client can receive notifications about low-memory situations. a client ...
nsIMsgSearchCustomTerm
attribute astring name; needsbody /// does this term need the message body? readonly attribute boolean needsbody; methods getenabled /** * is this custom term enabled? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any operator. * * @re
turn true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any oper...
... if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any operator. ...
...m is available for any operator. * * @re
turn true if available */ boolean getavailable(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailableoperators /** * list the valid operators for this term. ...
... [retval, array, size_is(length)] out nsmsgsearchopvalue operators); match /** * apply the custom search term to a message * * @param msghdr header database reference representing the message * @param searchvalue user-set value to use in the search * @param searchop search operator (contains, ishigherthan, etc.) * * @re
turn true if the term matches the message, else false */ boolean match(in nsimsgdbhdr msghdr, in autf8string searchvalue, in nsmsgsearchopvalue searchop); ...
nsINavHistoryResultTreeViewer
his tells you how many items are in the flattened list of results, that is how many rows are in this tree right now. the tree adaptor will also qi to nsitreeview, and this will be the same as nsitreeview.rowcount. this is only valid when a tree is attached, the result will be 0 otherwise. read only. ...
...w. the tree adaptor will also qi to nsitreeview, and this will be the same as nsitreeview.rowcount. this is only valid when a tree is attached, the result will be 0 otherwise. read only. obsolete since gecko 1.9 constants constant value description index_invisible 0xffffffff re
turned by treeindexfornode() when the requested node isn't visible (such as when its parent is collapsed). also re
turned if there is no tree attached. methods nodefortreeindex() re
turns the node for a given row index. ...
...0xffffffff re
turned by treeindexfornode() when the requested node isn't visible (such as when its parent is collapsed). also re
turned if there is no tree attached. methods nodefortreeindex() re
turns the node for a given row index. this is only valid when a tree is attached. nsinavhistoryresultnode nodefortreeindex( in unsigned long aindex ); parameters aindex the row index of the note to re
turn. re
turn value the node located at the specified index in the tree. treeindexfornode() re
turns the row index corresponding to the specified node within the tree, or index_invisible if the tree is unattached or the node is not visible (if, for example, its parent container is collapsed). unsigned long treeindexfornode( in nsinavhistoryresultnode anode ); parameters anode the node whose index i...
...value the node located at the specified index in the tree. treeindexfornode() re
turns the row index corresponding to the specified node within the tree, or index_invisible if the tree is unattached or the node is not visible (if, for example, its parent container is collapsed). unsigned long treeindexfornode( in nsinavhistoryresultnode anode ); parameters anode the node whose index is to be re
turned. this must be a node retrieved from the same result that the viewer displays. re
turn value the row index of the node specified by anode, or index_invisible for nodes that are hidden (by their parents being collapsed, for example) or if there is no attached tree. see also querying places displaying places information using views nsinavhistoryresult nsitreeview ...
nsIPermissionManager
ve permission information for all uris. void removeall(); parameters none. testexactpermission() checks if a uri is permitted to perform an action. this requires an exact hostname match, subdomains are not a match. pruint32 testexactpermission( in nsiuri uri, in string type ); parameters uri the uri to be tested. type a case-sensitive ascii string, identifying the consumer. re
turn value a pruint32 representing the permission, or unknown_action if no permission exists. testexactpermissionfromprincipal() checks if a principal is permitted to perform an action. see testexactpermission(). pruint32 testexactpermissionfromprincipal( in nsiprincipal principal, in string type ); parameters principal the principal to be tested. type a case-sensitive ascii string, id...
...ing the permission, or unknown_action if no permission exists. testexactpermissionfromprincipal() checks if a principal is permitted to perform an action. see testexactpermission(). pruint32 testexactpermissionfromprincipal( in nsiprincipal principal, in string type ); parameters principal the principal to be tested. type a case-sensitive ascii string, identifying the consumer. ...
...a case-sensitive ascii string, identifying the consumer. re
turn value a pruint32 representing the permission, or unknown_action if no permission exists. testpermission() checks if a uri is permitted to perform an action. pruint32 testpermission( in nsiuri uri, in string type ); parameters uri the uri to be tested. type a case-sensitive ascii string, identifying the consumer. re
turn value a pruint32 representing the permission, or unknown_action if no permission exists. testpermissionfromprincipal() checks if a principal is permitted to perform an action. pruint32 testpermissionfromprincipal( in nsiprincipal principal, in string type ); parameters principal the principal to be tested. ...
... remarks this service broadcasts the following notification when the permission list is changed: topic : "perm-changed" (perm_change_notification) broadcast whenever the permission list changes in some way. ...
nsIPrintingPrompt
the service. the service is automatically registered at start up. historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created. windows: the gfx layer no longer supports default toolkit behavior for displaying the native print dialog. if an embedder implemented service re
turns any error code (other than ns_error_abort) printing will terminate. re
turning ns_ok assumes that the printsettings object was correctly filled in and if it does not have valid fields for printer name, and so on. it may also terminate. defaults for platform service: showprintdialog - displays a native dialog showpagesetup() - displays a xul dialog showprogress() - displays a xul dialog s...
...vice is capable of displaying a native print dialog and a xul progress dialog. to fly your own dialog you may: implement this service to display at least the print dialog and a print progress dialog or you may implement just one of the dialogs and pass back ns_error_not_implemented for any of the others. for the print dialog: you may stub out this service by having all the methods re
turn ns_error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the print dialo...
...fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the print dialog. if an embedder implemented service re
turns ns_error_not_implemented for "showprintdialog" the toolkit will display the native print dialog. defaults for platform service: mac os x: showprintdialog - displays a native dialog showpagesetup() - displays a native dialog showprogress() - not implemented (provided by os) gtk: there are no native dialogs for gtk. defaults for platform service: showprintdialog - displays a native d...
... an observer that will be notifed when the dialog is opened. isforprinting true - for printing, false for print preview. webprogresslistener additional listener can be registered for progress notifications. printprogressparams parameter object for passing progress state. notifyonopen this indicates that the observer will be notified when the progress dialog has been opened. if false is re
turned it means the observer (usually the caller) shouldn't wait for print preview progress there is intermediate progress. ...
nsIPushService
subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription() fetches an existing subscription. void getsubscription( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters scope the unique scope url, as passed to ns...
... the subscription nsiprincipal, as passed to nsipushservice.subscribe(). callback the callback to call with the fetched nsipushsubscription. example pushservice.getsubscription( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error fetching subscription: " + code); re
turn; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription. otherwise, it's an instance of `nsipushsubscription`. } ); unsubscribe() drops an existing push subscription. void unsubscribe( in domstring scope, in nsiprincipal principal, in nsiunsubscriberesultcallback callback ); parameters scope the unique scope url, as passed to...
...cribe(). principal the subscription nsiprincipal, as passed to nsipushservice.subscribe(). callback the callback to call when the nsipushsubscription is dropped. example pushservice.unsubscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, ok) => { if (!components.issuccesscode(code)) { cu.reporterror("error unsubscribing: " + code); re
turn; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription. } ); receiving push messages subscriptions created from privileged code use xpcom observer notifications instead of service worker events. you can use the global nsiobserverservice to listen for these notifications. messages sent to system subscription...
...rs. make sure the message is meant // for us. if (data == this.scope) { if (topic == "push-message") { this.onpushmessage(subject); } else if (topic == "push-subscription-change") { this.onpushsubscriptionchange(); } } }, onpushmessage(maybemessage) { if (!maybemesssage) { // the subject will be `null` for messages without data. re
turn; } let message = maybemesssage.queryinterface(ci.nsipushmessage); message.text(); // re
turns the message contents as a utf-8 string. message.json(); // parses the message as json. message.binary(); // re
turns a byte array. }, onpushsubscriptionchange() { // re-subscribe if the subscription was dropped. pushservice.subscribe( this.scope, scriptsecuritym...
nsISHistory
y. index long the index of the current document in session history. read only. maxlength long used to get/set the maximum number of toplevel documents, session history can hold for each instance. requestedindex long the index of the last document that started to load that is not yet finished loading. when the document finishes loading the value -1 is re
turned. read only. shistoryenumerator nsisimpleenumerator called to obtain a enumerator for all the documents stored in session history. the enumerator object thus re
turned by this method can be traversed using nsisimpleenumerator. to access individual history entries of the enumerator, perform the following steps: call getshistoryenumerator() to obtain handle the ns...
... use nsishentry to access properties of each history entry. read only. ...
... use nsishentry to access properties of each history entry. read only. methods addshistorylistener() called to register a listener for the session history component. listeners are notified when pages are loaded or purged from history. ...
... use nsishentry to access properties of each history entry. read only. ...
nsIScreenManager
left, in long top, in long width, in long height ); attributes attribute type description numberofscreens unsigned long the number of screens on the user's computer. read only. primaryscreen nsiscreen the primary display screen; this is the screen with the menu bar (on the mac) or taskbar or equivalent on windows or linux. read only. ...
...the coordinates must be specified using global (screen) coordinates, and are in pixels. ...
... native widget pointer. this pointer's definition is specific to the platform's native widget implementation, and is typically of the same type as ns_native_window. nsiscreen screenfornativewidget( in voidptr nativewidget ); parameters nativewidget the native widget for which to obtain an nsiscreen instance. re
turn value the nsiscreen instance for the native widget pointer. screenforrect() re
turns the nsiscreen containing the specified rectangle. if the rectangle overlaps multiple screens, the screen containing the majority of the rectangle's area is selected and re
turned. the coordinates must be specified using global (screen) coordinates, and are in pixels. nsiscreen screenforrect( in long left, in long top, in long width, in long height ); parameters left the left edge of the...
...e majority of the rectangle's area is selected and re
turned. the coordinates must be specified using global (screen) coordinates, and are in pixels. nsiscreen screenforrect( in long left, in long top, in long width, in long height ); parameters left the left edge of the rectangle. top the top edge of the rectangle. width the width of the rectangle. height the height of the rectangle. re
turn value the nsiscreen containing the majority of the rectangle's area. see also nsiscreen ...
nsIStringBundle
you may also use other formatting codes. you can only pass unicode strings in. the id should refer to a string in the bundle that uses %s, and the number of strings you pass must be the same here and in the properties file (that is you...
...properties file (that is you can't omit %1 and use only %2). do not try to use any other types. this uses nstextformatter::smprintf. wstring formatstringfromid( in long aid, [array, size_is(length)] in wstring params, in unsigned long length ); parameters aid the id of the string to retrieve. params parameters to pass in to the string. length the length of the parameter list. re
turn value re
turns the formatted string. formatstringfromname() re
turns a formatted string with the given key name from the string bundle, where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array. you may also use other formatting codes, but can only pass unicode strings in. the name should refer to a string in the bundle that uses %s, and the number of s...
...'t omit %1 and use only %2). do not try to use any other types. this uses nstextformatter::smprintf to do the dirty work. wstring formatstringfromname( in wstring aname, [array, size_is(length)] in wstring params, in unsigned long length ); parameters aname the name of the string to retrieve. params parameters to pass in to the string. length the length of the parameter list. re
turn value re
turns the formatted string. getsimpleenumeration() nsisimpleenumerator getsimpleenumeration(); parameters none. re
turn value re
turns a nsisimpleenumerator of all nsipropertyelement entries in the string bundle. getstringfromid() retrieves a string from the bundle by its id. wstring getstringfromid( in long aid ); parameters aid the id of the string to retrieve. string i...
...getsimpleenumeration(); parameters none. re
turn value re
turns a nsisimpleenumerator of all nsipropertyelement entries in the string bundle. getstringfromid() retrieves a string from the bundle by its id. wstring getstringfromid( in long aid ); parameters aid the id of the string to retrieve. string id's are assigned by the order in which they are stored in the properties file. re
turn value re
turns the requested string. getstringfromname() retrieves a string from the bundle by its name. wstring getstringfromname( in wstring aname ); parameters aname the name of the string to retrieve. string name are designated in the properties file. re
turn value re
turns the requested string. see also xul:stringbundle xul tutorial:property files nsistringbundleservice ...
nsITelemetry
void clearevents(); test only attributes attribute type description canrecordbase boolean a flag indicating if telemetry can record base data (fhr data). this is true if the fhr data reporting service or the self-support service is enabled. canrecordextended boolean a flag indicating if telemetry is allowed to record extended data. re
turns false if the user has not opted into "extended telemetry" on the release channel, when the user has explicitly opted out of telemetry on nightly/aurora/beta or if manually set to false during tests. canrecordreleasedata readonly boolean a flag indicating whether telemetry is recording release data. does not indicate whether telemetry will send any data. that is governed by user pr...
...-by-default on all channels. dataset_release_channel_optin 1 the extended dataset that is opt-in on release, opt-out on pre-release channels. methods gethistogrambyid() get an histogram by id for histograms registered in histograms.json. jsval gethistogrambyid( in acstring id ); parameters id unique identifier from toolkit/components/telemetry/histograms.json. re
turn value the re
turned jsval object has the following functions: add(value) - adds an integer value to the appropriate bucket snapshot() - re
turns a snapshot of the histogram with the same data fields as in histogramsnapshots. getkeyedhistogrambyid() get a keyed histogram for histograms registered in histograms.json. jsval getkeyedhistogrambyid( in acstring id ); parameters id unique...
...dd(value) - adds an integer value to the appropriate bucket snapshot() - re
turns a snapshot of the histogram with the same data fields as in histogramsnapshots. getkeyedhistogrambyid() get a keyed histogram for histograms registered in histograms.json. jsval getkeyedhistogrambyid( in acstring id ); parameters id unique identifier from toolkit/components/telemetry/histograms.json. re
turn value the re
turned jsval object has the following functions: add(key, [optional] value) - adds an integer value to the appropriate bucket. for count histograms providing the value is optional. ...
...ered in histograms.json. jsval getkeyedhistogrambyid( in acstring id ); parameters id unique identifier from toolkit/components/telemetry/histograms.json. re
turn value the re
turned jsval object has the following functions: add(key, [optional] value) - adds an integer value to the appropriate bucket. for count histograms providing the value is optional. snapshot([optional] key) - re
turns a snapshot of the keyed histogram or (if key is provided) the snapshot of the contained histogram with that key. keys() - re
turns an array with the string keys of the currently registered histograms. clear() - clear out the registered histograms and keys. example you can find detailed information on adding a new telemetry probe and recording telemetry data at adding a new telemetry probe [...
nsIToolkitProfileService
ile arootdir, in autf8string aname); void flush(); nsitoolkitprofile getprofilebyname(in autf8string aname); nsiprofilelock lockprofilepath(in nsilocalfile adirectory, in nsilocalfile atempdirectory); attributes attribute type description profilecount unsigned long the number of user profiles currently in existence. this will always re
turn 0, 1, or 2; if there are more than 2 profiles, 2 is always re
turned. read only. profiles nsisimpleenumerator an enumerator providing access to the list of profiles; each profile is an nsitoolkitprofile object (though you must first call aprofile.queryinterface(components.interfaces.nsitoolkitprofile) to get access to its attributes and methods). selectedprofile nsitoolk...
...) creates a new profile. the profile temporary directory will be chosen based on where the profile directory is located. nsitoolkitprofile createprofile( in nsilocalfile arootdir, in autf8string aname ); parameters arootdir the profile directory. may be null, in which case a suitable default will be chosen based on the profile name. aname the name to give the new profile. re
turn value an nsitoolkitprofile object representing the newly-created profile. exceptions thrown ns_error_unexpected an unexpected error condition occurred. ns_error_file_not_directory one of the specified directory files is not actually a directory. ns_error_out_of_memory unable to allocate the new profile object. flush() flushes the profile list to disk. the profile list fi...
...ions thrown ns_error_out_of_memory an error occurred trying to allocate the memory buffer used to construct the profile list. ns_error_unexpected an error occurred writing the profile list file to disk. getprofilebyname() gets a profile, given the profile's name. nsitoolkitprofile getprofilebyname( in autf8string aname ); parameters aname the profile name to find. re
turn value an nsitoolkitprofile object describing the specified profile. exceptions thrown ns_error_failure no matching profile was found. lockprofilepath() locks an arbitrary path as a profile. if the path does not exist, it is created and the defaults copied from the application directory. nsiprofilelock lockprofilepath( in nsilocalfile adirectory, in nsilocalfile atempdirectory ); pa...
...ath() locks an arbitrary path as a profile. if the path does not exist, it is created and the defaults copied from the application directory. nsiprofilelock lockprofilepath( in nsilocalfile adirectory, in nsilocalfile atempdirectory ); parameters adirectory the directory to lock as a profile directory. atempdirectory the directory to lock as a profile temporary directory. re
turn value an nsiprofilelock object representing the locked directory. see also profile management nsitoolkitprofile nsiprofilelock ...
nsITransport
resulting stream will have blocking stream semantics. this means that if the stream has no data and is not closed, 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 re
turns 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 i...
...m 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 default value). asegmentcount if open_unbuffered is not set, then this parameter specifies the maximum number of buffer segments (pass 0 to use default value). re
turn value openoutputstream() open an output stream on this transport. nsioutputstream openoutputstream( in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount ); parameters aflags optional transport specific flags. flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics. this means that if the...
...d, then the resulting stream will have blocking stream semantics. this means that if the stream is full and is 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 re
turns 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 t...
... 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 of each buffer segment (pass 0 to use default value). asegmentcount if open_unbuffered is not set, then this parameter specifies the maximum number of buffer segments (pass 0 to use default value). re
turn value seteventsink() set the transport event sink. void seteventsink( in nsitransporteventsink asink, in nsieventtarget aeventtarget ); parameters asink receives transport layer notifications. aeventtarget indicates the event target to which the notifications should be delivered. if null, then the notifications may occur on any thread. ...
nsITreeBoxObject
readonly: obtain the treebody content node. this is a node that corresponds to the treechildren tag. rowheight long readonly: obtain the height of a row. rowwidth long readonly: obtain the width of a row. horizontalposition long readonly: get the pixel position of the horizontal scrollbar. selectionregion nsiscriptableregion readonly: re
turn the region for the visible parts of the selection, in device pixels. methods getfirstvisiblerow() get the index of the first visible row. long getfirstvisiblerow(); getlastvisiblerow() get the index of the last visible row. long getlastvisiblerow(); getpagelength() gets the number of possible visible rows. long getpagelength(); ensurerowisvisible() ensures that a row at a given index ...
...te(); void invalidatecolumn(in nsitreecolumn col); void invalidaterow(in long index); void invalidatecell(in long row, in nsitreecolumn col); void invalidaterange(in long startindex, in long endindex); void invalidatecolumnrange(in long startindex, in long endindex, in nsitreecolumn col); getrowat() a hit test that can tell you what row the mouse is over. re
turns -1 for invalid mouse coordinates. the coordinate system is the client coordinate system for the document this boxobject lives in, and the units are css pixels. long getrowat(in long x, in long y); parameters x the x coordinate y the y coordinate getcellat() a hit test that can tell you what cell the mouse is over. re
turns -1 for invalid mouse coordinates. the coordinate syste...
... childelt the pseudoelement hit: this can have values of "cell", "twisty", "image", and "text". getcoordsforcellitem() find the coordinates of an element within a specific cell. ...
...the coordinates of an element within a specific cell. void getcoordsforcellitem(in long row, in nsitreecolumn col, in acstring element, out long x, out long y, out long width, out long height); parameters row the index of the row col the nsitreecolumn element the pseudoelement. this can have values of "cell", "twisty", "image", and "text". re
turns x the x coordinate col the y coordinate. width the width of the element height the height of the element iscellcropped() determine if the text of a cell is being cropped or not. boolean iscellcropped(in long row, in nsitreecolumn col); parameters row the index of the row col the nsitreecolumn rowcountchanged() notify the tree that the number ...
nsITreeColumns
s attribute type description count long the number of columns. read only. length long an alias for count (for the benefit of scripts which treat this as an array). read only. tree nsitreeboxobject the tree widget for these columns. read only. methods getcolumnat() get the column for a given index. nsitreecolumn getcolumnat( in long index ); parameters index index of the column re
turn value a nsitreecolumn for this index. getcolumnfor() get the column for a given element. nsitreecolumn getcolumnfor( in nsidomelement element ); parameters element a dom element re
turn value a nsitreecolumn for this element. getfirstcolumn() get the first column. nsitreecolumn getfirstcolumn(); parameters none. re
turn value the first nsitreecolumn. getkeycolumn() get the key column. nsitree...
...olumnfor() get the column for a given element. nsitreecolumn getcolumnfor( in nsidomelement element ); parameters element a dom element re
turn value a nsitreecolumn for this element. getfirstcolumn() get the first column. nsitreecolumn getfirstcolumn(); parameters none. re
turn value the first nsitreecolumn. getkeycolumn() get the key column. nsitreecolumn getkeycolumn(); parameters none. re
turn value the key nsitreecolumn. getlastcolumn() get the last column. nsitreecolumn getlastcolumn(); parameters none. re
turn value the last nsitreecolumn. getnamedcolumn() get a column for a given name. nsitreecolumn getnamedcolumn( in astring id ); parameters id a column id re
turn value the nsitreecolumn for this id. getprimarycolumn() get the primary column. nsitreecolumn getprimarycolumn(); ...
...invalidatecolumns() this method is called whenever a treecol is added or removed and the column cache needs to be rebuilt. void invalidatecolumns(); parameters none. ...
...invalidatecolumns() this method is called whenever a treecol is added or removed and the column cache needs to be rebuilt. void invalidatecolumns(); parameters none. ...
nsIVersionComparator
omponents.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); parameters a the first version. b the second version. ...
... .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); parameters a the first version. b the second version. ...
...n strings. long compare( in acstring a, in acstring b ); parameters a the first version. b the second version. re
turn value if a and b are two version being compared, and the re
turn value is smaller than 0, then a < b equals 0 then version, then a==b is bigger than 0, then a > b example function compareversions(a,b) { var x = services.vc.compare(a,b); if(x == 0) re
turn a + "==" + b; else if(x > 0) re
turn a + ">" + b; re
turn a + "<" + b; } dump(compareversions("1.0pre", "1.0")); example - compare current browser version this example here uses nsixulappinfo component to get the version of the browser that the code is running in. see here: nsixulappinfo components.utils.import("resource://gre/modules/services.jsm"); var curentbrowserversion = services.appinf...
...owserversion, comparetothisversion); if (compareresult == -1) { //currentbrowserversion is less than '25.*' (comparetothisversion) } else if (compareresult == 0) { //currentbrowserversion is '25.*' (comparetothisversion) } else if (compareresult == 1) { //currentbrowserversion is greater than '25.*' (comparetothisversion) } else { //will never get here as services.vc.compare only re
turns -1, 0, or 1 } see also toolkit version format ...
nsIWinTaskbar
read only. defaultgroupid astring the default application user model id the application registers with the system. this id is used by the taskbar for grouping windows and when associating pinned shortcuts with running instances and jump lists. read ...
...be "foobar systems.squashweb.1.0". see xul application packaging for additional details. methods createjumplistbuilder() retrieve a taskbar jump list builder. fails if a jump list build operation has already been initiated, developers should make use of a single instance of nsijumplistbuilder for building lists within an application. nsijumplistbuilder createjumplistbuilder(); parameters none. re
turn value an nsijumplistbuilder. createtaskbartabpreview() creates a taskbar tab preview, given an nsidocshell reference to a top-level window. nsitaskbartabpreview createtaskbartabpreview( in nsidocshell shell, in nsitaskbarpreviewcontroller controller ); parameters shell an nsidocshell object representing the top-level window from which to create the preview. controller an nsitaskbarpreviewco...
...r. createtaskbartabpreview() creates a taskbar tab preview, given an nsidocshell reference to a top-level window. nsitaskbartabpreview createtaskbartabpreview( in nsidocshell shell, in nsitaskbarpreviewcontroller controller ); parameters shell an nsidocshell object representing the top-level window from which to create the preview. controller an nsitaskbarpreviewcontroller you implement. re
turn value an nsitaskbartabpreview object for the new tab preview. example netscape.security.privilegemanager.enableprivilege("universalxpconnect"); var taskbar = components.classes["@mozilla.org/windows-taskbar;1"].getservice(components.interfaces.nsiwintaskbar); // get the docshell for the browser var navigator2 = top.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(compone...
...terfaces.nsidocshelltreeitem); var parent = docshelltreeitem.parent; var ds = parent.queryinterface(components.interfaces.nsidocshell); // create the preview taskbar.createtaskbartabpreview(ds, {}); gettaskbarprogress() gets the taskbar progress for a window. nsitaskbarprogress gettaskbarprogress( in nsidocshell shell ); parameters shell the nsidocshell used to find the toplevel window. re
turn value an nsitaskbarprogress. gettaskbarwindowpreview() re
turns the taskbar preview for the window whose top level is identified by nsidocshell. nsitaskbarwindowpreview gettaskbarwindowpreview( in nsidocshell shell ); parameters shell an nsidocshell object to use to find the top-level window. re
turn value an nsitaskbarwindowpreview object for the window's preview. setgroupidforwindow() set th...
nsIZipWriter
n the zip file. ns_error_in_progress the zip writer is already performing another operation. close() closes the zip file. void close(); parameters none. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_in_progress the zip writer is already performing another operation. other errors may be thrown if a failure to complete the zip file occurs. getentry() re
turns a specified entry or null if there is no such entry in the current zip file. nsizipentry getentry( in autf8string azipentry ); parameters azipentry the path of the file entry to get. re
turn value an nsizipentry object describing the specified entry, or null if there is no such entry. hasentry() determines whether or not a specific entry exists in the zip file. boolean hasentry( ...
... open() opens the specified zip file. void open( in nsifile afile, in print32 aioflags ); parameters afile the zip file to open. aioflags the open flags for the zip file, from prio.h. ...
... open() opens the specified zip file. void open( in nsifile afile, in print32 aioflags ); parameters afile the zip file to open. aioflags the open flags for the zip file, from prio.h. exceptions thrown ns_error_already_initialized a zip file is already open. ns_error_invalid_arg the afile parameter is null. ...
...//developer.mozilla.org/docs/pr_open#parameters var fu = cu.import('resource://gre/modules/fileutils.jsm').fileutils; var fp = cc['@mozilla.org/filepicker;1'].createinstance(ci.nsifilepicker); fp.init(window, 'select directory to compile', ci.nsifilepicker.modegetfolder); fp.appendfilters(ci.nsifilepicker.filterall | ci.nsifilepicker.filtertext); var rv = fp.show(); if (rv == ci.nsifilepicker.re
turnok) { var dir = fp.file; //dir must exist, as the user selected it. but note that if dir doesnt exist zw.open throws problems //var path = fp.file.path; //re
turns c:\users\3k2kyc1\documents\prefs\prefs var xpi = fu.file(dir.path + '\\' + dir.leafname + '.zip'); zw.open(xpi, pr.pr_rdwr | pr.pr_create_file | pr.pr_truncate); //pr_truncate overwrites if file exists //pr_create_f...
NS ENSURE SUCCESS
summary macro re
turns re
turn-value if ns_failed(nsresult) evaluates to true, and shows a warning on stderr in that case. ...
... summary macro re
turns re
turn-value if ns_failed(nsresult) evaluates to true, and shows a warning on stderr in that case. ...
...alue if ns_failed(nsresult) evaluates to true, and shows a warning on stderr in that case. ...
...led(nsresult) evaluates to true, and shows a warning on stderr in that case. ...
NS_CStringCloneData
the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. see bug 239716 for details. ...
NS_StringCloneData
the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. see bug 239716 for details. ...
Using the clipboard
te a constructor for the built-in supports-string class. ...
...now that we have the object to copy, a transferring object needs to be created: var str = "text to copy"; var trans = transferable(sourcewindow); trans.adddataflavor("text/unicode"); // we multiply the length of the string by 2, since it's stored in 2-byte utf-16 // forma...
...here are the steps to pasting: create a clipboard object which refers to the system clipboard. create a transferring object which implements the nsitransferable interface. initialize the transferring obje...
...e need to get the data from the clipboard: services.clipboard.getdata(trans, services.clipboard.kglobalclipboard); var str = {}; var strlength = {}; trans.gettransferdata("text/unicode", str, strlength); the first line performs the opposite of setdata. the data currently on the system clipboard is placed into the transferable. next we create two javascript objects which will hold the re
turn values from gettransferdata. then we use gettransferdata to retrieve the data from the transferable. we specify the flavor we would like to get. the data will be converted if it is not available in the desired flavor, and a conversion from an available flavor is possible. if you originally copied data of multiple flavors onto the clipboard, you can retrieve the data in the best format necessary.
Gloda examples
r using gloda. see creating a gloda message query for more examples. ...
...tagarray = mailservices.tags.getalltags({}); query.tags(...tagarray); let collection = query.getcollection(mylistener); search messages by daterange searches for all messages within a date range id_q=gloda.newquery(gloda.noun_message); // define a date range form yesterday to now id_q.daterange([new date() - 86400000, new date()]); var mylistener = { /* called when new items are re
turned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function _onitemsremoved(...
...ges 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. ...
... acollection) { }, onitemsmodified: function _onitemsmodified(aitems, acollection) { }, onitemsremoved: function _onitemsremoved(aitems, acollection) { }, onquerycompleted: function _onquerycompleted(id_coll) { //woops no identity if (id_coll.items.length <= 0) re
turn; id = id_coll.items[0]; //now we use the identity to find all messages that person was involved with msg_q=gloda.newquery(gloda.noun_message) msg_q.involves(id) msg_q.getcollection({ /* called when new items are re
turned by the database query or fresh...
Mail and RDF
| mailbox_message://alecf@pop.mywork.com/inbox#2 | etc... there are of course many more properties that are exposed via rdf, but this should give you a feel for it. datasources we have a few primary datasources used in mail: nsmsgaccountdatasource - answers queries about arcs coming out of msgaccounts:/. if you ask it for #child nodes out of msgaccounts:/, it re
turns the root uris of all servers in the account manager. note that it does not actually know anything about the servers who's uris it re
turns. nsmsgfolderdatasource - answer queries about any mail folders, including toplevel server folders. if asked about a folder along the #child arc, it will re
turn resources for all subfolders in that folder. if asked about a folder along the #messagechild arc, i...
...it also answers queries about various properties of folders such as the total number of messages, whether or not this folder is actually a root server, and so forth. nsmsgmessagedatasource - answers queries about messages in folders. ...
...://home.netscape.com/nc-rdf#totalmessages"); var resultnode = datasource.gettarget(target, property, true); in the folder datasource's gettarget(), target would be queryinterfaced to a nsimsgfolder. to get the total messages, the datasource would then call nsimsgfolder.gettotalmessages(). finally, it would convert the result of this call to an rdf literal, and pass it back through the re
turn parameter of gettarget(). an example of how this might work inside the datasource: var msgcountarc = rdf.getresource("http://home.netscape.com/nc-rdf#totalmessages"); function gettarget(target, property, unused) { var folder = target.queryinterface(components.interfaces.nsimsgfolder); if (property == msgcountarc) { var msgcount = folder.gettotalmessages(false);...
... 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 templat...
Adding items to the Folder Pane
it displays. the folder pane tracks modifications to a user's folders and accounts. each time the folder pane determines that it is necessary to invalidate all its data (because of too many changes, or more commonly because the folder pane's "mode" (aka view) has changed), a "rebuild" occurs. when this happens, the folder pane consults the map-generator for the current mode, and that generator re
turns the necessary data for the folder pane's display. this data is re
turned in the form of an array of folder-tree-items. listening for folder pane rebuilds every time the folder pane rebuilds, it fires a "maprebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. the following code snippet listens for that event: let gnumbersext = { load: function ...
...s" container looks like this: let containerrow = { _numbers: 3, id: "numbers-main-container", text: "numbers", level: 0, open: false, _children: null, get children() { if (!this._children) { this._children = []; for (var i = 1; i <= this._numbers; i++) this._children.push(new numberrow(i)); } re
turn this._children; }, getproperties: function gne_getprops() { // put your css attributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.t...
...ents.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; second, our child items (the numbers 1, 2, and 3) are copies of the following prototype: function numberrow(anumber) { this._number = anumber; } numberrow.prototype = { get id() { re
turn "numbers-child-row-" + this._number; }, get text() { re
turn this._number; }, level: 1, open: false, children: [], getproperties: function gne_kid_getprops() {}, // no-op command: function gne_kid_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(co...
... .alert(window, null, this.text); } }; putting it all together all that is left at this point is to actually add these newly defined folder-tree-items to the folder pane's _rowmap at the appropriate time. thus, our _insert function becomes _insert: function gne__insert() { // only insert our nodes into the "all" mode if (gfoldertreeview.mode != "all") re
turn; gfoldertreeview._rowmap.push(containerrow); }, right now, clicking on these additional items has no effect. however, the complete example file includes code to display the number selected in thunderbird's main viewing pane, when such a number is selected in the folder pane. a note about the initial rebuild when thunderbird first starts up, the folder pane does an initial rebuild to get...
Creating a Custom Column
the following is a list of functions that must be implemented to ensure that your extension works well with thunderbird. rest assured that these functions will be called - so implement them, even with empty function. ...
...implemented to ensure that your extension works well with thunderbird. rest assured that these functions will be called - so implement them, even with empty function. ...
...t them, even with empty function. from nsitreeview: getcellproperties(row, col, props): optionally modify the props array getrowproperties(row, props): optionally modify the props array getimagesrc(row, col): re
turn a string (or null) getcelltext(row, col): re
turn a string representing the actual text to display in the column from nsimsgcustomcolumnhandler: getsortstringforrow(hdr): re
turn the string value that the column will be sorted by getsortlongforrow(hdr): re
turn the long value that the column will be sorted by isstring(): re
turn true / false warning! do not get confused between getcelltext() and getsortstring/longforrow()! though they sound similar you may not want to re
turn the same value from both. getcelltext() is the text that is displayed to the user while getsort*...
...what is used internally when sorting by your column a simple implementation objects in javascript are just "advanced" variables, so an implementation of the nsimsgcustomcolumnhandler interface looks like: var columnhandler = { getcelltext: function(row, col) { //get the message's header so that we can extract the reply to field var hdr = gdbview.getmsghdrat(row); re
turn hdr.getstringproperty("replyto"); }, getsortstringforrow: function(hdr) {re
turn hdr.getstringproperty("replyto");}, isstring: function() {re
turn true;}, getcellproperties: function(row, col, props){}, getrowproperties: function(row, props){}, getimagesrc: function(row, col) {re
turn null;}, getsortlongforrow: function(hdr) {re
turn 0;} } basically, ...
Activity Manager examples
ator = aactivity.initiator; if (initiator) { let folder = aactivity.getsubjects({})[0]; .... // assuming that the initiator has some way to cancel // the junk processing for given folder if (initiator.cancelfolderop(folder)) { aactivity.state = components.interfaces.nsiactivityprocess.state_canceled; gactivitymanager.removeactivity(aactivity.id); re
turn cr.ns_success; } } re
turn cr.ns_failure; } } // step 2: modify the previous sample to add initiator, subject // and associate a nsiactivitycancelhandler component ... // assuming that gjunkprocessor is the entity initiating the junk processing // activity, and it has cancelfolderop method that cancels the operations on folders process.init("processing folder: " + folder.prettiestname,...
...tivityundohandler mycopyeventundo() {} private: ~mycopyeventundo() {} }; ns_impl_isupports1(mycopyeventundo, nsiactivityundohandler) ns_imethodimp mycopyeventundo::undo(nsiactivityevent *event, nsresult *result) { nsresult rv; // get the subjects of this copy event pruint32 length; nsivariant **subjectlist; rv = event->getsubjects(&length, &subjectlist); if(ns_failed(rv)) re
turn rv; // first subject in the list is the source folder in this particular case nscomptr<nsimsgfolder> folder = do_queryinterface(subjectlist[0]); // get the initiator nsivariant *initiator; event->getinitiator(&initiator); if (initiator) { nsisupports* ptr; rv = object->getasisupports(&ptr); if(ns_failed(rv)) re
turn rv; nscomptr<nsimsgcopyservice> copyservic...
...we want to // associate it with the even...
...let process = new nsactprocess("processing folder: " + folder.prettiestname, ...
CType
property type description name string the type's name. read only. for primitive types, this is just the name of the corresponding c type. for structure and opaque pointer types, this is simply the string that was passed to the constructor. for other function, pointer, and array types, this should be a valid c type expression. ...
...expression. ptr ctype re
turns a ctype representing the data type "pointer to this type". this is the result of calling ctypes.pointertype(the_type). read only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. methods available on all ctype objects array() re
turns a new ctype representing an array of elements of the type on which it was called. ctype array( [n] }; parameters n optional the number of elements in the declared array type. if this parameter is left out, the array's size is indeterminate. re
turn value a ctype representing the data type "array of this type". this is the same as calling ctypes.arraytype(the_type[, n]). tosource() r...
... a new ctype representing an array of elements of the type on which it was called. ctype array( [n] }; parameters n optional the number of elements in the declared array type. if this parameter is left out, the array's size is indeterminate. re
turn value a ctype representing the data type "array of this type". this is the same as calling ctypes.arraytype(the_type[, n]). tosource() re
turns a javascript expression that evaluates to a ctype describing the same c type as this object. string tosource(); parameters none. re
turn value a javascript expression that evaluates to a ctype describing the same c type as this object. example ctypes.uint32_t.tosource() re
turns "ctypes.uint32_t". tostring() re
turns a string identifying the type. the format of this string is "type " + na...
...type describing the same c type as this object. string tosource(); parameters none. re
turn value a javascript expression that evaluates to a ctype describing the same c type as this object. example ctypes.uint32_t.tosource() re
turns "ctypes.uint32_t". tostring() re
turns a string identifying the type. the format of this string is "type " + name. string tostring(); parameters none. re
turn value a string identifying the data type. see also arraytype functiontype pointertype structtype type conversion ...
PointerType
exceptions thrown typeerror thrown if the parameter isn't a ctype. examples creating a type "pointer to 32-bit integer" looks like this: var intptrtype = new ctypes.pointertype(ctypes.int32_t); properties property type description targettype ctype the type of object the pointer points to. read only. ...
... property type description name string the type's name. read only. for primitive types, this is just the name of the corresponding c type. for structure and opaque pointer types, this is simply the string that was passed to the constructor. for other function, pointer, and array types, this should be a valid c type expression. ptr ctype re
turns a ctype representing the data type "pointer to this type". this is the result of calling ctypes.pointertype(the_type). read only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. method overview methods inherited from ctype ctype array([n]) string tosource(...
...ead only. size number the size of the type, in bytes. this is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() pointertype cdata syntax cdata pointertype(); pointertype is pointertype ctype. re
turn value a cdata representing the newly allocated pointer. pointertype cdata properties property type description contents cdata reading this property re
turns a cdata object referring to the pointed-to contents of the object. writing to this value writes the c conversion of the data into the pointed-to memory. if converting the data fails, a typeerror exception is th...
...'s value. this will throw a typeerror exception if the value can't be converted. pointertype cdata method_overview bool isnull() methods inherited from cdata cdata address() string tosource() string tostring() pointertype cdata methods isnull() determines whether or not the pointer's value is null. bool isnull(); parameters none. re
turn value true if the pointer's value is null, otherwise false. see also ctype cdata type conversion ...
js-ctypes reference
ta to use js-ctypes effectively, it is important to understand the different kinds of objects that the module provides. there are three major categories: types these represent a type in c, and are thus represented by ctype objects. these objects have two main purposes. first, they provide a concrete representation of different data types, allowing the programmer to describe the arguments and re
turn type of a native function (see library.declare()). second, they serve as constructors to create concrete instances of the given type, i.e. cdata objects. out of the box, js-ctypes supports a number of predefined types. type constructors these are functions that define new types, and thus re
turn a ctype object. these include ctypes.pointertype(type) and the .ptr property, which creates a ne...
..., and thus re
turn a ctype object. these include ctypes.pointertype(type) and the .ptr property, which creates a new type describing a pointer to an existing type. ctypes.arraytype(type, [length]) and the .array() method, which creates a new type describing an array of objects of an existing type. ctypes.structtype(), which creates a new type describing a c struct. ctypes.functiontype(abi, re
turntype, argtype1 [, argtype2 ...]), which creates a new type describing a c function. data these are instances of types, represented by cdata objects and instantiated by calling ctype objects as functions. these distinctions are crucial, and understanding them will alleviate much of the confusion surrounding js-ctypes. calling a type constructor will re
turn a ctype. ...
...you call a native function with cdata objects. other features error-handling js-ctypes supports both errno (on all platforms) and getlasterror (on windows platforms). callbacks you can pass regular javascript functions as callbacks to native functions. see the callbacks page for details. ...
...reates a new type describing a c function. data these are instances of types, represented by cdata objects and instantiated by calling ctype objects as functions. these distinctions are crucial, and understanding them will alleviate much of the confusion surrounding js-ctypes. calling a type constructor will re
turn a ctype. calling a ctype will re
turn a cdata. you declare the arguments and re
turn value of a native function with ctype objects. you call a native function with cdata objects. other features error-handling js-ctypes supports both errno (on all platforms) and getlasterror (on windows platforms). callbacks you can pass regular javascript functions as callbacks to native functions. see the callbacks page for details. 64-bit integer handling because javascript number object...
Plug-in Development Overview - Plugins
ngual" in your development environment. the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser loads each library and calls into the np_getmimedescription entry point. this exported c function should re
turn a string containing the type, extension list, and type description separated by colons. each mime types should be separated by semicolons. for example: image/xbm:xbm:x bitmap or for 2 mime types: image/xbm:xbm:x bitmap;image/png:png:portable network graphics. this information will then appear in the navigator.mimetypes dom object. npp_getvalue is called after the plug-in is initialized to get th...
...raphics. this information will then appear in the navigator.mimetypes dom object. npp_getvalue is called after the plug-in is initialized to get the scripting interface while np_getvalue is called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins. caution: gecko caches the values re
turned by these functions and will only call it if the plug-in's timestamp has changed. see bug 125469. mac os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmi...
...'s timestamp has changed. see bug 125469. mac os x mac os x plug-ins are found according to the section how gecko finds plug-ins. plug-ins are identified by file type nspl. to determine the supported mime types, gecko first checks for registry information in the plugins info.plist. if nothing is found there, gecko checks for an np_getmimedescription entry point, and will use the information re
turned by this function. note: the resource method described below is deprecated. plugins should use the info.plist approach, and only use the following method as a supplement to support older browsers. if neither is present, gecko will check the plugins resources. 'str#' 128 should contain a list of mime types and file extensions in alternating strings. for example: str 128 mime type...
...ction operates like npn_posturl, except that it notifies the plug-in of the result when the operation completes. for information about using these methods, see urls. starting in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), you can get the origin of the document in a secure, convenient way by calling npn_getvalue() to retrieve the value of the variable npnvdocumentorigin. the re
turned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8. your plug-in must free the re
turned string's memory by calling npn_memfree() when you're done with it. getting version and ui information the netscape group of plug-in api methods provides some basic services to the plug-in. you can use these netscape methods: to identify the ...
Debugger.Environment - Firefox Developer Tools
ronment within the function, which receives var definitions) for a call to a functionf, then this property’s value is a debugger.object instance referring tof. otherwise, this property’s value is null. optimizedout true if this environment is optimized out. false otherwise. for example, functions whose locals are never aliased may present optimized-out environments. ...
...ue, getvariable re
turns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror. function properties of the debugger.environment prototype object the methods described below may only be called with a this value referring to a debugger.environment instance; they may not be used as methods of other kinds of objects. names() re
turn an array of strings giving the names of the identifiers bound by this environment. the result does not include the names of identifiers bound by enclosing environments. getvariable(name) re
turn the value of the variable bound toname in this environment, or undefined if this environment does not bindname.name must be a string that is a valid ecmascript identifier name. the result is a debuggee...
...lue of the variable bound toname in this environment, or undefined if this environment does not bindname.name must be a string that is a valid ecmascript identifier name. the result is a debuggee value. javascript engines often omit variables from environments, to save space and reduce execution time. if the given variable should be in scope, but getvariable is unable to produce its value, it re
turns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true. this is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with statement’s operand), this call throws a debugger.debuggeewouldrun exception. setvariable(name,value) ...
...revalue as the value of the variable bound toname in this environment.name must be a string that is a valid ecmascript identifier name;value must be a debuggee value. if this environment binds no variable namedname, throw a referenceerror. this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewouldrun exception. find(name) re
turn a reference to the innermost environment, starting with this environment, that bindsname. ifname is not in scope in this environment, re
turn null.name must be a string whose value is a valid ecmascript identifier name. source metadata generated from file: js/src/doc/debugger/debugger.environment.md watermark: sha256:3d6f67939e351803d5d7fe201ed38c4aaf766caf032f255e168df1f1c6fe73cb chan...
Debugger.Memory - Firefox Developer Tools
some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true. a bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationsamplingprobability of all debugger instances d that are observing the global that this object is allocated within the scope of. given a debugger.object instancedobj referring to some object, dobj.allocationsite re
turns a saved call stack indicating wheredobj’s referent was allocated. allocation logging ifdbg is a debugger instance, and dbg.memory.trackingallocationsites is set to true, then the javascript engine logs each object allocated bydbg’s debuggee code. you can retrieve the current log by calling dbg.memory.drainallocationslog. you can control the limit on the log’s size by setting dbg.memory.m...
...at in the presence of multiple debugger instances observing the same allocations within a global’s scope, the maximum allocationsamplingprobability of all the debuggers is used. maxallocationsloglength the maximum number of allocation sites to accumulate in the allocations log at a time. this accessor can be both fetched and stored to. its default value is 5000. allocationslogoverflowed re
turns true if there have been more than [maxallocationsloglength][#max-alloc-log] allocations since the last time [drainallocationslog][#drain-alloc-log] was called and some data has been lost. re
turns false otherwise. debugger.memory handler functions similar to debugger’s handler functions, debugger.memory inherits accessor properties that store handler functions for spidermonkey to call when g...
...the handler functions receive the debugger.memory’s owning debugger instance as their this value. the owning debugger’s uncaughtexceptionhandler is still fired for errors thrown in debugger.memory hooks. ...
......
Web Console Helpers - Firefox Developer Tools
the commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier. $(selector, element) looks up a css selector string selector , re
turning the first node descended from element that matches. if unspecified, element defaults to document. equivalent to document.queryselector() or calls the $ function in the page, if it exists. see the queryselector code snippet. $$(selector, element) looks up a css selector string selector, re
turning an array of dom nodes descended from element that match. if unspecified, element defaults to document. this is like for document.queryselectorall(), but re
turns an array instead of a nodelist. $0 the currently-inspected element in the page. $_ stores the result of the last ex...
...for document.queryselectorall(), but re
turns an array instead of a nodelist. $0 the currently-inspected element in the page. $_ stores the result of the last expression executed in the console's command line. for example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4. $x(xpath, element, resulttype) evaluates the xpath xpath expression in the context of element and re
turns an array of matching nodes. if unspecified, element defaults to document. the resulttype parameter specifies the type of result to re
turn; it can be an xpathresult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, any_type is used. :block (starting in firefox 80) followed by an unquoted string, blocks requests where the url contains that stri...
...led on the argument, and the result will be copied to the clipboard. help()deprecated since gecko 62 :help displays help text. actually, in a delightful example of recursion, it brings you to this page. inspect() given an object, generates rich output for that object. once you select the object in the output area, you can use the arrow keys to navigate the object. keys() given an object, re
turns a list of the keys (or property names) on that object. this is a shortcut for object.keys. pprint() obsolete since gecko 74 formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays. :screenshot creates a screenshot of the current page with the supplied filename. if you don't supply a filename, the image file will be named with the following...
... a single element on the page. when supplied, only this element will be included in the screenshot. :unblock (starting in firefox 80) followed by an unquoted string, removes blocking for urls containing that string. in the network monitor, the string is removed from the request blocking sidebar. no error is given if the string was not previously blocked. values() given an object, re
turns a list of the values on that object; serves as a companion to keys(). please refer to the console api for more information about logging from content. variables tempn the "use in console" option in the inspector generates a variable for a node named temp0, temp1, temp2, etc. referencing the node. examples looking at the contents of a dom node let's say you have a dom node with the id ...
AudioTrack - Web APIs
l of "commentary with director john q. public and actors john doe and jane eod." this string is empty if no label is provided. language read only a domstring specifying the audio track's primary language, or an empty string if unknown. the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. ...
...fc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. re
turns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which re
turns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach(). this first example gets the first audio track on the media: var firsttrack = tracks[0]; the next example scans through ...
... tracks, enabling any that are in the user's preferred language (taken from a variable userlanguage) and disabling any others. tracks.foreach(function(track) { if (track.language === userlanguage) { track.enabled = true; } else { track.enabled = false; } }); the language is in standard (rfc 5646) format. for us english, this would be "en-us", for example. example this example re
turns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element. the list is filtered to only allow certain track kinds through. function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedk...
...only allow certain track kinds through. function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); re
turn tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label. specifications specification status comment html living standardthe definition of 'audiotrack' in that specification. living standard html5the definition of 'audiotrack...
AudioWorkletProcessor - Web APIs
the audioworkletprocessor interface of the web audio api represents an audio processing code behind a custom audioworkletnode. it lives in the audioworkletglobalscope and runs on the web audio rendering thread. in
turn, an audioworkletnode based on it runs on the main thread. constructor the audioworkletprocessor and classes that derive from it cannot be instantiated directly from a user-supplied code. instead, they are created only internally by the creation of an associated audioworkletnodes. ...
...plied code. instead, they are created only internally by the creation of an associated audioworkletnodes. the constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details. audioworkletprocessor() creates a new instance of an audioworkletprocessor object. properties port read only re
turns a messageport used for bidirectional communication between the processor and the audioworkletnode which it belongs to. the other end is available under the port property of the node. methods the audioworkletprocessor interface does not define any methods of its own. however, you must provide a process() method, which is called in order to process the audio stream. events the audioworkletpro...
...put and output arrays and calculated values of custom audioparams (if they are defined) as parameters. you can use inputs and audio parameter values to fill the outputs array, which by default holds silence. optionally, if you want custom audioparams on your node, you can supply a parameterdescriptors property as a static getter on the processor. the array of audioparamdescriptor-based objects re
turned is used internally to create the audioparams during the instantiation of the audioworkletnode. the resulting audioparams reside in the parameters property of the node and can be automated using standard methods such as linearramptovalueattime. their calculated values will be passed into the process() method of the processor for you to shape the node output accordingly. processing audio an ex...
...ich will output white noise, and register it. note that this should be done in a separate file. // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) re
turn true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode, passing it the name of the processor, then connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audiowor...
BaseAudioContext - Web APIs
it starts at 0. baseaudiocontext.destination read only retur...
...a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties baseaudiocontext.audioworklet read only secure context re
turns the audioworklet object, which can be used to create and manage audionodes in which javascript code implementing the audioworkletprocessor interface are run in the background to process audio data. baseaudiocontext.currenttime read only re
turns a double representing an ever-increasing hardware time in seconds used for scheduling. it starts at 0. baseaudiocontext.destination read only re
turns an audiodestinationnode representing the final destination of all audio in the context. it can be thought of as the audio-rendering device. baseaudiocontext.listener read only re
turns the audiolistener object, used for 3d spatialization. bas...
...ing hardware time in seconds used for scheduling. it starts at 0. baseaudiocontext.destination read only re
turns an audiodestinationnode representing the final destination of all audio in the context. it can be thought of as the audio-rendering device. baseaudiocontext.listener read only re
turns the audiolistener object, used for 3d spatialization. baseaudiocontext.samplerate read only re
turns a float representing the sample rate (in samples per second) used by all nodes in this context. the sample-rate of an audiocontext cannot be changed. baseaudiocontext.state read only re
turns the current state of the audiocontext. event handlers baseaudiocontext.onstatechange an event handler that runs when an event of type statechange has fired. this occurs when the audiocontext's state...
..., band-pass, etc baseaudiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode. baseaudiocontext.createbuffersource() creates an audiobuffersourcenode, which can be used to play and manipulate audio data contained within an audiobuffer object. audiobuffers are created using audiocontext.createbuffer or re
turned by audiocontext.decodeaudiodata when it successfully decodes an audio track. baseaudiocontext.createconstantsource() creates a constantsourcenode object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value. baseaudiocontext.createchannelmerger() creates a channelmergernode, which is used to combine channels from mult...
Using the Beacon API - Web APIs
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. ...
...iew. 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 re
turns true and re
turns false otherwise. ...
...may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method re
turns true and re
turns false otherwise. the following example specifies a handler for the load and beforeunload events. the handler calls sendbeacon() with the current url. ...
..."success" : "fail"); } else { postmessage("worker: self.navigator.sendbeacon is unsupported"); } } see also beacon api (overview) beacon standard beacon caniuse data ...
BluetoothCharacteristicProperties - Web APIs
the bluetoothcharacteristicproperties interface of the the web bluetooth api provides the operations that are valid on the given bluetoothremotegattcharacteristic. this interface is re
turned by calling bluetoothremotegattcharacteristic.properties. properties authenticatedsignedwritesread only re
turns a boolean that is true if signed writing to the characteristic value is permitted. broadcastread only re
turns a boolean that is true if the broadcast of the characteristic value is permitted using the server characteristic configuration descriptor. ...
...e
turned by calling bluetoothremotegattcharacteristic.properties. properties authenticatedsignedwritesread only re
turns a boolean that is true if signed writing to the characteristic value is permitted. broadcastread only re
turns a boolean that is true if the broadcast of the characteristic value is permitted using the server characteristic configuration descriptor. indicateread only re
turns a boolean that is true if indications of the characteristic value with acknowledgement is permitted. notifyread only re
turns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted. readread only re
turns a boolean that is true if the reading of the characteristic value is permitted. ...
...or. indicateread only re
turns a boolean that is true if indications of the characteristic value with acknowledgement is permitted. notifyread only re
turns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted. readread only re
turns a boolean that is true if the reading of the characteristic value is permitted. reliablewriteread only re
turns a boolean that is true if reliable writes to the characteristic is permitted. writableauxiliariesread only re
turns a boolean that is true if reliable writes to the characteristic descriptor is permitted. writeread only re
turns a boolean that is true if the writing to the characteristic with response is permitted. ...
... examples the following example shows how tell if a gatt characteristic supports value change notifications. ...
Body.arrayBuffer() - Web APIs
examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. ...
... examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. ...
...e up to the audiocontext.destination. ...
... living standard ...
Body.body - Web APIs
eader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
...stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
...tream — effectively creating an identical copy of the image. ...
...y as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); re
turn new readablestream({ start(controller) { re
turn pump(); function pump() { re
turn reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); re
turn; } // enqueue the next data chunk into our target stream controller.enqueue(value); re
turn pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); specifications specifi...
CSS Painting API - Web APIs
nterfaces paintworklet programmatically generates an image where a css property expects a file. access this interface through css.paintworklet. paintworkletglobalscope the global execution context of the paintworklet. paintrenderingcontext2d implements a subset of the canvasrenderingcontext2d api. it has an output bitmap that is the size of the object it is rendering to. paintsize re
turns the read-only values of the output bitmap's width and height. dictionaries paintrenderingcontext2dsettings a dictionary providing a subset of canvasrenderingcontext2d settings. examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet ad...
...cript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function. ...
...sterpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function. ...
...et using the paintworklet addmodule() method, then include the image we created using the css paint() function. ...
Cache.keys() - Web APIs
this can be a request object or a url. options optional an object whose properties control how matching is done in the keys operation. ...
...this can be a request object or a url. options optional an object whose properties control how matching is done in the keys operation. ...
...this can be a request object or a url. options optional an object whose properties control how matching is done in the keys operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. ...
... to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header. it defaults to false. cachename: a domstring that represents a specific cache to search within. note that this option is ignored by cache.keys(). re
turn value a promise that resolves to an array of cache keys. examples caches.open('v1').then(function(cache) { cache.keys().then(function(keys) { keys.foreach(function(request, index, array) { cache.delete(request); }); }); }) specifications specification status comment service workersthe definition of 'cache: keys' in that specification. working draf...
CacheStorage.keys() - Web APIs
examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. ...
...at will resolve with an array containing strings corresponding to all of the named cache objects tracked by the cachestorage object in the order they were created. use this method to iterate over a list of all cache objects. you can access cachestorage through the global caches property. syntax caches.keys().then(function(keylist) { //do something with your keylist }); parameters none. ...
... parameters none. re
turn value a promise that resolves with an array of the cache names inside the cachestorage object. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. here we have a whitelist containing the names of the caches we want to keep (cachewhitelist). we re
turn the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist. if not, we delete it using cachestorage.delete(). ...
...ntaining the names of the caches we want to keep (cachewhitelist). we re
turn the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist. if not, we delete it using cachestorage.delete(). then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.keys().then(function(keylist) { re
turn promise.all(keylist.map(function(key) { if (cachewhitelist.indexof(key) === -1) { re
turn caches.delete(key); } }); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: keys' in that specification. working draft initial definition. ...
CacheStorage.open() - Web APIs
examples this example is from the mdn sw-test example (see sw-test running live). ...
... examples this example is from the mdn sw-test example (see sw-test running live). ...
... examples this example is from the mdn sw-test example (see sw-test running live). ...
...-test example (see sw-test running live). here we wait for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open() to create a new cache, then using cache.addall() to add a series of assets to it. ...
Applying styles and colors - Web APIs
operties which allow us to style lines. linewidth = value sets the width of lines drawn in the future. linecap = type sets the appearance of the ends of lines. linejoin = type sets the appearance of the "corners" where lines meet. miterlimit = value establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes. getlinedash() re
turns the current line dash pattern array containing an even number of non-negative numbers. setlinedash(segments) sets the current line dash pattern. linedashoffset = value specifies where to start a dash array on a line. you'll get a better understanding of what these do by looking at the examples below. a linewidth example this property sets the current line thickness. values must be positi...
...cument.getelementbyid('miterlimit').value.match(/\d+(\.\d+)?/)) { ctx.miterlimit = parsefloat(document.getelementbyid('miterlimit').value); } else { alert('value must be a positive number'); } // draw lines ctx.beginpath(); ctx.moveto(0, 100); for (i = 0; i < 24 ; i++) { var dy = i % 2 == 0 ? ...
...(); ctx.moveto(0, 100); for (i = 0; i < 24 ; i++) { var dy = i % 2 == 0 ? ...
...very obvious from the code because it uses two different css color methods as a demonstration, but in the first gradient #019f62 = rgba(1,159,98,1). screenshotlive sample patterns in one of the examples on the previous page, we used a series of loops to create a pattern of images. there is, however, a much simpler method: the createpattern() method. createpattern(image, type) creates and re
turns a new canvas pattern object. image is a canvasimagesource (that is, an htmlimageelement, another canvas, a <video> element, or the like. type is a string indicating how to use the image. the type specifies how to use the image in order to create the pattern, and must be one of the following string values: repeat tiles the image in both vertical and horizontal directions. repeat-x tiles t...
Clients - Web APIs
clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. ...
... clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. ...
... clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. ...
... clients.claim() allows an active service worker to set itself as the controller for all clients within its scope. ...
Clipboard.readText() - Web APIs
to read non-text contents from the clipboard, use the read() method instead. you can write text to the clipboard using writetext(). ...
... to read non-text contents from the clipboard, use the read() method instead. you can write text to the clipboard using writetext(). ...
... to read non-text contents from the clipboard, use the read() method instead. you can write text to the clipboard using writetext(). ...
...empty string if the clipboard is empty, does not contain text, or does not include a textual representation among the datatransfer objects representing the clipboard's contents. to read non-text contents from the clipboard, use the read() method instead. you can write text to the clipboard using writetext(). example this example retrieves the textual contents of the clipboard and inserts the re
turned text into an element's contents. navigator.clipboard.readtext().then( cliptext => document.getelementbyid("outbox").innertext = cliptext); specifications specification status comment clipboard api and eventsthe definition of 'readtext()' in that specification. working draft initial definition. ...
ClipboardItem - Web APIs
note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. note: you can only pass in one clipboard item at a time. constructor clipboarditem.clipboarditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties. types read only re
turns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() re
turns 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, ...
...ray of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() re
turns 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. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(...
... async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { ...
... navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're re
turning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and re
turn the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.
Constraint validation API - Web APIs
this will be displayed in the ui if the element is ...
...ve a form attribute that indicates their form owner): htmlbuttonelement htmlfieldsetelement htmlinputelement htmlobjectelement htmloutputelement htmlselectelement htmltextareaelement properties validity a read-only property that re
turns a validitystate object, whose properties represent validation errors for the value of that element. validationmessage a read-only property that re
turns an empty string if the element is not a candidate for constraint validation, or if the element's value is valid. if the element's value is not valid, it re
turns a localized validation message. this will be displayed in the ui if the element is the only form control with a validity problem; if a custom error message is set using setcustomvalidity(), this will be shown. willvalidate a read-only ...
...elements with the htmlobjectelement interface are never candidates for constraint validation. others may be barred from constraint validation depending on specific conditions. ...
...lement is a candidate for constraint validation; and false otherwise. elements with the htmlobjectelement interface are never candidates for constraint validation. others may be barred from constraint validation depending on specific conditions. methods checkvalidity() checks the element's value against its constraints. if the value is invalid, it fires an invalid event at the element and re
turns false; otherwise it re
turns true. reportvalidity() htmlformelement method checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, re
turns false, and then reports the validity status to the user in whatever way the user agent has available. otherwise, it re
turns true. setcustomvalidity(message) ...
CredentialsContainer.get() - Web APIs
if no match is found the promise will resolve to null. this method first collects all credentials in the credentialscontainer that meet the necessary criteria (defined in the options argument). from the resulting set of credentials, it then selects the best one. depending on the options, it may display a dialog to the user and ask the user to make the selection. this method collects credentials by calling the "collectfromcredentialstore" method for each credential type allowed by the options argument. ...
...without effect. syntax var promise = credentialscontainer.get([options]) parameters options optional an object of type credentialrequestoptions that contains options for the request. the options include criteria that the credentials are required or allowed to have, and options for interacting with the user. it can contain the following properties: password: a boolean indicating that re
turned credential instances should include user (as opposed to federated) credentials. federated: a federatedcredentialrequestoptions object containing requirements for re
turned federated credentials. the available options are: providers: an array of domstring instances of identity providers to search for. protocols an array of domstring instances of federation protocols to search for. ...
...d: a federatedcredentialrequestoptions object containing requirements for re
turned federated credentials. the available options are: providers: an array of domstring instances of identity providers to search for. protocols an array of domstring instances of federation protocols to search for. publickey: an publickeycredentialrequestoptions object containing requirements for re
turned webauthn credentials. mediation: a string indicating whether the user will be required to log on for every visit to the website. valid values are "silent", "optional", or "required". unmediated: a boolean indicating the re
turned credential instance should not require user mediation. signal: an instance of abortsignal that can indicate that an ongoing get() operation should be halted. a...
...if a single credential cannot be unambigiously obtained, the promise will resolve to null. specifications specification status comment credential management level 1the definition of 'get()' in that specification. ...
CustomEvent - Web APIs
customevent() creates a customevent. properties customevent.detail read only any data passed when initializing the event. this interface inherits properties from its parent, event: event.bubbles read only a boolean indicating whether or not the event bubbles up through the dom. event.cancelbubble a historical alias to event.stoppropagation(). setting its value to true before re
turning from an event handler prevents propagation of the event. event.cancelable read only a boolean indicating whether the event is cancelable. event.composed read only a boolean indicating whether or not the event can bubble across the boundary between the shadow dom and the regular dom. event.currenttarget read only a reference to the currently registered target for the event. this is the...
...indicates whether or not the call to event.preventdefault() canceled the event. event.eventphase read only indicates which phase of the event flow is being processed. event.explicitoriginaltarget read only the explicit original target of the event (mozilla-specific.) event.originaltarget read only the original target of the event, before any retargetings. (mozilla-specific.) event.re
turnvalue a historical property introduced by internet explorer and eventually adopted into the dom specification in order to ensure existing sites continue to work. ideally, you should try to use event.preventdefault() and event.defaultprevented instead, but you can use re
turnvalue if you choose to do so. event.srcelement a non-standard alias (from old versions of microsoft internet explorer) fo...
...hrough the shadow root into the standard dom.) methods customevent.initcustomevent() initializes a customevent object. if the event has already being dispatched, this method does nothing. this interface inherits methods from its parent, event: event.createevent() creates a new event, which must then be initialized by calling its initevent() method. event.composedpath() re
turns the event’s path (objects on which listeners will be invoked). this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed. event.initevent() initializes the value of an event created. if the event has already been dispatched, this method does nothing. event.preventdefault() cancels the event (if it is cancelable). event.stopimmediatepro...
...t, prevent all other listeners from being called. this includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance). event.stoppropagation() stops the propagation of events further along in the dom. obsolete methods event.getpreventdefault() non-standard; use event.defaultprevented instead. (re
turns the value of event.defaultprevented.) event.preventbubble() obsolete since gecko 24 obsolete; use event.stoppropagation instead. (prevents the event from bubbling.) event.preventcapture() obsolete since gecko 24 obsolete; use event.stoppropagation instead. specifications specification status comment domthe definition of 'customevent' in that specification. ...
DOMException - Web APIs
the domexception interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web api. this is basically how error conditions are described in web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. ...
...as a result of calling a method or accessing a property of a web api. this is basically how error conditions are described in web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor domexception() re
turns a domexception object with a specified message and name. properties domexception.code read only re
turns a short that contains one of the error code constants, or 0 if none match. ...
... error names common error names are listed here. some apis define their own sets of names, so this is not necessarily a complete list. ...
... error names common error names are listed here. some apis define their own sets of names, so this is not necessarily a complete list. ...
DOMRect - Web APIs
for example, vreyeparameters.renderrect from the defunct webvr api specified the viewport of a canvas into which visuals for one eye of a head mounted display should be rendered. it inherits from its parent, domrectreadonly. ...
...mrect object. properties domrect inherits properties from its parent, domrectreadonly. the difference is that they are not read-only anymore. domrectreadonly.x the x coordinate of the domrect's origin. domrectreadonly.y the y coordinate of the domrect's origin. domrectreadonly.width the width of the domrect. domrectreadonly.height the height of the domrect. ...
...ly anymore. domrectreadonly.x the x coordinate of the domrect's origin. domrectreadonly.y the y coordinate of the domrect's origin. domrectreadonly.width the width of the domrect. domrectreadonly.height the height of the domrect. ...
... domrectreadonly.width the width of the domrect. domrectreadonly.height the height of the domrect. domrectreadonly.top re
turns the top coordinate value of the domrect (has the same value as y, or y + height if height is negative.) domrectreadonly.right re
turns the right coordinate value of the domrect (has the same value as x + width, or x if width is negative.) domrectreadonly.bottom re
turns the bottom coordinate value of the domrect (has the same value as y + height, or y if height is negative.) domrectreadonly.left re
turns the left coordinate value of the domrect (has the same value as x, or x + width if width is negative.) methods domrect inherits methods from its parent, domrectreadonly. static methods domrectreadonly.fromrect() creates a new domrect object with a ...
DOMTokenList - Web APIs
the domtokenlist interface represents a set of space-separated tokens. such a set is re
turned by element.classlist, htmllinkelement.rellist, htmlanchorelement.rellist, htmlareaelement.rellist, htmliframeelement.sandbox, or htmloutputelement.htmlfor. it is indexed beginning with 0 as with javascript array objects. domtokenlist is always case-sensitive. properties domtokenlist.length read only is an integer representing the number of objects stored in the object. domtokenlist.value a stringifier property that re
turns the value of the list as a domstring. ...
...nt.sandbox, or htmloutputelement.htmlfor. it is indexed beginning with 0 as with javascript array objects. domtokenlist is always case-sensitive. properties domtokenlist.length read only is an integer representing the number of objects stored in the object. domtokenlist.value a stringifier property that re
turns the value of the list as a domstring. methods domtokenlist.item(index) re
turns the item in the list by its index, or undefined if index is greater than or equal to the list's length. domtokenlist.contains(token) re
turns true if the list contains the given token, otherwise false. domtokenlist.add(token1[, token2[, ...tokenn]]) adds the specified token(s) to the list. domtokenlist.remove(token1[, token2[, ...tokenn]]) removes the specified token(s) from the list. domt...
...gth. domtokenlist.contains(token) re
turns true if the list contains the given token, otherwise false. domtokenlist.add(token1[, token2[, ...tokenn]]) adds the specified token(s) to the list. domtokenlist.remove(token1[, token2[, ...tokenn]]) removes the specified token(s) from the list. domtokenlist.replace(oldtoken, newtoken) replaces token with newtoken. domtokenlist.supports(token) re
turns true if a given token is in the associated attribute's supported tokens. domtokenlist.toggle(token [, force]) removes token from the list if it exists, or adds token to the list if it doesn't. re
turns a boolean indicating whether token is in the list after the operation. domtokenlist.entries() re
turns an iterator, allowing you to go through all key/value pairs contained in this object. domt...
...the list if it exists, or adds token to the list if it doesn't. re
turns a boolean indicating whether token is in the list after the operation. domtokenlist.entries() re
turns an iterator, allowing you to go through all key/value pairs contained in this object. domtokenlist.foreach(callback [, thisarg]) executes a provided callback function once per domtokenlist element. domtokenlist.keys() re
turns an iterator, allowing you to go through all keys of the key/value pairs contained in this object. domtokenlist.values() re
turns an iterator, allowing you to go through all values of the key/value pairs contained in this object. examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenl...
DataTransfer.mozTypesAt() - Web APIs
example this example shows the use of the moztypesat() method in a drop event handler. ...
... example this example shows the use of the moztypesat() method in a drop event handler. ...
... example this example shows the use of the moztypesat() method in a drop event handler. ...
... example this example shows the use of the moztypesat() method in a drop event handler. ...
DataTransfer.mozUserCancelled - Web APIs
example this example shows the use of the mozusercancelled property in the dragend event handler. ...
... example this example shows the use of the mozusercancelled property in the dragend event handler. ...
... example this example shows the use of the mozusercancelled property in the dragend event handler. ...
... example this example shows the use of the mozusercancelled property in the dragend event handler. ...
Document.getElementById() - Web APIs
the document method getelementbyid() re
turns an element object representing the element whose id property matches the specified string. since element ids are required to be unique if specified, they're a useful way to get access to a specific element quickly. if you need to get access to an element which doesn't have an id, you can use queryselector() to find the element using any selector. syntax var element = document.getelementbyid(id); parameters id the id of the element to locate. the id is case-sensitive string which is unique within the document; only one element may have any given id. re
turn value an element object describing the dom element object matching the specified id, or null if no matching element was found in the document. example html <html> <head> <title>ge...
... elements not in the document are not searched by getelementbyid(). when creating an element and assigning it an id, you have to insert the element into the document tree with node.insertb...
... var parentdom = document.getelementbyid('parent-id'); var test1 = parentdom.getelementbyid('test1'); //throw error //uncaught typeerror: parentdom.getelementbyid is not a function </script> </body> </html> if there is no element with the given id, this function re
turns null. note that the id parameter is case-sensitive, so document.getelementbyid("main") will re
turn null instead of the element <div id="main"> because "m" and "m" are different for the purposes of this method. elements not in the document are not searched by getelementbyid(). when creating an element and assigning it an id, you have to insert the element into the document tree with node.insertbefore() or a similar method before you can access it with getelementbyid(): var element = document.
...el will be null! non-html documents. the dom implementation must have information that says which attributes are of type id. attributes with the name "id" are not of type id unless so defined in the document's dtd. the id attribute is defined to be of id type in the common cases of xhtml, xul, and other. implementations that do not know whether attributes are of type id or not are expected to re
turn null. specification specification status comment document object model (dom) level 1 specificationthe definition of 'getelementbyid' in that specification. obsolete initial definition for the interface document object model (dom) level 2 core specificationthe definition of 'getelementbyid' in that specification. obsolete supersede dom 1 ...
Document.lastModified - Web APIs
let olastmodif = new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time. ...
... let olastmodif = new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time. ...
... specifications specification status comment html living st...
...]*).*$)|^.*$/, "$1")), nlastmodif = date.parse(document.lastmodified); if (isnan(nlastvisit) || nlastmodif > nlastvisit) { document.cookie = "last_modif=" + date.now() + "; expires=fri, 31 dec 9999 23:59:59 gmt; path=" + location.pathname; if (isfinite(nlastvisit)) { alert("this page has been changed!"); } } note: webkit re
turns the time string in utc; gecko and internet explorer re
turn a time in the local timezone. (see: bug 4363 – document.lastmodified re
turns date in utc time, but should re
turn it in local time) if you want to know whether an external page has changed, please read this paragraph about the xmlhttprequest() api. specifications specification status comment html living standardthe definition of 'document.lastmodified' in that spec...
Document.origin - Web APIs
use self.origin instead. the document.origin read-only property re
turns the document's origin. in most cases, this property is equivalent to document.defaultview.location.origin. ...
... use self.origin instead. the document.origin read-only property re
turns the document's origin. in most cases, this property is equivalent to document.defaultview.location.origin. ...
... use self.origin instead. the document.origin read-only property re
turns the document's origin. in most cases, this property is equivalent to document.defaultview.location.origin. ...
...nly property re
turns the document's origin. in most cases, this property is equivalent to document.defaultview.location.origin. ...
DocumentFragment - Web APIs
ct x="266" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="346" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">documentfragment</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor documentfragment() creates and re
turns a new documentfragment object. properties this interface has no specific properties, but inherits those of its parent, node, and implements those of the parentnode interface. parentnode.children read only re
turns a live htmlcollection containing all objects of type element that are children of the documentfragment object. parentnode.firstelementchild read only re
turns the element th...
...node, and implements those of the parentnode interface. parentnode.children read only re
turns a live htmlcollection containing all objects of type element that are children of the documentfragment object. parentnode.firstelementchild read only re
turns the element that is the first child of the documentfragment object, or null if there is none. parentnode.lastelementchild read only re
turns the element that is the last child of the documentfragment object, or null if there is none. parentnode.childelementcount read only re
turns an unsigned long giving the amount of children that the documentfragment has. ...
...read only re
turns the element that is the last child of the documentfragment object, or null if there is none. parentnode.childelementcount read only re
turns an unsigned long giving the amount of children that the documentfragment has. methods this interface inherits the methods of its parent, node, and implements those of the parentnode interface. documentfragment.queryselector() re
turns the first element node within the documentfragment, in document order, that matches the specified selectors. documentfragment.queryselectorall() re
turns a nodelist of all the element nodes within the documentfragment that match the specified selectors. ...
...functionally equivalent to document.getelementbyid(). ...
Element.getAttribute() - Web APIs
syntax let attribute = element.getattribute(attributename); where attribute is a string containing the value of attributename. attributename is the name of the attribute whose value you want to get. ...
...); alert(align); // shows the value of align for the element with id="div1" description lower casing when called on an html element in a dom flagged as an html document, getattribute() lower-cases its argument before proceeding. non-existing attributes essentially all web browsers (firefox, internet explorer, recent versions of opera, safari, konqueror, and icab, as a non-exhaustive list) re
turn null when the specified attribute does not exist on the specified element; this is what the current dom specification draft specifies. the old dom 3 core specification, on the other hand, says that the correct re
turn value in this case is actually the empty string, and some dom implementations implement this behavior. the implementation of getattribute() in xul (gecko) actually follows the dom 3 ...
...attribute does not exist on the specified element; this is what the current dom specification draft specifies. the old dom 3 core specification, on the other hand, says that the correct re
turn value in this case is actually the empty string, and some dom implementations implement this behavior. the implementation of getattribute() in xul (gecko) actually follows the dom 3 core specification and re
turns an empty string. consequently, you should use element.hasattribute() to check for an attribute's existence prior to calling getattribute() if it is possible that the requested attribute does not exist on the specified element. retrieving nonce values for security reasons, csp nonces from non-script sources, such as css selectors, and .getattribute("nonce") calls are hidden. let nonce = scri...
..., you should use element.hasattribute() to check for an attribute's existence prior to calling getattribute() if it is possible that the requested attribute does not exist on the specified element. retrieving nonce values for security reasons, csp nonces from non-script sources, such as css selectors, and .getattribute("nonce") calls are hidden. let nonce = script.getattribute('nonce'); // re
turns empty string instead of retrieving the nonce from the content attribute, use the nonce property: let nonce = script.nonce; specifications specification status comment domthe definition of 'getattribute()' in that specification. living standard ...
Element.querySelector() - Web APIs
the queryselector() method of the element interface re
turns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. syntax element = baseelement.queryselector(selectors); parameters selectors a group of selectors to match the descendant elements of the element baseelement against; this must be valid css syntax, or a syntaxerror exception will occur. the first element found which matches this group of selectors is re
turned. re
turn value the first descendant element of baseelement which matches the specified group of selectors. the entire hierarchy of elements is considered when matching, including those outside the set of elements including baseelement and its descendants; in other words, selectors is first applied ...
...elements is considered when matching, including those outside the set of elements including baseelement and its descendants; in other words, selectors is first applied to the whole document, not the baseelement, to generate an initial list of potential elements. the resulting elements are then examined to see if they are descendants of baseelement. ...
...of elements including baseelement and its descendants; in other words, selectors is first applied to the whole document, not the baseelement, to generate an initial list of potential elements. the resulting elements are then examined to see if they are descendants of baseelement. the first match of those remaining elements is re
turned by the queryselector() method. if no matches are found, the re
turned value is null. ...
...nts is re
turned by the queryselector() method. if no matches are found, the re
turned value is null. exceptions syntaxerror the specified selectors are invalid. examples let's consider a few examples. find a specific element with specific values of an attribute in this first example, the first <style> element which either has no type or has type "text/css" in the html document body is re
turned: var el = document.body.queryselector("style[type='text/css'], style:not([type])"); the entire hierarchy counts this example demonstrates that the hierarchy of the entire document is considered when applying selectors, so that levels outside the specified baseelement are still considered when locating matches. html <div> <h5>original content</h5> <p> inside paragraph <span>ins...
FeaturePolicy.allowedFeatures() - Web APIs
example the followin example logs all the allowed directives for the current document. ...
... example the followin example logs all the allowed directives for the current document. ...
... example the followin example logs all the allowed directives for the current document. ...
... example the followin example logs all the allowed directives for the current document. ...
FetchEvent.respondWith() - Web APIs
the respondwith() method of fetchevent prevents the browser's default fetch handling, and allows you to provide a promise for a response yourself. in most cases you can provide any response that the receiver understands. for example, if an <img> initiates the request, the response body needs to be image data. for security reasons, there are a few global rules: you can only re
turn response objects of type "opaque" if the fetchevent.request object's mode is "no-cors". this prevents the leaking of private data. you can only re
turn response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". you cannot re
turn response objects of type "cors" if the fetchevent.request object's mode is "same-origin". specifying the final url of a resource from firefox 59 o...
...handles redirects for navigations ends up using the request url for the resulting window.location. this means sites can still provide an "alternate" view of a web page when offline without changing the user-visible url. syntax fetchevent.respondwith( // promise that resolves to a response. ); parameters a response or a promise that resolves to a response. otherwise, a network error is re
turned to fetch. re
turn value undefined. exceptions exception notes networkerror a network error is triggered on certain combinations of fetchevent.request.mode and response.type values, as hinted at in the "global rules" listed above. invalidstateerror the event has not been dispatched or respondwithwith() has already been invoked. examples this fe...
...value undefined. exceptions exception notes networkerror a network error is triggered on certain combinations of fetchevent.request.mode and response.type values, as hinted at in the "global rules" listed above. invalidstateerror the event has not been dispatched or respondwithwith() has already been invoked. ...
... has already been invoked. examples this fetch event tries to re
turn 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); // re
turn it if we found one. if (cachedresponse) re
turn cachedresponse; // if we didn't find a match in the cache, use the network. re
turn fetch(event.request); }()); }); note: caches.match() is a convenience method. equivalent functionality is to call cache.match() on each cache (in the order re
turned by caches.keys()) until a response is re
turned. specifications specification...
FetchEvent - Web APIs
navigation. fetchevent.request read only the request the browser intends to make. methods inherits methods from its parent, extendableevent. fetchevent.respondwith() prevent the browser's default fetch handling, and provide (a promise for) a response yourself. extendableevent.waituntil() extends the lifetime of the event. used to notify the browser of tasks that extend beyond the re
turning 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 re
turn 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-...
... examples this fetch event uses the browser default for non-get requests. for get requests it tries to re
turn 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') re
turn; // prevent the default, and handle the request ourselves. event.respondwith(async function() { // try to get the response from a cache. ...
... // for non-get requests. if (event.request.method != 'get') re
turn; // 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'); const cachedresponse = await cache.match(event.request); if (cachedresponse) { // if we found a match in the cache, re
turn it, but also // update the entry in the cache in the background. event.waituntil(cache.add(event.request)); re
turn cachedresponse; } // if we didn't find a match in the cache, use the network. ...
... = await caches.open('dynamic-v1'); const cachedresponse = await cache.match(event.request); if (cachedresponse) { // if we found a match in the cache, re
turn it, but also // update the entry in the cache in the background. event.waituntil(cache.add(event.request)); re
turn cachedresponse; } // if we didn't find a match in the cache, use the network. re
turn fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'fetchevent()' in that specification. working draft initial definition. ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
absolute paths may not be able to be used, for security reasons. ...
...esponding to a directory contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getdirectory([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the method is called, describing which directory entry to re
turn. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemdirectoryen...
...l in web contexts. successcallback optional a method to be called once the filesystemdirectoryentry has been created. the method receives a single parameter: the filesystemdirectoryentry object representing the directory in question. errorcallback optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. re
turn value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the fileerror.code specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist. fileerror.path_exists_err the create a...
...ctionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in
turn, creates a new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getdirectory()' in that specific...
FileSystemDirectoryEntry.getFile() - Web APIs
options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. ...
... filesystemfileentry object corresponding to a file contained somewhere within the directory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getfile([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring specifying the path, relative to the directory on which the method is called, describing which file's entry to re
turn. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemfileentry has been created. the method receives a single parameter: the file...
...ently not useful in web contexts. successcallback optional a method to be called once the filesystemfileentry has been created. the method receives a single parameter: the filesystemfileentry object representing the file in question. errorcallback optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. re
turn value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the {domxref("fileerror.code")}} specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist. fileerror.path_exists_err the...
...ctionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in
turn, creates a new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getfile()' in that specification...
FileSystemDirectoryReader.readEntries() - Web APIs
les, or filesystemdirectoryentry objects, which represent directories. if there are no files left, or you've already called readentries() on this filesystemdirectoryreader, the array is empty. errorcallback optional a callback function which is called if an error occurs while reading from the directory. it receives one input parameter: a fileerror object describing the error which occurred. re
turn value undefined. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing. html content the html establishes the drop zone itself, which is a <div> element with the id "dropzone", and an unordered list element with the id "listing". <p>drag files and/or directories to ...
... javascript content first, let's look at the recursive scanfiles() function. this function takes as input a filesystementry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). note that to read all files in a directory, readentries needs to be called repeatedly until it re
turns an empty array. in chromium-based browsers, the following example will only re
turn a max of 100 entries. let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryrea...
...e a filesystemdirectoryreader to handle fetching the directory's contents. that's done by calling the item's createreader() method. then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in
turn, passed into a recursive call to scanfiles() to process them. any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth. then come the event handlers. first, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the dr...
...in order to obtain all of the instances, readentries() must be called multiple times. ...
GeolocationCoordinates - Web APIs
the geolocationcoordinates interface represents the position and altitude of the device on earth, as well as the accuracy with which these properties are calculated. properties the geolocationcoordinates interface doesn't inherit any properties. geolocationcoordinates.latitude read only secure context re
turns a double representing the position's latitude in decimal degrees. geolocationcoordinates.longitude read only secure context re
turns a double representing the position's longitude in decimal degrees. geolocationcoordinates.altitude read only secure context re
turns a double representing the position's altitude in meters, relative to sea level. this value can be null if the implementation cannot provide the data. geolocationcoordinates.accuracy read only secure cont...
...dinates.longitude read only secure context re
turns a double representing the position's longitude in decimal degrees. geolocationcoordinates.altitude read only secure context re
turns a double representing the position's altitude in meters, relative to sea level. this value can be null if the implementation cannot provide the data. geolocationcoordinates.accuracy read only secure context re
turns a double representing the accuracy of the latitude and longitude properties, expressed in meters. geolocationcoordinates.altitudeaccuracy read only secure context re
turns a double representing the accuracy of the altitude expressed in meters. this value can be null. ...
...this value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). if speed is 0, heading is nan. ...
... this value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). if speed is 0, heading is nan. if the device is unable to provide heading information, this value is null. geolocationcoordinates.speed read only secure context re
turns a double representing the velocity of the device in meters per second. this value can be null. methods the geolocationcoordinates interface neither implements, nor inherits any method. specifications specification status comment geolocation apithe definition of 'geolocationcoordinates' in that specification. recommendation initial specification. ...
HTMLCanvasElement.toDataURL() - Web APIs
chrome also supports the image/webp type. syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format. the default format type is image/png. ...
... chrome also supports the image/webp type. syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format. the default format type is image/png. ...
... chrome also supports the image/webp type. syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format. the default format type is image/png. ...
...pe optional a domstring indicating the image format. the default format type is image/png. encoderoptions optional a number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. if this argument is anything else, the default value for image quality is used. the default value is 0.92. other arguments are ignored. re
turn value a domstring containing the requested data uri. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. examples given this <canvas> element: <canvas id="canvas" width="5" height="5"></canvas> you can get a data-url of the canvas with the ...
HTMLCollection - Web APIs
rs methods and properties for selecting from the list. note: this interface is called htmlcollection for historical reasons (before the modern dom, collections implementing this interface could only have html elements as their items). an htmlcollection in the html dom is live; it is automatically updated when the underlying document is changed. ...
...led htmlcollection for historical reasons (before the modern dom, collections implementing this interface could only have html elements as their items). an htmlcollection in the html dom is live; it is automatically updated when the underlying document is changed. properties htmlcollection.length read only re
turns the number of items in the collection. methods htmlcollection.item() re
turns the specific node at the given zero-based index into the list. re
turns null if the index is out of range. an alternative to accessing collection[i] (which instead re
turns undefined when i is out-of-bounds). this is mostly useful for non-javascript dom implementations. htmlcollection.nameditem() re
turns the specific node whose id or, as a fallback, name matches the string specified by name. m...
...this is mostly useful for non-javascript dom implementations. usage in javascript htmlcollection also exposes its members directly as properties by both name and index. html ids may contain : and . ...
...this is mostly useful for non-javascript dom implementations. usage in javascript htmlcollection also exposes its members directly as properties by both name and index. html ids may contain : and . as valid characters, which would necessitate using bracket notation for property access. ...
HTMLElement.offsetParent - Web APIs
the element is <body> or <html>. offsetparent is useful because offsettop and offsetleft are relative to its padding edge. ...
... the element is <body> or <html>. offsetparent is useful because offsettop and offsetleft are relative to its padding edge. ...
... the element is <body> or <html>. offsetparent is useful because offsettop and offsetleft are relative to its padding edge. ...
... the element is <body> or <html>. offsetparent is useful because offsettop and offsetleft are relative to its padding edge. syntax parentobj = element.offsetparent; parentobj is an object reference to the element in which the current element is offset. ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
this event loop may be either the browser's main event loop or the event loop driving a web worker. this lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. ...
...or. and they are similar; both are made up of javascript code which gets placed on a queue and run at an appropriate time. however, whereas the event loop runs only the tasks present on the queue when the iteration began, one after another, it handles the microtask queue very differently. there are two key differences. first, each time a task exits, the event loop checks to see if the task is re
turning control to other javascript code. if not, it runs all of the microtasks in the microtask queue. the microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. second, if a microtask adds more microtasks to the queue by calling queuemicrotask(), those newly-added microtasks execute before the next task is run. that's...
...oids. simply pass the javascript function to call while the context is handling microtasks into the queuemicrotask() method, which is exposed on the global context as defined by either the window or worker interface, depending on the current execution context. queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not re
turn a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly useful. generally, it's about capturing or checking results, or performing cleanup, after the main body of a javascript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed. when is that useful? the main reason to use ...
...l doesn't fire until the entire program exits, since that's when the task exits and there's nothing else on the execution stack. ...
Headers.get() - Web APIs
the get() method of the headers interface re
turns a byte string of all the values of a header within a headers object with a given name. if the requested header doesn't exist in the headers object, it re
turns null. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.get(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. the name is case-insensitive. re
turns a bytestring sequence representing the values of the retrieved header or null if this header is not set. example creating an empty headers object is simple: ...
...etrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. the name is case-insensitive. re
turns a bytestring sequence representing the values of the retrieved header or null if this header is not set. ...
...representing the values of the retrieved header or null if this header is not set. ...
...ng get(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // re
turns "image/jpeg" if the header has multiple values associated with it, the byte string will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // re
turns "deflate,gzip" note: headers.getall used to have this functionality, with headers.get re
turning only the first value added to the headers object. the latest spec has removed getall(), and updated get() to re
turn all values. specifications specification status comment fetchthe definition of 'get()' in that specification. living standard ...
IDBCursor - Web APIs
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 property. ...
...s 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 property. idbcursor.source read only re
turns the idbobjectstore or idbindex that the cursor is iterating. this function never re
turns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active. idbcursor.direction read only re
turns the direction of traversal of the cursor. see constants for possible values. idbcursor.key read only re
turns the key for the record at the cursor's position. if the cursor is outside its range, this is set to undefin...
...has iterated past its end, or its transaction is not active. idbcursor.direction read only re
turns the direction of traversal of the cursor. see constants for possible values. idbcursor.key read only re
turns the key for the record at the cursor's position. if the cursor is outside its range, this is set to undefined. the cursor's key can be any data type. idbcursor.primarykey read only re
turns the cursor's current effective primary key. if the cursor is currently being iterated or has iterated outside its range, this is set to undefined. the cursor's primary key can be any data type. idbcursor.request read only re
turns the idbrequest that was used to obtain the cursor. methods idbcursor.advance() sets the number of times a cursor should move its position forward. idbcursor.c...
...o obtain the cursor. methods idbcursor.advance() sets the number of times a cursor should move its position forward. idbcursor.continue() advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. idbcursor.continueprimarykey() sets the cursor to the given index key and primary key given as arguments. idbcursor.delete() re
turns an idbrequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. this can be used to delete specific records. idbcursor.update() re
turns an idbrequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store. this can be used to update specific records. constants th...
IDBFactory.deleteDatabase() - Web APIs
when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
... when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
... when deletedatabase() is called, any other open connections to this particular database will get a versionchange event. note: this feature is available in web workers. ...
...es not throw an exception, in contrast to idbdatabase.deleteobjectstore(), which does throw an exception if the named object store does not exist. optionsnon-standard in gecko, since version 26, you can include a non-standard optional storage parameter that specifies whether you want to delete a permanent (the default value) indexeddb, or an indexeddb in temporary storage (aka shared pool.) re
turn value a idbopendbrequest on which subsequent events related to this request are fired. example var dbdeleterequest = window.indexeddb.deletedatabase("todolist"); dbdeleterequest.onerror = function(event) { console.log("error deleting database."); }; dbdeleterequest.onsuccess = function(event) { console.log("database deleted successfully"); console.log(event.result); // should be ...
IDBFactory.open() - Web APIs
may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
... may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
... may trigger upgradeneeded, blocked or versionchange events. note: this feature is available in web workers. ...
...er you want to use persistent or temporary storage. warning: the storage attribute is deprecated and will soon be removed from gecko. you should use storagemanager.persist() to get persistent storage instead. note: you can find out more information on the different available storage types, and how firefox handles client-side data storage, at browser storage limits and eviction criteria. re
turn value a idbopendbrequest object on which subsequent events related to this request are fired. exceptions this method may raise a domexception of the following types: exception description typeerror the value of version is zero or a negative number or not a number. example example of calling open with the current specification's version parameter: var reque...
IDBIndex.openKeyCursor() - Web APIs
the method sets the position of the cursor to the appropriate key, based on the specified direction. if the key range is not specified or is null, then the range includes all the keys. a success event is always fired on the result object. if at least one key matches the key range, then the result property of the event is set to the new idbcursor object; the key property of the cursor object is set to the found key and the primarykey property is set to the the corresponding primary key of the found record. ...
...t. if at least one key matches the key range, then the result property of the event is set to the new idbcursor object; the key property of the cursor object is set to the found key and the primarykey property is set to the the corresponding primary key of the found record. if no keys match the key range, then then the result property of the event is set to null. note: cursors re
turned by openkeycursor() do not make the referenced value available as idbindex.opencursor does. this makes obtaining a list of keys much more efficient. note: this feature is available in web workers. syntax var request = myindex.openkeycursor(); var request = myindex.openkeycursor(range); var request = myindex.openkeycursor(range, direction); parameters range optional a key or idbkeyrange ...
...x.openkeycursor(); var request = myindex.openkeycursor(range); var request = myindex.openkeycursor(range, direction); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or...
... invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a key cursor on the index using openkeycursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.openkeycursor except that the re
turned records are sorted based on the index, not the primary key. finally, we iterate through each record in the index, and insert the last name and the corresponding primary key of the referenced record into an html table. function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('conta...
IDBKeyRange.includes() - Web APIs
the includes() method of the idbkeyrange interface re
turns a boolean indicating whether a specified key is inside the key range. note: this feature is available in web workers. syntax var isincluded = mykeyrange.includes(key) parameters key the key you want to check for in your key range. this can be any type. re
turn value a boolean. exceptions this method may raise a domexception of the following type: attribute description dataerror the supplied key was not a valid key. ...
...for browsers that do not support it, the following polyfill can be used. ...
...an be any type. re
turn value a boolean. exceptions this method may raise a domexception of the following type: attribute description dataerror the supplied key was not a valid key. example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // re
turns true var myresult = keyrangevalue.includes('w'); // re
turns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfill can be used. ...
...('w'); // re
turns false polyfill the includes() method was added in the second edition of the indexed db specification. for browsers that do not support it, the following polyfill can be used. idbkeyrange.prototype.includes = idbkeyrange.prototype.includes || function(key) { var r = this, c; if (r.lower !== undefined) { c = indexeddb.cmp(key, r.lower); if (r.loweropen && c <= 0) re
turn false; if (!r.loweropen && c < 0) re
turn false; } if (r.upper !== undefined) { c = indexeddb.cmp(key, r.upper); if (r.upperopen && c >= 0) re
turn false; if (!r.upperopen && c > 0) re
turn false; } re
turn true; }; specification specification status comment indexed database api draftthe definition of 'includes()' in that specification. recommenda...
IDBRequest.error - Web APIs
constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. ...
... constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. ...
... constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. ...
...full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the do-do list with the specified title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsucc...
IDBTransaction - Web APIs
storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction. properties idbtransaction.db read only the database connection with which this transaction is associated. idbtransaction.error read only re
turns a domexception indicating the type of error that occured when there is an unsuccessful transaction. this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with theidbtransaction.abort() function. idbtransaction.mode read only the mode for isolating access to data in the object stores that are in the scope of the transaction. the defaul...
...e is an unsuccessful transaction. this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with theidbtransaction.abort() function. idbtransaction.mode read only the mode for isolating access to data in the object stores that are in the scope of the transaction. the default value is readonly. ...
... idbtransaction.commit() for an active transaction, commits the transaction. note that this doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. ...
...quests to be dispatched. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when an indexeddb transaction is aborted. also available via the onabort property. complete fired when a transaction successfully completes. also available via the oncomplete property. error fired when a request re
turns an error and the event bubbles up to the transaction object. also available via the onerror property. mode constants these constants are no longer available — they were removed in gecko 25. you should use the string constants directly instead. (bug 888598) transactions can have one of three modes: constant value description read_only "readonly" ...
ImageCapture.grabFrame() - Web APIs
for simplicy it does not show how to instantiate the imagecapture object. ...
...for simplicy it does not show how to instantiate the imagecapture object. ...
...for simplicy it does not show how to instantiate the imagecapture object. ...
...for simplicy it does not show how to instantiate the imagecapture object. ...
InputEvent - Web APIs
ize="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">inputevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor inputevent() creates an inputevent object. properties this interface inherits properties from its parents, uievent and event. ...
...inter-events: all;} constructor inputevent() creates an inputevent object. properties this interface inherits properties from its parents, uievent and event. inputevent.dataread only re
turns a domstring with the inserted characters. this may be an empty string if the change doesn't insert text (such as when deleting characters, for example). inputevent.datatransferread only re
turns a datatransfer object containing information about richtext or plaintext data being added to or removed from editable content. ...
...t. inputevent.dataread only re
turns a domstring with the inserted characters. this may be an empty string if the change doesn't insert text (such as when deleting characters, for example). inputevent.datatransferread only re
turns a datatransfer object containing information about richtext or plaintext data being added to or removed from editable content. inputevent.inputtyperead only re
turns the type of change for editable content such as, for example, inserting, deleting, or formatting text. see the property page for a complete list of input types. inputevent.iscomposingread only re
turns a boolean value indicating if the event is fired after compositionstart and before compositionend. methods this interface inherits methods from its parents, uievent and event. inputevent.g...
... for editable content such as, for example, inserting, deleting, or formatting text. see the property page for a complete list of input types. inputevent.iscomposingread only re
turns a boolean value indicating if the event is fired after compositionstart and before compositionend. methods this interface inherits methods from its parents, uievent and event. inputevent.gettargetranges() re
turns an array of static ranges that will be affected by a change to the dom if the input event is not canceled. specifications specification status comment input events level 2the definition of 'inputevent' in that specification. working draft ui eventsthe definition of 'inputevent' in that specification. working draft initial definition. ...
MediaDeviceInfo.groupId - Web APIs
two devices have the same group identifier if they belong to the same physical device; for example, a monitor with both a built-in camera and microphone. syntax var groupid = mediadeviceinfo.groupid; value a domstring which uniquely identifies the group of related devices to which this device belongs. specifications specification status comment media capture and streamsthe definition of 'groupid' in that specification. candidate recommendation initial definition. examples in this example, we assemble a list of the devices which are part of the same group as a given device. ...
...purposes, or to make it easy for the user to choose to use the built-in camera and microphone on the same display at the same time. const getdevicegroup = maindevinfo => { let devlist = []; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if (device.groupid === maindevinfo.groupid) { devlist.push(device); } }); }); re
turn devlist; }; the getdevicegroup() function takes as input the mediadeviceinfo object describing the device for which a group list is to be built. the function starts by initializing the result array, devlist, to be an empty array. then navigator.mediadevices.enumeratedevices() is called to get the list of all media devices. once the promise resolves, we walk the list using foreach(). for each d...
...to be an empty array. then navigator.mediadevices.enumeratedevices() is called to get the list of all media devices. once the promise resolves, we walk the list using foreach(). for each device, if its groupid matches the main device's groupid, we push the mediadeviceinfo object onto the list. finally, the list, which now contains a mediadeviceinfo object for each device in the same group, is re
turned to the caller. this could be altered easily to either leave out the passed-in device from the re
turned list, or to place it at the top of the list, by comparing the two objects' deviceid values, only pushing the device onto the result list if it doesn't match. this version of the example puts the passed-in device at the top of the result list, then adds any other members of the group that are...
...list, then adds any other members of the group that are found: const getdevicegroup = maindevinfo => { let devlist = [maindevinfo]; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if ((device.groupid === maindevinfo.groupid) && (device.deviceid !== maindevinfo.deviceid)) { devlist.push(device); } }); }); re
turn devlist; }; ...
MediaDevices.getDisplayMedia() - Web APIs
w) as a mediastream. the resulting stream can then be recorded using the mediastream recording api or transmitted as part of a webrtc session. see using the screen capture api for more details and an example. syntax var promise = navigator.mediadevices.getdisplaymedia(constraints); parameters constraints optional an optional mediastreamconstraints object specifying requirements for the re
turned mediastream. since getdisplaymedia() requires a video track, the re
turned stream will have one even if no video track is expressly requested by the constraints object. re
turn value a promise that resolves to a mediastream containing a video track whose contents come from a user-selected screen area, as well as an optional audio track. note: browser support for audio tracks varies, both in ...
...taining a video track whose contents come from a user-selected screen area, as well as an optional audio track. note: browser support for audio tracks varies, both in terms of whether or not they're supported at all by the media recorder and in terms of the which audio source or sourcoes are supported. check the compatibility table for details for each browser. exceptions rejections of the re
turned promise are made by passing a domexception error object to the promise's failure handler. possible errors are: aborterror an error or failure that doesn't match any of the other exceptions below occurred. invalidstateerror the call to getdisplaymedia() was not made from code running due to a user action, such as an event handler. another potential cause for this event: the document in who...
...error or lockout occurred, preventing the sharing of the selected source. overconstrainederror after creating the stream, applying the specified constraints fails because no compatible stream could be generated. typeerror the specified constraints include constraints which are not permitted when calling getdisplaymedia(). these unsupported constraints are advanced and any constraints which in
turn have a member named min or exact. usage notes privacy and security because getdisplaymedia() could be used in nefarious ways, it can be a source of significant privacy and security concerns. for that reason, the specification details measures browsers are required to take in order to fully support getdisplaymedia(). the specified constraints can't be used to limit the options available to ...
...fied in the form of a mediastreamconstraints 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); } re
turn 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 re
turned 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 ...
MediaKeySession - Web APIs
this promise can only be fulfilled and is never rejected. closing a session means that licenses and keys associated with it are no longer valid for decrypting media data. mediakeysession.expiration read only the time after which the keys in the current session can no longer be used to decrypt media data, or nan if no such time exists. ...
...for the current media object and its associated keys or licenses. event handlers mediakeysession.onkeystatuseschange sets the eventhandler called when there has been a change in the keys in a session or their statuses. mediakeysession.onmessage sets the eventhandler called when the content decryption module has generated a message for the session. ...
...or their statuses. mediakeysession.onmessage sets the eventhandler called when the content decryption module has generated a message for the session. methods mediakeysession.close() re
turns a promise after notifying the current media session is no longer needed and that the cdm should release any resources associated with this object and close it. mediakeysession.generaterequest() re
turns a promise after generating a media request based on initialization data. mediakeysession.load() re
turns a promise that resolves to a boolean value after loading data for a specified session object. ...
...t media session is no longer needed and that the cdm should release any resources associated with this object and close it. mediakeysession.generaterequest() re
turns a promise after generating a media request based on initialization data. mediakeysession.load() re
turns a promise that resolves to a boolean value after loading data for a specified session object. mediakeysession.remove() re
turns a promise after removing any session data associated with the current object. mediakeysession.update() re
turns a promise after loading messages and licenses to the cdm. examples // tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeysession' in that specification. recommendation initial definition. ...
MediaRecorder - Web APIs
media. it is created using the mediarecorder() constructor. constructor mediarecorder() creates a new mediarecorder object, given a mediastream to record. options are available to do things like set the container's mime type (such as "video/webm" or "video/mp4") and the bit rates of the audio and video tracks or a single overall bit rate. properties mediarecorder.mimetype read only re
turns the mime type that was selected as the recording container for the mediarecorder object when it was created. mediarecorder.state read only re
turns the current state of the mediarecorder object (inactive, recording, or paused.) mediarecorder.stream read only re
turns the stream that was passed into the constructor when the mediarecorder was created. mediarecorder.ignoremutedmedia indicates...
...this may differ from the bit rate specified in the constructor (if it was provided). methods mediarecorder.pause() pauses the recording of media. ...
...this may differ from the bit rate specified in the constructor (if it was provided). ...
...s. if this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk. mediarecorder.stop() stops recording, at which point a dataavailable event containing the final blob of saved data is fired. no more recording occurs. static methods mediarecorder.istypesupported() a static method which re
turns a boolean value indicating if the given mime media type is supported by the current user agent. event handlers mediarecorder.ondataavailable called to handle the dataavailable event, which is periodically triggered each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if timeslice wasn't specified). the event, of type blobevent, contains...
MimeTypeArray - Web APIs
example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. ...
... example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. ...
... example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. ...
... example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. ...
MutationRecord - Web APIs
a mutationrecord represents an individual dom mutation. it is the object that is passed to mutationobserver's callback. properties property type description mutationrecord.type string re
turns "attributes" if the mutation was an attribute mutation, "characterdata" if it was a mutation to a characterdata node, and "childlist" if it was a mutation to the tree of nodes. mutationrecord.target node re
turns the node the mutation affected, depending on the mutationrecord.type. for attributes, it is the element whose attribute changed. for characterdata, it is the characterdata node. for childlist, it is the node whose children changed. mutationrecord.addednodes nodelist re
turn the nodes added. will be an empty nodelist ...
...affected, depending on the mutationrecord.type. for attributes, it is the element whose attribute changed. for characterdata, it is the characterdata node. for childlist, it is the node whose children changed. mutationrecord.addednodes nodelist re
turn the nodes added. will be an empty nodelist if no nodes were added. mutationrecord.removednodes nodelist re
turn the nodes removed. will be an empty nodelist if no nodes were removed. ...
...ata, it is the characterdata node. for childlist, it is the node whose children changed. mutationrecord.addednodes nodelist re
turn the nodes added. will be an empty nodelist if no nodes were added. mutationrecord.removednodes nodelist re
turn the nodes removed. will be an empty nodelist if no nodes were removed. mutationrecord.previoussibling node re
turn the previous sibling of the added or removed nodes, or null. mutationrecord.nextsibling node re
turn the next sibling of the added or removed nodes, or null. mutationrecord.attributename string re
turns the local name of the changed attribute, or null. mutationrecord.attributenamespace string re
turns the namespace of the changed attribute, or null. ...
... for attributes, it is the value of the changed attribute before the change. for characterdata, it is the data of the changed node before the change. for childlist, it is null. ...
NamedNodeMap - Web APIs
odemap object is live and will thus be auto-updated if changes are made to its contents internally or elsewhere. although called namednodemap, this interface doesn't deal with node objects but with attr objects, which were originally a specialized class of node, and still are in some implementations. properties this interface doesn't inherit any property. ...
...ed namednodemap, this interface doesn't deal with node objects but with attr objects, which were originally a specialized class of node, and still are in some implementations. properties this interface doesn't inherit any property. namednodemap.length read only re
turns the amount of objects in the map. methods this interface doesn't inherit any method. namednodemap.getnameditem() re
turns a attr, corresponding to the given name. ...
... namednodemap.setnameditemns() replaces, or adds, the attr identified in the map by the given namespace and related local name. ...
... namednodemap.setnameditemns() replaces, or adds, the attr identified in the map by the given namespace and related local name. namednodemap.removenameditemns() removes the attr identified by the given namespace and related local name. ...
Navigator.productSub - Web APIs
specifications specification status comment html living standardthe definition of 'navigatorid: productsub' in that specification. ...
... specifications specification status comment html living standardthe definition of 'navigatorid: productsub' in that specification. ...
... specifications specification status comment html living standardthe definition of 'navigatorid: productsub' in that specification. ...
...r. syntax prodsub = window.navigator.productsub prodsub is a string. example <script> function prodsub() { var dt = document.getelementbyid("d").childnodes[0]; dt.data = window.navigator.productsub; } </script> <button onclick="prodsub();">productsub</button> // re
turns: 20010725 notes on ie, this property re
turns undefined. on apple safari and google chrome this property always re
turns 20030107. specifications specification status comment html living standardthe definition of 'navigatorid: productsub' in that specification. living standard initial definition ...
Navigator.requestMediaKeySystemAccess() - Web APIs
the navigator.requestmediakeysystemaccess() method re
turns a promise which delivers a mediakeysystemaccess object that can be used to access a particular media key system, which can in
turn be used to create keys for decrypting a media stream. this method is part of the encrypted media extensions api, which brings support for encrypted media and drm-protected video to the web. this method may have user-visible effects such as asking for permission to access one or more system resources. consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. ...
...ted video to the web. this method may have user-visible effects such as asking for permission to access one or more system resources. consider that when deciding when to call requestmediakeysystemaccess(); you don't want those requests to happen at inconvenient times. as a general rule, this function should be called only when it's about time to create and use a mediakeys object by calling the re
turned mediakeysystemaccess object's createmediakeys() method. syntax promise = navigator.requestmediakeysystemaccess(keysystem, supportedconfigurations); parameters keysystem a domstring identifying the key system. for example com.example.somesystem or org.w3.clearkey. supportedconfigurations a non-empty array of mediakeysystemconfiguration objects. the first element with a satisfiable co...
...'s createmediakeys() method. syntax promise = navigator.requestmediakeysystemaccess(keysystem, supportedconfigurations); parameters keysystem a domstring identifying the key system. for example com.example.somesystem or org.w3.clearkey. supportedconfigurations a non-empty array of mediakeysystemconfiguration objects. the first element with a satisfiable configuration will be used. ...
... notsupportederror either the specified keysystem isn't supported by the platform or the browser, or none of the configurations specified by supportedconfigurations can be satisfied (if, for example, none of the codecs specified in contenttype are available). ...
NetworkInformation - Web APIs
provides a means for scripts to be notified if the connection type changes. the networkinformation interfaces cannot be instantiated. it is instead accessed through the connection property of the navigator interface. note: this feature is available in web workers. properties this interface also inherits properties of its parent, eventtarget. ...
...connection property of the navigator interface. note: this feature is available in web workers. properties this interface also inherits properties of its parent, eventtarget. networkinformation.downlink read only re
turns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. networkinformation.downlinkmax read only re
turns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology. ...
...s parent, eventtarget. networkinformation.downlink read only re
turns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. networkinformation.downlinkmax read only re
turns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology. networkinformation.effectivetype read only re
turns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. this value is determined using a combination of recently observed round-trip time and downlink values. ...
...read only re
turns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology. networkinformation.effectivetype read only re
turns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. this value is determined using a combination of recently observed round-trip time and downlink values. networkinformation.rtt read only re
turns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. networkinformation.savedata read only re
turns true if the user has set a reduced data usage option on the user agent. networkinformation.type read only re
turns the type of connection a device is using to communicate with the network. it will be one of the following values:...
Node.textContent - Web APIs
s the text content of the node and its descendants. note: textcontent and htmlelement.innertext are easily confused, but the two properties are different in important ways. ...
...textcontent = string value a string or null description the value of textcontent depends on the situation: if the node is a document or a doctype, textcontent re
turns null. note: to get all of the text and cdata data for the whole document, one could use document.documentelement.textcontent. if the node is a cdata section, comment, processing instruction, or text node, textcontent re
turns the text inside the node, i.e., the node.nodevalue. for other node types, textcontent re
turns the concatenation of the textcontent of every child node, excluding comments and processing instructions. (this is an empty string if the node has no children.) setting textcontent on a node removes all of the node's children and replaces them with a single text node with the given string value. dif...
...ingle text node with the given string value. differences from innertext don't get confused by the differences between node.textcontent and htmlelement.innertext. although the names seem similar, there are important differences: textcontent gets the content of all elements, including <script> and <style> elements. in contrast, innertext only shows “human-readable” elements. textcontent re
turns every element in the node. in contrast, innertext is aware of styling and won’t re
turn the text of “hidden” elements. moreover, since innertext takes css styles into account, reading the value of innertext triggers a reflow to ensure up-to-date computed styles. (reflows can be computationally expensive, and thus should be avoided when possible.) unlike textcontent, altering inn...
...tationally expensive, and thus should be avoided when possible.) unlike textcontent, altering innertext in internet explorer (version 11 and below) removes child nodes from the element and permanently destroys all descendant text nodes. it is impossible to insert the nodes again into any other element or into the same element after doing so. differences from innerhtml element.innerhtml re
turns html, as its name indicates. sometimes people use innerhtml to retrieve or write text inside an element, but textcontent has better performance because its value is not parsed as html. moreover, using textcontent can prevent xss attacks. examples given this html fragment: <div id="diva">this is <span>some</span> text!</div> ... you can use textcontent to get the element's text content: let...
NodeFilter.acceptNode() - Web APIs
the nodefilter.acceptnode() method re
turns an unsigned short that will be used to tell if a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm. this method is expected to be written by the user of a nodefilter. possible re
turn values are: constant description nodefilter.filter_accept value re
turned by the nodefilter.acceptnode() method when a node should be accepted. nodefilter.filter_reject value to be re
turned by the nodefilter.acceptnode() method when a node should be rejected. the children of rejected nodes are not visited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". ...
...by the nodefilter.acceptnode() method when a node should be accepted. nodefilter.filter_reject value to be re
turned by the nodefilter.acceptnode() method when a node should be rejected. the children of rejected nodes are not visited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". nodefilter.filter_skip value to be re
turned by nodefilter.acceptnode() for nodes to be skipped by the nodeiterator or treewalker object. the children of skipped nodes are still considered. this is treated as "skip this node but not its children". ...
...sited by the nodeiterator or treewalker object; this value is treated as "skip this node and all its children". nodefilter.filter_skip value to be re
turned by nodefilter.acceptnode() for nodes to be skipped by the nodeiterator or treewalker object. the children of skipped nodes are still considered. this is treated as "skip this node but not its children". the function should re
turn nodefilter.filter_accept, which causes the treewalker to re
turn the node, nodefilter.filter_reject, which causes the treewalker to ignore the entire subtree, or nodefilter.filter_skip. the browser doesn't provide any object implementing this method. it is the user who is expected to write an object implementing the nodefilter interface, tailoring the acceptnode() method to its needs, and using i...
... living standard no change from document object mod...
NodeIterator - Web APIs
the nodeiterator interface represents an iterator over the members of a list of the nodes in a subtree of the dom. the nodes will be re
turned in document order. syntax a nodeiterator can be created using the document.createnodeiterator() method, as follows: const nodeiterator = document.createnodeiterator(root, whattoshow, filter); properties this interface doesn't inherit any property. nodeiterator.root read only re
turns a node representing the root node as specified when the nodeiterator was created. nodeiterator.whattoshow read only re
turns an unsigned long being a bitmask made of constants describing the types of node that must to be presented. non-matching nodes are skipped, but their children may be included, if relevant. the possible values are: constant ...
...e, it means that the notation node will appear in the first position of the traversal. since entities are not part of the document tree, they do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. ...
...cessinginstruction nodes. nodefilter.show_text 4 shows text nodes. nodeiterator.filter read only re
turns a nodefilter used to select the relevant nodes. nodeiterator.expandentityreferences read only is a boolean indicating if, when discarding an entityreference its whole sub-tree must be discarded at the same time. nodeiterator.referencenode read only re
turns the node to which the iterator is anchored. nodeiterator.pointerbeforereferencenode read only re
turns a boolean flag that indicates whether the nodeiterator is anchored before, the flag being true, or after, the flag being false, the anchor node. methods this interface doesn't inherit any method. nodeiterator.detach() this operation is a no-op. it doesn't do anything. previously it...
...ag that indicates whether the nodeiterator is anchored before, the flag being true, or after, the flag being false, the anchor node. methods this interface doesn't inherit any method. nodeiterator.detach() this operation is a no-op. it doesn't do anything. previously it was telling the engine that the nodeiterator was no more used, but this is now useless. nodeiterator.previousnode() re
turns the previous node in the document, or null if there are none. nodeiterator.nextnode() re
turns the next node in the document, or null if there are none. specifications specification status comment domthe definition of 'nodeiterator' in that specification. living standard added the referencenode and pointerbeforereferencenode properties. removed the expand...
NodeList - Web APIs
although nodelist is not an array, it is possible to iterate over it with foreach(). it can also be converted to a real array using array.from(). however, some older browsers have not implemented nodelist.foreach() nor array.from(). this can be circumvented by using array.prototype.foreach() — see this document's example. live vs. static nodelists although they are both considered nodelists, there are 2 varieties of nodelist: live and static. live nodelists in some cases, the nodelist is live, which means that changes in the dom automatically update the collection. ...
...elementbyid('parent'); let child_nodes = parent.childnodes; console.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection. the ubiquitous document.queryselectorall() method re
turns a static nodelist. it's good to keep this distinction in mind when you choose how to iterate over the items in the nodelist, and whether you should cache the list's length. properties nodelist.length the number of nodes in the nodelist. methods nodelist.item() re
turns an item in the list by its index, or null if the index is out-of-bounds. an alternative to accessing nodelist[i] (wh...
...elist. it's good to keep this distinction in mind when you choose how to iterate over the items in the nodelist, and whether you should cache the list's length. properties nodelist.length the number of nodes in the nodelist. methods nodelist.item() re
turns an item in the list by its index, or null if the index is out-of-bounds. an alternative to accessing nodelist[i] (which instead re
turns undefined when i is out-of-bounds). this is mostly useful for non-javascript dom implementations. nodelist.entries() re
turns an iterator, allowing code to go through all key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0 and the values are nodes.) nodelist.foreach() executes a provided function once per nodelist element, passing the element as a...
...ostly useful for non-javascript dom implementations. nodelist.entries() re
turns an iterator, allowing code to go through all key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0 and the values are nodes.) nodelist.foreach() executes a provided function once per nodelist element, passing the element as an argument to the function. nodelist.keys() re
turns an iterator, allowing code to go through all the keys of the key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0.) nodelist.values() re
turns an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection. example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i ...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
the nondocumenttypechildnode.nextelementsibling read-only property re
turns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list. syntax var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet ...
...ed to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("nextelementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "nextelementsibling", { get: function(){ var e = this.nextsibling; while(e && 1 !== e.nodetype) e = e.nextsibling; re
turn e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/nextelementsibling/nextelementsibling.md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('nextelementsibling')) { re
turn; } object.defineproperty(item, 'nextelementsibling', { configurable: tru...
... living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode.
...on (arr) { arr.foreach(function (item) { if (item.hasownproperty('nextelementsibling')) { re
turn; } object.defineproperty(item, 'nextelementsibling', { configurable: true, enumerable: true, get: function () { var el = this; while (el = el.nextsibling) { if (el.nodetype === 1) { re
turn el; } } re
turn null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'childnodenextelementsibling' in that specification. living standard split the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is now defined on the former...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
the nondocumenttypechildnode.previouselementsibling read-only property re
turns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list. syntax prevnode = elementnodereference.previouselementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <li>this is a list item</li> <li>this is another list item</li> <div id="div-03">here is div-03</div> <script> let el = document.getelementbyid('div-03').previouselementsibling; document.write('<p>siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodename + '</li>'); el = el.previouselementsibling; } document.write('</ol>'); </script> this example outputs the following into the page ...
...nippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("previouselementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "previouselementsibling", { get: function(){ var e = this.previoussibling; while(e && 1 !== e.nodetype) e = e.previoussibling; re
turn e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/previouselementsibling/previouselementsibling.md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('previouselementsibling')) { re
turn; } object.defineproperty(item, 'previouselementsibling', { configu...
... living standard splitted the elementtraversal interface in childnode, parentnode, and no...
... arr.foreach(function (item) { if (item.hasownproperty('previouselementsibling')) { re
turn; } object.defineproperty(item, 'previouselementsibling', { configurable: true, enumerable: true, get: function () { let el = this; while (el = el.previoussibling) { if (el.nodetype === 1) { re
turn el; } } re
turn null; }, set: undefined }); }); })([element.prototype, characterdata.prototype]); specifications specification status comment domthe definition of 'nondocumenttypechildnode.previouselementsibling' in that specification. living standard splitted the elementtraversal interface in childnode, parentnode, and nondocumenttypechildnode. this method is no...
NotificationEvent.notification - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click'); // data can be attached to the notification so that you // can process it in the notificationclick handler. ...
... example self.addeventlistener('notificationclick', function(event) { console.log('on notification click'); // data can be attached to the notification so that you // can process it in the notificationclick handler. ...
... living standard living standard. ...
... living standard living standard. ...
Page Visibility API - Web APIs
visible. when the user minimizes the window or switches to another tab, the api sends a visibilitychange event to let listeners know the state of the page has changed. you can detect the event and perform some actions or behave differently. for example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user re
turns to the tab. the user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime. visibility states of an <iframe> are the same as the parent document. hiding an <iframe> using css properties (such as display: none;) doesn't trigger visibility events or change the state of the do...
...for example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. the page visibility api addresses this. note: while onblur and onfocus will tell you if the user switches windows, it doesn't n...
...nning code that's using real-time network connections (websockets and webrtc) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed. indexeddb processes are also left unthrottled in order to avoid timeouts. example view live example (video with sound). ...
... videoelement.addeventlistener("pause", function(){ document.title = 'paused'; }, false); // when the video plays, set the title. videoelement.addeventlistener("play", function(){ document.title = 'playing'; }, false); } properties added to the document interface the page visibility api adds the following properties to the document interface: document.hidden read only re
turns true if the page is in a state considered to be hidden to the user, and false otherwise. document.visibilitystate read only a domstring indicating the document's current visibility state. possible values are: visible the page content may be at least partially visible. in practice this means that the page is the foreground tab of a non-minimized window. hidden the page's content is n...
PaymentResponse.retry() - Web APIs
t method specific errors which may have occurred. this object's contents will vary depending on the payment used. for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object. shippingaddress optional an addresserrors object which contains error messages for any of the fields in the shipping address that failed validation. re
turn value a promise which is resolved when the payment is successfully completed. the promise is rejected with an appropriate exception value if the payment fails again. typically you will use this by calling show(), then entering a loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request. if a retry is needed, the loop calls retry(), then ...
... loop calls retry(), then loops back to check the response when it comes in. the loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the re
turned paymentresponse describes the requested payment and the options chosen by the user. continue by... validate the re
turned reponse; if there are any fields whose values are not acceptable, call the response's complete() method with a value of "fail" to indicate failure. if the response's data is valid and acceptable, call complete("success") to finalize the payment and proces it. i...
...st request = new paymentrequest(methoddata, details, options); const response = await request.show(); await recursivevalidate(request, response); await response.complete("success"); } // keep validating until the data looks good! ...
... requestorresponse.addeventlistener(event, async function listener(ev) { const promisetovalidate = validator(requestorresponse); ev.updatewith(promisetovalidate); const errors = await promisetovalidate; if (!errors) { // yay! fixed! event.removeeventlistener(event, listener); ...
PerformanceEntry.duration - Web APIs
the duration property re
turns a timestamp that is the duration of the performance entry. note: this feature is available in web workers. the value re
turned by this property depends on the performance entry's type: "frame" - re
turns a timestamp indicating the difference between the starttimes of two successive frames. "mark" - re
turns "0" (a mark has no duration). "measure" - re
turns the timestamp that is the duration of the measure. "navigation" - re
turns the timestamp that is the difference between the performancenavigationtiming.loadeventend and performanceentry.starttime properties, respectively. "resource" - re
turns the difference between the resource's responseend timestamp and its starttime timestamp. this property is read only . ...
...re
turns the timestamp that is the duration of the measure. "navigation" - re
turns the timestamp that is the difference between the performancenavigationtiming.loadeventend and performanceentry.starttime properties, respectively. "resource" - re
turns the difference between the resource's responseend timestamp and its starttime timestamp. this property is read only . syntax entry.duration; re
turn value a domhighrestimestamp representing the duration of the performance entry. if the duration concept doesn't apply for a particular performance metric, the browser may choose to re
turn a duration of 0. note: if the performance entry has an entrytype of "resource" (i.e. ...
...s property is read only . syntax entry.duration; re
turn value a domhighrestimestamp representing the duration of the performance entry. if the duration concept doesn't apply for a particular performance metric, the browser may choose to re
turn a duration of 0. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property re
turns the difference between the performanceentry.responseend and performanceentry.starttime timestamps. example the following example shows the use of the duration property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
...s a performanceresourcetiming object), this property re
turns the difference between the performanceentry.responseend and performanceentry.starttime timestamps. example the following example shows the use of the duration property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
PerformanceNavigationTiming - Web APIs
this interface also extends following performa...
...ent-baseline="middle">performancenavigationtiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface extends the following performanceentry properties for navigation performance entry types by qualifying and constraining them as follows: performanceentry.entrytype read only re
turns "navigation". performanceentry.name read only re
turns the document's address. performanceentry.starttime read only re
turns a domhighrestimestamp with a value of "0". performanceentry.duration read only re
turns a timestamp that is the difference between the performancenavigationtiming.loadeventend and performanceentry.starttime properties. this interface also extends following performanceresourcetiming properties for navigation performance e...
... the interface also supports the following properties: performancenavigationtiming.domcomplete read only a domhighrestimestamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete. ...
...stamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document. performancenavigationtiming.unloadeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document. methods performancenavigationtiming.tojson() re
turns a domstring that is the json representation of the performancenavigationtiming object. specifications specification status comment navigation timing level 2the definition of 'performancenavigationtiming' in that specification. working draft initial definition. ...
PerformanceResourceTiming.secureConnectionStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceTiming - Web APIs
. if there is no previous document, this value will be the same as performancetiming.fetchstart. performancetiming.unloadeventstart read only when the unload event has been thrown, indicating the time at which the previous document in the window began to unload. if there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value re
turned is 0. performancetiming.unloadeventend read only when the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value re
turned is 0. performancetiming.redirectstart read only when the first http redirect starts. if there is no redirect, or if one of the redirects is not of the same...
...ncetiming.unloadeventend read only when the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value re
turned is 0. performancetiming.redirectstart read only when the first http redirect starts. if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0. performancetiming.redirectend read only when the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirects is not of the same origin, the value re
turned is 0. performancetiming.fetchstart read only when the browser is ready to fetch the document using an http request. this moment is b...
...st connection establishment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. performancetiming.secureconnectionstart read only when the secure connection handshake starts. if no such connection is requested, it re
turns 0. performancetiming.requeststart read only when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. performancetiming.responsestart read only when the browser received the first by...
...in order or not, have been executed. performancetiming.domcomplete read only when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. performancetiming.loadeventstart read only when the load event was sent for the current document. if this event has not yet been sent, it re
turns 0. performancetiming.loadeventend read only when the load event handler terminated, that is when the load event is completed. if this event has not yet been sent, or is not yet completed, it re
turns 0. methods the performancetiming interface doesn't inherit any methods. performancetiming.tojson() re
turns a json object representing this performancetiming object. specifications...
PhotoCapabilities - Web APIs
the photocapabilities interface of the the mediastream image capture api provides available configuration options for an attached photographic device. a photocapabilities object is retrieved by calling imagecapture.getphotocapabilities(). properties photocapabilities.redeyereduction read only re
turns one of "never", "always", or "controllable". the "controllable" value means the device's read-eye reduction is controllable by the user. ...
...e configuration options for an attached photographic device. a photocapabilities object is retrieved by calling imagecapture.getphotocapabilities(). properties photocapabilities.redeyereduction read only re
turns one of "never", "always", or "controllable". the "controllable" value means the device's read-eye reduction is controllable by the user. photocapabilities.imageheight read only re
turns a mediasettingsrange object indicating the image height range supported by the user agent. photocapabilities.imagewidth read only re
turns a mediasettingsrange object indicating the image width range supported by the user agent. photocapabilities.filllightmode read only re
turns an array of available fill light options. options may include auto, off, or flash. example the following exampl...
...ture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
... working draft initial definition. browser compatibility the co...
Multi-touch interaction - Web APIs
event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. ...
...>clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. ...
...utput></output> </body> miscellaneous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. ...
...ous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. ...
RTCConfiguration - Web APIs
g ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or
turn servers. if this isn't specified, the connection attempt will be made with no stun or
turn server available, which limits the connection to local peers. icetransportpolicy optional the current ice transport policy; this must be one of the values from the rtcicetransportpolicy enumeration. if the policy isn't specified, all is assumed by default, allowing all candidates to be considered. a value...
... server available, which limits the connection to local peers. icetransportpolicy optional the current ice transport policy; this must be one of the values from the rtcicetransportpolicy enumeration. if the policy isn't specified, all is assumed by default, allowing all candidates to be considered. a value of relay limits the candidates to those relayed through another server, such as a stun or
turn server. peeridentity optional a domstring which specifies the target peer identity for the rtcpeerconnection. if this value is set (it defaults to null), the rtcpeerconnection will not connect to a remote peer unless it can successfully authenticate with the given name. rtcpmuxpolicy optional the rtcp mux policy to use when gathering ice candidates, in order to support non-multiplexed rtcp. t...
...onsidered during the connection process. constant description "all" all ice candidates will be considered. "public" only ice candidates with public ip addresses will be considered. removed from the specification's may 13, 2016 working draft. "relay" only ice candidates whose ip addresses are being relayed, such as those being passed through a
turn server, will be considered. rtcrtcpmuxpolicy enum the rtcrtcpmuxpolicy enum defines string constants which specify what ice candidates are gathered to support non-multiplexed rtcp. <<<add a link to info about multiplexed rtcp. constant description "negotiate" instructs the ice agent to gather both rtp and rtcp candidates. if the remote peer can multiplex rtcp,...
...t ice candidates are gathered to support non-multiplexed rtcp. <<<add a link to info about multiplexed rtcp. constant description "negotiate" instructs the ice agent to gather both rtp and rtcp candidates. if the remote peer can multiplex rtcp, then rtcp candidates are multiplexed atop the corresponding rtp candidates. otherwise, both the rtp and rtcp candidates are re
turned, separately. "require" tells the ice agent to gather ice candidates for only rtp, and to multiplex rtcp atop them. if the remote peer doesn't support rtcp multiplexing, then session negotiation fails. using certificates when you wish to provide your own certificates for use by an rtcpeerconnection instead of having the rtcpeerconnection generate them automatically, you do so...
RTCDtlsTransport - Web APIs
rs directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining rtcdtlstransport objects. data channels rtcdatachannels use sctp to communicate. all of a peer connection's data channels share a single rtcsctptransport, found in the connection's sctp property. ...
... let pc = new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ... ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport' in that specification. candidate recommendation initial definition. ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport' in that specification. candidate recommendation initial definition. ...
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
the rtcicecandidatepairstats property availableoutgoingbitrate re
turns a value indicative of the available outbound capacity of the network connection represented by the candidate pair. the higher the value, the more bandwidth you can assume is available for outgoing data. you can get the incoming available bitrate from availableincomingbitrate. syntax availableoutgoingbitrate = rtcicecandidatepairstats.availableoutgoingbitrate; value a floating-point value which approximates the amount of available bandwidth for outgoing data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. ...
...ncoming available bitrate from availableincomingbitrate. syntax availableoutgoingbitrate = rtcicecandidatepairstats.availableoutgoingbitrate; value a floating-point value which approximates the amount of available bandwidth for outgoing data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. ...
...he value is reported in bits per second and is computed over a 1-second interval. the re
turned value is undefined in each of the following situations: the underlying implementation doesn't support computing a sender-side estimate of the outgoing bit rate. the rtcicecandidatepair described by this object has never been used. the candidate pair was once in use, but no longer is. the value re
turned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the re
turned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp. ...
... rtcicecandidatepair described by this object has never been used. the candidate pair was once in use, but no longer is. the value re
turned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the re
turned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp. note: the re
turned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.availableoutgoingbitrate' in that specification. candidate recommendation ini...
RTCIceCandidateStats - Web APIs
bject provides statistics for. deleted optional a boolean value indicating whether or not the candidate has been released or deleted; the default value is false. for local candidates, it's value is true if the candidate has been deleted or released. for host candidates, true means that any network resources (usually a network socket) associated with the candidate have already been released. for
turn candidates, the
turn allocation is no longer active for deleted candidates. this property is not present for remote candidates. networktype optional a string from the rtcnetworktype enumerated type which indicates the type of interface used for a local candidate. this property is only present for local candidates. port optional the network port number used by the candidate. priority optional...
...y is only present for local candidates. port optional the network port number used by the candidate. priority optional the candidate's priority, corresponding to rtcicecandidate.priority. protocol optional a string specifying the protocol (tcp or udp) used to transmit data on the port. relayprotocol optional a string identifying the protocol used by the endpoint for communicating with the
turn server; valid values are tcp, udp, and tls. only present for local candidates. transportid optional a string uniquely identifiying the transport object that was inspected in order to obtain the rtctransportstats associated with the candidate correspondin to these statistics. url optional for local candidates, the url property is the url of the ice server from which the candidate was received.
...s object's networktype and determine whether or not the type of network is acceptable for use. this function is then called for rtcstats objects whose type is local-candidate, indicating that the object is in fact an rtcicecandidatestats with information about a local ice candidate. ...
...hen called for rtcstats objects whose type is local-candidate, indicating that the object is in fact an rtcicecandidatestats with information about a local ice candidate. const isusablenetworktype = stats => { switch(stats.networktype) { case "ethernet": case "vpn": re
turn true; case "bluetooth": case "cellular": case "wimax": case "unknown": default: re
turn false; } } if (rtcstats && rtcstats.type === "local-candidate") { if (!isusablenetworktype(rtcstats)) { abortconnection(); re
turn; } } this code calls a function called abortconnection() if the rtcstats object represents information about a local candidate is which would be using a network connection other than ethernet or a vpn. specifications specification status ...
RTCIceServer.credentialType - Web APIs
d string type: oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. ...
... oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. ...
...ticate in order to use the ice server described. this process is detailed in rfc 7635. this property was formerly called token. password the rtciceserver requires a username and password to authenticate prior to using the described ice server. example this example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server will use the username "webrtc" and the creative password "
turnpassword". ...
... a username and password to authenticate prior to using the described ice server. example this example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server will use the username "webrtc" and the creative password "
turnpassword". mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "
turn:
turnserver.example.org", // a
turn server username: "webrtc", credential: "
turnpassword", credentialtype: "password" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification. candidate recommendation initial specification. ...
RTCIceServer - Web APIs
this must be one of the values defined by the rtcicecredentialtype enum. the default is password. ...
...this must be one of the values defined by the rtcicecredentialtype enum. the default is password. ...
...nary defines how to connect to a single ice server (such as a stun or
turn server). objects of this type are provided in the configuration of an rtcpeerconnection, in the iceservers array. properties credential optional the credential to use when logging into the server. this is only used if the rtciceserver represents a
turn server. credentialtype optional if the rtciceserver represents a
turn server, this attribute specifies what kind of credential is to be used when connecting. this must be one of the values defined by the rtcicecredentialtype enum. the default is password. ...
... avoid specifying an unnecessarily large number of urls in the urls property; the startup time for your connection will go up substantially. every server in the list will be contacted and tried out before one is selected to be used for negotiation. ...
RTCPeerConnection.addTrack() - Web APIs
which the track should be added. the specified track doesn't necessarily have to already be part of any of the specified streams. instead, the streams are simply a way to group tracks together on the receiving end of the connection, making sure they are synchronized. any tracks that are added to the same stream on the local end of the connection will be on the same stream on the remote end. re
turn value the rtcrtpsender object which will be used to transmit the media data. note: every rtcrtpsender is paired with an rtcrtpreceiver to make up an rtcrtptransceiver. the associated receiver is muted (indicating that it is not able to deliver packets) until and unless one or more streams are added to the receiver by the remote peer. exceptions invalidaccesserror the specified track (or ...
...audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoelem.srcobject = stream; this sets the video element's current stream to the one that contains the track that's been added to the connection. reused senders this method may re
turn either a new rtcrtpsender or, under very specific circumstances, an existing compatible sender which has not yet been used to transmit data. compatible reusable rtcrtpsender instances meet these criteria: there is no track already associated with the sender. the rtcrtptransceiver associated with the sender has a rtcrtpreceiver whose track property specifies a mediastreamtrack whose kind is th...
...g and its corresponding sample code. it comes from the handlevideooffermsg() method there, which is called when an offer message is received from the remote peer. var mediaconstraints = { audio: true, // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); pc.setremotedescription(desc).then(function () { re
turn navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { previewelement.srcobject = stream; stream.gettracks().foreach(track => pc.addtrack(track, stream)); }) this code takes sdp which has been received from the remote peer and constructs a new rtcsessiondescription to pass into setremotedescription(). once that succeeds, it uses mediadevices.getusermedia() to obt...
...it uses mediadevices.getusermedia() to obtain access to the local webcam and microphone. if that succeeds, the resulting stream is assigned as the source for a <video> element which is referenced by the variable previewelement. the final step is to begin sending the local video across the peer connection to the caller. this is done by adding each track in the stream by iterating over the list re
turned by mediastream.gettracks() and passing them to addtrack() along with the stream which they're a component of. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.addtrack()' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.createOffer() - Web APIs
tc connection to a remote peer. the sdp offer includes information about any mediastreamtracks already attached to the webrtc session, codec, and options supported by the browser, and any candidates already gathered by the ice agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection. the re
turn value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the newly-created offer. syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(successcallback, failurecallback, [options]) parameters options optional an rtcofferoptions dictionary providing options requested for the offer. rtcoffero...
...eerconnection.createoffer(successcallback, failurecallback, [options]) parameters options optional an rtcofferoptions dictionary providing options requested for the offer. rtcofferoptions dictionary the rtcofferoptions dictionary is used to customize the offer created by this method. icerestart optional to restart ice on an active connection, set this to true. this will cause the re
turned offer to have different credentials than those already in place. if you then apply the re
turned offer, ice will restart. specify false to keep the same credentials and therefore not restart ice. the default is false. offertoreceiveaudio optional (legacy) a legacy boolean option which used to control whether or not to offer to the remote peer the opportunity to try to send audio. if this value...
...allback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created offer. errorcallback an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an offer failed. options optional an optional rtcofferoptions dictionary providing options requested for the offer. re
turn value a promise whose fulfillment handler will receive an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp describing the generated offer. that received offer should be delivered through the signaling server to a remote peer. exceptions these exceptions are re
turned by rejecting the re
turned promise. your rejection handler should examine the received excepti...
... detail that's entirely up to you. in this case, a websocket connection is used to send a json message with a type field with the value "video-offer" to the other peer. the contents of the object being passed to the sendtoserver() function, along with everything else in the promise fulfillment handler, depend entirely on your design. ...
RTCPeerConnection.peerIdentity - Web APIs
once this promise resolves successfully, the resulting identity is the target peer identity and cannot change for the duration of the connection. syntax var identity = rtcpeerconnection.peeridentity; value a javascript promise which resolves to an rtcidentityassertion that describes the remote peer's identity. if an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. ...
... peer's identity. if an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. note: the promise re
turned by setremotedescription() cannot resolve until any target peer identity that's been set is validated. if the identity hasn't been validated yet, the promise re
turned 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. example in this example, a function, getidentityassertion(),...
... set is validated. if the identity hasn't been validated yet, the promise re
turned 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. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then re
turns the identity to the caller. if an error occurs and the promise is rejected, this logs the error to the console and re
turns null to the caller. let pc = new rtcpeerconnection(); /* ... ...
...entityassertion(), is created which asynchronously waits for the peer's identity to be verified, then re
turns the identity to the caller. if an error occurs and the promise is rejected, this logs the error to the console and re
turns null to the caller. let pc = new rtcpeerconnection(); /* ... */ async function getidentityassertion(pc) { try { const identity = await pc.peeridentity; re
turn identity; } catch(err) { console.log("error identifying remote peer: ", err); re
turn null; } } specifications specification status comment identity for webrtc candidate recommendation initial specification. ...
RTCPeerConnectionIceErrorEvent - Web APIs
the rtcpeerconnectioniceerrorevent interface—based upon the event interface—provides details pertaining to an ice error announced by sending an icecandidateerror event to the rtcpeerconnection object. constructor rtcpeerconnectioniceerrorevent() creates and re
turns a new rtcpeerconnectioniceerrorevent object, with its type and other properties initialized as specified in the parameters. you will not normally create an object of this type yourself. ...
...ject, with its type and other properties initialized as specified in the parameters. you will not normally create an object of this type yourself. properties the rtcpeerconnectioniceerrorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or
turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate. errorcode read only an unsigned integer value stating the numeric stun error code re
turned by the stun or
turn server. if no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid stun error codes. th...
...ned integer value stating the numeric stun error code re
turned by the stun or
turn server. if no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid stun error codes. the 701 error is fired only once per server url, and only while the is icegatheringstate is gathering. errortext read only a domstring containing the stun reason text re
turned by the stun or
turn server. if communication with the stun or
turn server couldn't be established at all, this string will be a browser-specific string explaining the error. port read only an unsigned integer value giving the port number over which communication with the stun or
turn server is taking place, using the ip address given in address. null if the connection hasn't been established...
... methods rtcpeerconnectioniceerrorevent has no methods other than any provided by the parent interface, event. ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
the static function rtcrtpreceiver.getcapabilities() re
turns an rtcrtpcapabilities object describing the codecs and capabilities supported by rtcrtpreceivers on the current device. you can, similarly, obtain the capabilities of rtcrtpsenders by calling the static function rtcrtpsender.getcapabilities(). syntax let rtpcapabilities = rtcrtpreceiver.getcapabilities(kind); parameters kind a domstring indicating the type of media for which you wish to get the device's capability to receive. all browsers support the primary media kinds: audio and video. re
turn value an rtcrtpcapabilities object stating what capabilities the browser has for receiving the specified media kind over an rtcpeerconnection. ...
... kind a domstring indicating the type of media for which you wish to get the device's capability to receive. all browsers support the primary media kinds: audio and video. re
turn value an rtcrtpcapabilities object stating what capabilities the browser has for receiving the specified media kind over an rtcpeerconnection. if the browser doesn't have any support for the given media kind, the re
turned value is null. description as a static function, this is always called using the form: capabilities = rtcrtpreceiver.getcapabilities("audio"); the re
turned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browse...
...a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below re
turns a boolean indicating whether or not the device supports receiving h.264 video on a webrtc connection. since rtcrtpreceiver.getcapabilities() actually only indicates probable support, attempting to receive h.264 video might still fail even after getting a positive response from this function. function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); capabili...
... webrtc connection. since rtcrtpreceiver.getcapabilities() actually only indicates probable support, attempting to receive h.264 video might still fail even after getting a positive response from this function. function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { re
turn true; } }); re
turn false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getcapabilities()' in that specification. candidate recommendation ...
RTCRtpReceiver - Web APIs
the rtcrtpreceiver interface of the webrtc api manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection. properties rtcrtpreceiver.track read only re
turns the mediastreamtrack associated with the current rtcrtpreceiver instance. rtcrtpreceiver.transport read only re
turns the rtcdtlstransport instance over which the media for the receiver's track is received. obsolete properties rtcptransport this property has been removed; the rtp and rtcp transports have been combined into a single transport. use the transport property instead. ...
... rtcrtpreceiver instance. rtcrtpreceiver.transport read only re
turns the rtcdtlstransport instance over which the media for the receiver's track is received. obsolete properties rtcptransport this property has been removed; the rtp and rtcp transports have been combined into a single transport. use the transport property instead. methods rtcrtpreceiver.getcontributingsources() re
turns an array of rtcrtpcontributingsource instances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. rtcrtpreceiver.getparameters() re
turns an rtcrtpparameters object which contains information about how the rtc data is to be decoded. ...
...tead. methods rtcrtpreceiver.getcontributingsources() re
turns an array of rtcrtpcontributingsource instances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. rtcrtpreceiver.getparameters() re
turns an rtcrtpparameters object which contains information about how the rtc data is to be decoded. rtcrtpreceiver.getstats() re
turns a promise whose fulfillment handler receives a rtcstatsreport which contains statistics about the incoming streams and their dependencies. rtcrtpreceiver.getsynchronizationsources() re
turns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds. static methods rtcr...
...ndler receives a rtcstatsreport which contains statistics about the incoming streams and their dependencies. rtcrtpreceiver.getsynchronizationsources() re
turns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds. static methods rtcrtpreceiver.getcapabilities() re
turns the most optimistic view of the capabilities of the system for receiving media of the given kind. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver' in that specification. candidate recommendation initial definition. ...
RTCRtpSender.getCapabilities() static function - Web APIs
the static function rtcrtpsender.getcapabilities() re
turns an rtcrtpcapabilities object describing the codecs and capabilities supported by the rtcrtpsender. you can, similarly, obtain the capabilities of rtcrtpreceivers by calling the static function rtcrtpreceiver.getcapabilities(). syntax let rtpcapabilities = rtcrtpsender.getcapabilities(kind); parameters kind a domstring indicating the type of media for which you wish to get the sender's capability to receive. all browsers support the primary media kinds: audio and video. re
turn value an rtcrtpcapabilities object stating what capabilities the browser has for sending the specified media kind over an rtcpeerconnection. if the browser doesn't have any support for the given media kind, the re
turned value is null. description as ...
...it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. ...
...a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below re
turns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicates probable support, h.264 support might still fail even after getting a positive response from this function. function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec) => { ...
...pports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicates probable support, h.264 support might still fail even after getting a positive response from this function. function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { re
turn true; } }); re
turn false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getcapabilities()' in that specification. candidate recommendation ...
ReadableStream.cancel() - Web APIs
f there are chunks enqueued waiting to be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). syntax var promise = readablestream.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. re
turn value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to cancel is not a readablestream, or it is locked. examples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers". when the search terms is found, canc...
...(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ? searchterm.tolowercase() : searchterm; var buffersize = math.max(tomatch.length - 1, contextbefore); var bytesreceived = 0; var buffer = ''; var matchfoundat = -1; re
turn reader.read().then(function process(result) { if (result.done) { console.log('failed to find match'); re
turn; } bytesreceived += result.value.length; console.log(`received ${bytesreceived} bytes of data so far`); buffer += decoder.decode(result.value, {stream: true}); // already found match & just context-gathering? if (matchfoundat === -1) { match...
...see devtools for details. does the response lack cors headers?"); throw err; }); specifications specification status comment streamsthe definition of 'cancel()' in t...
...see devtools for details. does the response lack cors headers?"); throw err; }); specifications specification status comment streamsthe definition of 'cancel()' in that specification. living standard initial definition. ...
ReadableStream.pipeTo() - Web APIs
piping a stream will generally lock it for the duration of the pipe, preventing other readers from locking it. syntax var promise = readablestream.pipeto(destination[, options]); parameters destination a writablestream that acts as the final destination for the readablestream. options optional the options that should be used when piping to the writable stream. ...
...(destination[, options]); parameters destination a writablestream that acts as the final destination for the readablestream. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. ...
...ng will no longer cause the destination writablestream to be closed. the method will re
turn a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventabort: if this is set to true, errors in the source readablestream will no longer abort the destination writablestream. the method will re
turn a promise rejected with the source’s error, or with any error that occurs during aborting the destination. preventcancel: if this is set to true, errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will re
turn a promise rejected with the source’s error, or with any error that occurs during canceling the source. in addition, if th...
...rue, errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will re
turn a promise rejected with the source’s error, or with any error that occurs during canceling the source. in addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. in this case the method will re
turn a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. re
turn value a promise that resolves when the piping process has completed. exceptions typeerror the writablestream and/or r...
SVGMatrix - Web APIs
t of the matrix. svgmatrix.c a float representing the c component of the matrix. svgmatrix.d a float representing the d component of the matrix. svgmatrix.e a float representing the e component of the matrix. svgmatrix.f a float representing the f component of the matrix. methods svgmatrix.multiply() performs matrix multiplication. this matrix is post-multiplied by another matrix, re
turning the resulting new matrix as svgmatrix. svgmatrix.inverse() re
turns the inverse matrix as svgmatrix. svgmatrix.translate() post-multiplies a translation transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.scale() post-multiplies a uniform scale transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.scalenonu...
...ix as svgmatrix. svgmatrix.translate() post-multiplies a translation transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.scale() post-multiplies a uniform scale transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.scalenonuniform() post-multiplies a non-uniform scale transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.rotate() post-multiplies a rotation transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.rotatefromvector() post-multiplies a rotation transformation on the current matrix and re
turns the resulting matrix as svgmatrix. the rotation angle is determined by taking (+/-) atan(y/x). the direction of the vector (...
... matrix as svgmatrix. svgmatrix.rotatefromvector() post-multiplies a rotation transformation on the current matrix and re
turns the resulting matrix as svgmatrix. the rotation angle is determined by taking (+/-) atan(y/x). the direction of the vector (x, y) determines whether the positive or negative angle value is used. svgmatrix.flipx() post-multiplies the transformation [-1 0 0 1 0 0] and re
turns the resulting matrix as svgmatrix. svgmatrix.flipy() post-multiplies the transformation [1 0 0 -1 0 0] and re
turns the resulting matrix as svgmatrix. ...
...vector (x, y) determines whether the positive or negative angle value is used. svgmatrix.flipx() post-multiplies the transformation [-1 0 0 1 0 0] and re
turns the resulting matrix as svgmatrix. svgmatrix.flipy() post-multiplies the transformation [1 0 0 -1 0 0] and re
turns the resulting matrix as svgmatrix. svgmatrix.skewx() post-multiplies a skewx transformation on the current matrix and re
turns the resulting matrix as svgmatrix. svgmatrix.skewy() post-multiplies a skewy transformation on the current matrix and re
turns the resulting matrix as svgmatrix. exceptions a domexception with the code no_modification_allowed_err is raised when attempting updating a read-only attribute or when the object itself is read-only. specifications specification status comment ...
Screen - Web APIs
the one on which the current window is being rendered, and is obtained using window.screen. note that browsers determine which screen to report as current by detecting which screen has the center of the browser window. properties screen.availtop specifies the y-coordinate of the first pixel that is not allocated to permanent or semipermanent user interface features. ...
...rst pixel that is not allocated to permanent or semipermanent user interface features. screen.availleft re
turns the first available pixel available from the left side of the screen. screen.availheight specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the taskbar on windows. screen.availwidth re
turns the amount of horizontal space in pixels available to the window. screen.colordepth re
turns the color depth of the screen. screen.height re
turns the height of the screen in pixels. ...
...ecifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the taskbar on windows. screen.availwidth re
turns the amount of horizontal space in pixels available to the window. screen.colordepth re
turns the color depth of the screen. screen.height re
turns the height of the screen in pixels. screen.left re
turns the distance in pixels from the left side of the main screen to the left side of the current screen. screen.orientation re
turns the screenorientation instance associated with this screen. screen.pixeldepth gets the bit depth of the screen. screen.top re
turns the distance in pixels from the top side of the current screen. screen.width re
turns the width of the screen. screen.mozenabled ...
... screen.mozbrightness controls the brightness of a device's screen. a double between 0 and 1.0 is expected. events handler screen.onorientationchange a handler for the orientationchange event. ...
Screen Wake Lock API - Web APIs
the screen wake lock api provides a way to prevent devices from dimming or locking the screen when an application needs to keep running. concepts and usage most devices by default
turn off their screen after a specified amount of time to prolong the life of the hardware. modern devices do this to save on battery power. whilst this is a useful feature, some applications need the screen to stay awake to be their most useful. the screen wake lock api prevents the screen from
turning off, dimming or locking. it allows for a simple platform based solution which up until now could only be achieved via workarounds which were potentially power hungry. only visible (active) documents can acquire the screen wake lock. there are plenty of use cases for keeping a screen on, including reading an ebook...
...disable it if they wish. screen wake lock api interfaces wakelock the wakelock interface prevents device screens from dimming or locking when an application needs to keep running. wakelocksentinel provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. get an instance of the object by calling wakelock.request. navigator.wakelock re
turns a wakelock object instance, from which all other functionality can be accessed. examples feature detection this code checks for wake lock support and updates the ui accordingly. if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by thi...
...ssupported = 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. 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. // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake lock active statuselem.textcontent = 'wake lock is active!'; } catch (err)...
...ility of the document change and the wake lock is released. document.addeventlistener('visibilitychange', () => { if (wakelock !== null && document.visibilitystate === 'visible') { wakelock = await navigator.wakelock.request('screen'); } }); putting it all together you can find the complete code on github here. the demo uses a button to acquire a wake lock and also release it, which in
turn updates the ui. the ui also updates if the wake lock is released automatically for any reason. there's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again. performance considerations release the screen wake lock when user ends activity that required always-on screen. for example, a ticketing app which u...
ServiceWorkerGlobalScope.onfetch - Web APIs
n event handler fired whenever a fetch event occurs (usually when the windoworworkerglobalscope.fetch() method is called.) syntax serviceworkerglobalscope.onfetch = function(fetchevent) { ... }; example this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code re
turns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code set. self.addeventlistener('fetch...
...04) will not trigger an exception. it will re
turn a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); re
turn response; } console.log('no response found in cache. ...
...t. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); re
turn response; } console.log('no response found in cache. ...
....respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); re
turn response; } console.log('no response found in cache. about to fetch from network...'); re
turn fetch(event.request).then(function(response) { console.log('response from network is:', response); re
turn response; }).catch(function(error) { console.error('fetching failed:', error); throw error; }); }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification. working draft initial definition ...
ShadowRoot - Web APIs
the shadowroot interface of the shadow dom api is the root node of a dom subtree that is rendered separately from a document's main dom tree. you can retrieve a reference to an element's shadow root using its element.shadowroot property, provided it was created using element.attachshadow() with the mode option set to open. properties shadowroot.delegatesfocus read only re
turns a boolean that indicates whether delegatesfocus was set when the shadow was attached (see element.attachshadow()). shadowroot.host read only re
turns a reference to the dom element the shadowroot is attached to. shadowroot.innerhtml sets or re
turns a reference to the dom tree inside the shadowroot. shadowroot.mode read only the mode of the shadowroot — either open or closed. this defines whether or n...
...er or not the shadow root's internal features are accessible from javascript. properties included from documentorshadowroot the shadowroot interface includes the following properties defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.activeelement read only re
turns the element within the shadow tree that has focus. documentorshadowroot.stylesheets read only re
turns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods the shadowroot interface includes the following methods defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers sti...
...read only re
turns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. methods the shadowroot interface includes the following methods defined on the documentorshadowroot mixin. note that this is currently only implemented by chrome; other browsers still implement them on the document interface. documentorshadowroot.getselection() re
turns a selection object representing the range of text selected by the user, or the current position of the caret. documentorshadowroot.elementfrompoint() re
turns the topmost element at the specified coordinates. documentorshadowroot.elementsfrompoint() re
turns an array of all elements at the specified coordinates. ...
... examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes. ...
SpeechRecognition - Web APIs
using speech recognition on a web page involves a server-based recognition engine. your audio is sent to a web service for recognition processing, so it won't work offline. constructor speechrecognition.speechrecognition() creates a new speechrecognition object. properties speechrecognition also inherits properties from its parent interface, eventtarget. speechrecognition.grammars re
turns and sets a collection of speechgrammar objects that represent the grammars that will be understood by the current speechrecognition. speechrecognition.lang re
turns and sets the language of the current speechrecognition. if not specified, this defaults to the html lang attribute value, or the user agent's language setting if that isn't set either. speechrecognition.continuous controls whether...
... speechgrammar objects that represent the grammars that will be understood by the current speechrecognition. speechrecognition.lang re
turns and sets the language of the current speechrecognition. if not specified, this defaults to the html lang attribute value, or the user agent's language setting if that isn't set either. speechrecognition.continuous controls whether continuous results are re
turned for each recognition, or only a single result. defaults to single (false.) speechrecognition.interimresults controls whether interim results should be re
turned (true) or not (false.) interim results are results that are not yet final (e.g. the speechrecognitionresult.isfinal property is false.) speechrecognition.maxalternatives sets the maximum number of speechrecognitionalternatives provid...
...fies the location of the speech recognition service used by the current speechrecognition to handle the actual recognition. the default is the user agent's default speech service. methods speechrecognition also inherits methods from its parent interface, eventtarget. speechrecognition.abort() stops the speech recognition service from listening to incoming audio, and doesn't attempt to re
turn a speechrecognitionresult. speechrecognition.start() starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. speechrecognition.stop() stops the speech recognition service from listening to incoming audio, and attempts to re
turn a speechrecognitionresult using the audio captured so far. events listen ...
... via the onaudiostart property. audioend fired when the user agent has finished capturing audio. also available via the onaudioend property. end fired when the speech recognition service has disconnected. also available via the onend property. error fired when a speech recognition error occurs. also available via the onerror property. nomatch fired when the speech recognition service re
turns a final result with no significant recognition. this may involve some degree of recognition, which doesn't meet or exceed the confidence threshold. also available via the onnomatch property. result fired when the speech recognition service re
turns a result — a word or phrase has been positively recognized and this has been communicated back to the app. also available via the onresult prope...
SpeechRecognitionAlternative.confidence - Web APIs
the confidence read-only property of the speechrecognitionresult interface re
turns a numeric estimate of how confident the speech recognition system is that the recognition is correct. note: mozilla's implementation of confidence is still being worked on — at the moment, it always seems to re
turn 1. syntax var myconfidence = speechrecognitionalternativeinstance.confidence; re
turns a number betwen 0 and 1. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. ...
... a number betwen 0 and 1. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. ...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
SpeechRecognitionAlternative - Web APIs
the speechrecognitionalternative interface of the web speech api represents a single word that has been recognised by the speech recognition service. properties speechrecognitionalternative.transcript read only re
turns a string containing the transcript of the recognised word. speechrecognitionalternative.confidence read only re
turns a numeric estimate of how confident the speech recognition system is that the recognition is correct. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array ...
...e recognition is correct. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. ...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionalternative' in that specification. draft ...
SpeechRecognitionEvent.results - Web APIs
when subsequent result events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases. final results on the other hand will not be overwritten or removed. ...
...if they are at the end of the "results" array and the array length decreases. final results on the other hand will not be overwritten or removed. syntax var myresults = event.results; value a speechrecognitionresultlist object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'results' in that specification. draft ...
SpeechRecognitionResultList - Web APIs
the speechrecognitionresultlist interface of the web speech api represents a list of speechrecognitionresult objects, or a single one if results are being captured in continuous mode. properties speechrecognitionresultlist.length read only re
turns the length of the "array" — the number of speechrecognitionresult objects in the list. methods speechrecognitionresultlist.item a standard getter that allows speechrecognitionresult objects in the list to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it ...
...ccessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. ...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionresultlist' in that specification. draft ...
StaticRange - Web APIs
ment-baseline="middle">staticrange</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor staticrange() creates a new staticrange object given the staticrangeinit dictionary specifying the default values for its properties. properties the properties below are inherited from its parent interface, abstractrange. ...
... staticrange object given the staticrangeinit dictionary specifying the default values for its properties. properties the properties below are inherited from its parent interface, abstractrange. staticrange.collapsed read only re
turns a boolean value which is true if the range's start and end positions are the same, resulting in a range of length 0. staticrange.endcontainer read only re
turns the dom node which contains the ending point of the range. the offset into the node at which the end position is located is indicated by endoffset. ...
...range. staticrange.collapsed read only re
turns a boolean value which is true if the range's start and end positions are the same, resulting in a range of length 0. staticrange.endcontainer read only re
turns the dom node which contains the ending point of the range. the offset into the node at which the end position is located is indicated by endoffset. staticrange.endoffset read only re
turns an integer value indicating the offset into the node given by endcontainer at which the last character of the range is found. staticrange.startcontainer read only re
turns the dom node which contains the starting point of the range (which is in
turn identified by startoffset. ...
... is located is indicated by endoffset. staticrange.endoffset read only re
turns an integer value indicating the offset into the node given by endcontainer at which the last character of the range is found. staticrange.startcontainer read only re
turns the dom node which contains the starting point of the range (which is in
turn identified by startoffset. staticrange.startoffset read only re
turns an integer value indicating the offset into the node specified by startcontainer at which the first character of the range is located. methods staticrange.torange() re
turns a new range object which describes the same range as the source staticrange, but is "live" with values that change to reflect changes in the contents of the dom tree. usage notes a dom range specifies a span of conte...
Using the Storage Access API - Web APIs
st access to storage that would otherwise be blocked when a user’s browser is set to block all third-party cookies. since embedded content won’t know which storage policy is in use by the user, it’s best to always check whether the embedded frame has storage access before attempting to read or write from storage. this is particularly true for document.cookie access, as browsers will often re
turn an empty cookie jar when third-party cookies are blocked. accessing a user's cookies in an embedded cross-origin iframe in this example we show how an embedded cross-origin <iframe> can access a user’s cookies under a storage access policy that blocks third-party cookies. first of all, if the <iframe> is sandboxed, the embedding website needs to add the allow-storage-access-by-user-activatio...
...t to call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> now on to the code executed inside the embedded document. since it does not know whether it currently has access to storage, it should first call document.hasstorageaccess(). ...
...: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> now on to the code executed inside the embedded document. since it does not know whether it currently has access to storage, it should first call document.hasstorageaccess(). ...
...oes not know whether it currently has access to storage, it should first call document.hasstorageaccess(). if that call re
turns false, we can then call document.requeststorageaccess(), re
turning the result so that then we can chain it onto the previous promise call. in the final then, we'll have first-party storage access. document.hasstorageaccess().then(hasaccess => { if (!hasaccess) { re
turn document.requeststorageaccess(); } }).then(_ => { // now we have first-party storage access! // let's access some items from the first-party cookie jar document.cookie = "foo=bar"; // set a cookie localstorage.setitem("username", "john"); // access a localstorage entry }).catch(_ => { // error obtaining storage access. }); note that access requests are automatically den...
SubtleCrypto.deriveBits() - Web APIs
essentially derivekey() is composed of derivebits() followed by importkey(). ...
...essentially derivekey() is composed of derivebits() followed by importkey(). ...
...2params object. basekey is a cryptokey representing the input to the derivation algorithm. if algorithm is ecdh, this will be the ecdh private key. otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey(). length is a number representing the number of bits to derive. re
turn value result is a promise that fulfills with an arraybuffer containing the derived bits. exceptions the promise is rejected when one of the following exceptions are encountered: invalidaccesserror raised when the base key is not a key for the requested derivation algorithm or if the cryptokey.usages value of that key doesn't contain derivekey. notsupported raised when trying to use an...
...); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2. see the complete code on github. let salt; /* get some key material to use as input to the derivebits method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); re
turn window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user. */ async function getderivedbits() { const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const derivedbits = await window.crypto.subtle.deriveb...
SubtleCrypto.digest() - Web APIs
the subtlecrypto interface generates a digest of the given data. a digest is a short fixed-length value derived from some variable-length input. cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. it takes as its arguments an identifier for the digest algorithm to use and the data to digest. it re
turns a promise which will be fulfilled with the digest. syntax const digest = crypto.subtle.digest(algorithm, data); parameters algorithm is a domstring defining the hash function to use. supported values are: sha-1 (but don't use this in cryptographic applications) sha-256 sha-384 sha-512. data is an arraybuffer or arraybufferview containing the data to be digested. re...
...s a promise which will be fulfilled with the digest. syntax const digest = crypto.subtle.digest(algorithm, data); parameters algorithm is a domstring defining the hash function to use. supported values are: sha-1 (but don't use this in cryptographic applications) sha-256 sha-384 sha-512. data is an arraybuffer or arraybufferview containing the data to be digested. re
turn value digest is a promise that fulfills with an arraybuffer containing the digest. supported algorithms digest algorithms, also known as cryptographic hash functions, transform an arbitrarily large block of data into a fixed-size output, usually much shorter than the input. they have a variety of applications in cryptography. sha-1 this algorithm is specified in fips 180-4, section 6.1, a...
...xample 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. the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); re
turn hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is re
turned 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. t...
... recommendation initial definition. ...
Touch events - Web APIs
for example, for a touch.identifier value of 10, the resulting string is "#a31". copying a touch object some browsers (mobile safari, for one) re-use touch objects between events, so it's best to copy the properties you care about, rather than referencing the entire objec...
...can be used when calling <canvas> functions to set drawing colors. for example, for a touch.identifier value of 10, the resulting string is "#a31". copying a touch object some browsers (mobile safari, for one) re-use touch objects between events, so it's best to copy the properties you care about, rather than referencing the entire object. function copytouch({ identifier, pagex, pagey }) { re
turn { identifier, pagex, pagey }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier then re
turns that touch's index into the array. function ongoingtouchindexbyid(idtofind) { for (var i = 0; i < ongoingtouches.length; i++) { var id = ongoingtouches[i].identifier; if (id == idtofind...
...r, pagex, pagey }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier then re
turns that touch's index into the array. function ongoingtouchindexbyid(idtofind) { for (var i = 0; i < ongoingtouches.length; i++) { var id = ongoingtouches[i].identifier; if (id == idtofind) { re
turn i; } } re
turn -1; // not found } showing what's going on function log(msg) { var p = document.getelementbyid('log'); p.innerhtml = msg + "\n" + p.innerhtml; } if your browser supports it, you can see it live. jsfiddle example additional tips this section provides additional tips on how to handle touch events in your web application. handling clicks since calling preventdef...
...ill fire and things like links will continue to work. alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (this example is oversimplified and may result in strange behavior. ...
UIEvent.pageY - Web APIs
syntax var pagey = event.pagey; pagey is an integer value in pixels for the y-coordinate of the mouse pointer, relative to the whole document, when the mouse event fired. this property takes into account any vertical scrolling of the page. ...
...this is a p...
... border: solid blue 1px; padding: 10px; } </style> </head> <body onmousedown="showcoords(event)"> <p>to display the mouse coordinates please click anywhere on the page.</p> <div id="d1"> <span>this is an un-positioned div so clicking it will re
turn layerx/layery values almost the same as pagex/pagey values.</span> </div> <div id="d2"> <span>this is a positioned div so clicking it will re
turn layerx/layery values that are relative to the top-left corner of this positioned element. note the pagex\pagey properties still re
turn the absolute position in the document, including page scrolling.</span> <span>make the page scroll more! this is a positioned div so clicking it will re
turn layerx/layery values that are relative to the top-left corner of this positioned element. note the pagex\p...
...at are relative to the top-left corner of this positioned element. note the pagex\pagey properties still re
turn the absolute position in the document, including page scrolling.</span> <span>make the page scroll more! ...
UIEvent - Web APIs
dle" alignment-baseline="middle">uievent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructors uievent() creates a uievent object. properties this interface also inherits properties of its parent, event. uievent.cancelbubble is a boolean indicating whether the bubbling of the event has been canceled or not. uievent.detailread only re
turns a long with details about the event, depending on the event type. uievent.ischar read only re
turns a boolean indicating whether the event produced a key character or not. uievent.layerx read only re
turns the horizontal coordinate of the event relative to the current layer. uievent.layery read only re
turns the vertical coordinate of the event relative to the current layer. uievent...
...bout the event, depending on the event type. uievent.ischar read only re
turns a boolean indicating whether the event produced a key character or not. uievent.layerx read only re
turns the horizontal coordinate of the event relative to the current layer. uievent.layery read only re
turns the vertical coordinate of the event relative to the current layer. uievent.pagex read only re
turns the horizontal coordinate of the event relative to the whole document. uievent.pagey read only re
turns the vertical coordinate of the event relative to the whole document. uievent.sourcecapabilities read only re
turns an instance of the inputdevicecapabilities interface, which provides information about the physical device responsible for generating a touch event. uievent.viewread only...
... methods this interface also inherits methods of its parent, event. ...
... methods this interface also inherits methods of its parent, event. uievent.inituievent() initializes a uievent object. ...
URLSearchParams - Web APIs
nterface defines utility methods to work with the query string of a url. an object implementing urlsearchparams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers. constructor urlsearchparams() re
turns a urlsearchparams object instance. methods urlsearchparams.append() appends a specified key/value pair as a new search parameter. urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. urlsearchparams.entries() re
turns an iterator allowing iteration through all key/value pairs contained in this object. urlsearchpa...
...arameter. urlsearchparams.delete() deletes the given search parameter, and its associated value, from the list of all search parameters. urlsearchparams.entries() re
turns an iterator allowing iteration through all key/value pairs contained in this object. urlsearchparams.foreach() allows iteration through all values contained in this object via a callback function. urlsearchparams.get() re
turns the first value associated with the given search parameter. urlsearchparams.getall() re
turns all the values associated with a given search parameter. urlsearchparams.has() re
turns a boolean indicating if such a given parameter exists. urlsearchparams.keys() re
turns an iterator allowing iteration through all keys of the key/value pairs contained in this object. urlsearchparams.set() sets ...
... examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters. ...
...e key/value pairs contained in this object. urlsearchparams.set() sets the value associated with a given search parameter to the given value. if there are several values, the others are deleted. urlsearchparams.sort() sorts all key/value pairs, if any, by their keys. urlsearchparams.tostring() re
turns a string containing a query string suitable for use in a url. urlsearchparams.values() re
turns an iterator allowing iteration through all values of the key/value pairs contained in this object. examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters. for (let p of searchparams) { console.log(p); } searchparams.has("topic") === true; // true searchparams.get("topic") === "api"; // true sea...
URLUtilsReadOnly.hash - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
...this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nolegend full support full support ...
URLUtilsReadOnly - Web APIs
containing the whole url. urlutilsreadonly.protocol read only is a domstring containing the protocol scheme of the url, including the final ':'. urlutilsreadonly.host read only is a domstring containing the host, that is the hostname, a ':', and the port of the url. urlutilsreadonly.hostname read only is a domstring containing the domain of the url. urlutilsreadonly.origin read only re
turns a domstring containing the canonical form of the origin of the specific location. urlutilsreadonly.port read only is a domstring containing the port number of the url. urlutilsreadonly.pathname read only is a domstring containing an initial '/' followed by the path of the url. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url. urlut...
...e read only is a domstring containing an initial '/' followed by the path of the url. urlutilsreadonly.search read only is a domstring containing a '?' followed by the parameters of the url. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url. methods this interface doesn't inherit any methods. urlutilsreadonly.tostring() re
turns a domstring containing the whole url. it is a synonym for urlutilsreadonly.href. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androi...
...this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nohost experimentalchrome no support noedge no sup...
User Timing API - Web APIs
performance entry will have the following property values: entrytype - set to "mark". name - set to the "name" given when the mark was created. starttime - set to the timestamp when mark() was called. duration - set to "0" (a mark has no duration). retrieving performance marks the performance interface has three methods that can be used to retrieve a mark: performance.getentries() re
turns all performance entries in the performance timeline. finding only mark entries requires checking each entry's entrytype for "mark". performance.getentriesbyname(name, entrytype) re
turns all performance entries in the performance timeline with the specified name and entrytype, thus set entrytype to "mark" to get all marks (and set name accordingly to retrieve more specific entries). performanc...
...performance timeline. finding only mark entries requires checking each entry's entrytype for "mark". performance.getentriesbyname(name, entrytype) re
turns all performance entries in the performance timeline with the specified name and entrytype, thus set entrytype to "mark" to get all marks (and set name accordingly to retrieve more specific entries). performance.getentriesbytype(entrytype) re
turns all performance entries in the performance timeline with the specified entrytype, thus set entrytype to "mark" to get all marks. removing performance marks to remove a specific mark from the performance timeline, call performance.clearmarks(name) where name is the name of the mark(s) you want removed. if this method is called with no arguments, all mark type entries will be removed from the p...
... "name" given when the measure was created. starttime - set to the timestamp when measure() was called. duration - set to a domhighrestimestamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). retrieving performance measures the performance interface has three methods that can be used to retrieve a measure: performance.getentries() re
turns all performance entries in the performance timeline. finding the measure entries requires checking each entry's entrytype for "measure". performance.getentriesbyname(name, entrytype) re
turns all performance entries in the performance timeline with the specified name and entrytype, thus set entrytype to "measure" to get all measures (and set name accordingly to retrieve more specific entries). ...
... timeline. finding the measure entries requires checking each entry's entrytype for "measure". performance.getentriesbyname(name, entrytype) re
turns all performance entries in the performance timeline with the specified name and entrytype, thus set entrytype to "measure" to get all measures (and set name accordingly to retrieve more specific entries). performance.getentriesbytype(entrytype) re
turns all performance entries in the performance timeline with the specified entrytype, thus set entrytype to "measure" to get all measures. removing performance measures to remove a specific measure from the performance timeline, call performance.clearmeasures(name) where name is the name of the measure(s) you want removed. if this method is called with no arguments, all measure type entries will ...
VisualViewport - Web APIs
the layout viewport. therefore, it's generally only the visualviewport object of the top-level window that's useful. for an <iframe>, visual viewport metrics like visualviewport.width always correspond to layout viewport metrics like document.documentelement.clientwidth. properties visualviewport also inherits properties from its parent, eventtarget. ...
...rics like visualviewport.width always correspond to layout viewport metrics like document.documentelement.clientwidth. properties visualviewport also inherits properties from its parent, eventtarget. visualviewport.offsetleft read only re
turns the offset of the left edge of the visual viewport from the left edge of the layout viewport in css pixels. visualviewport.offsettop read only re
turns the offset of the top edge of the visual viewport from the top edge of the layout viewport in css pixels. ...
...o inherits properties from its parent, eventtarget. visualviewport.offsetleft read only re
turns the offset of the left edge of the visual viewport from the left edge of the layout viewport in css pixels. visualviewport.offsettop read only re
turns the offset of the top edge of the visual viewport from the top edge of the layout viewport in css pixels. visualviewport.pageleft read only re
turns the x coordinate of the visual viewport relative to the initial containing block origin of the top edge in css pixels. visualviewport.pagetop read only re
turns the y coordinate of the visual viewport relative to the initial containing block origin of the top edge in css pixels. visualviewport.width read only re
turns the width of the visual viewport in css pixels. visualviewport.height rea...
...rdinate of the visual viewport relative to the initial containing block origin of the top edge in css pixels. visualviewport.pagetop read only re
turns the y coordinate of the visual viewport relative to the initial containing block origin of the top edge in css pixels. visualviewport.width read only re
turns the width of the visual viewport in css pixels. visualviewport.height read only re
turns the height of the visual viewport in css pixels. visualviewport.scale read only re
turns the pinch-zoom scaling factor applied to the visual viewport. events listen to these events using addeventlistener() or by assigning an event listener to the relevant oneventname property of this interface. resize fired when the visual viewport is resized. also available via the visualviewport.onre...
WebGL2RenderingContext.getActiveUniforms() - Web APIs
2 api retrieves information about active uniforms within a webglprogram. syntax any gl.getactiveuniforms(program, uniformindices, pname); parameters program a webglprogram containing the active uniforms. uniformindices an array of gluint specifying the indices of the active uniforms to query. pname a glenum specifying which information to query. ...
...ny gl.getactiveuniforms(program, uniformindices, pname); parameters program a webglprogram containing the active uniforms. uniformindices an array of gluint specifying the indices of the active uniforms to query. pname a glenum specifying which information to query. possible values: gl.uniform_type: re
turns an array of glenum indicating the types of the uniforms. gl.uniform_size: re
turns an array of gluint indicating the sizes of the uniforms. ...
...gram containing the active uniforms. uniformindices an array of gluint specifying the indices of the active uniforms to query. pname a glenum specifying which information to query. possible values: gl.uniform_type: re
turns an array of glenum indicating the types of the uniforms. gl.uniform_size: re
turns an array of gluint indicating the sizes of the uniforms. gl.uniform_block_index: re
turns an array of glint indicating the block indices of the uniforms. gl.uniform_offset: re
turns an array of glint indicating the uniform buffer offsets. gl.uniform_array_stride: re
turns an array of glint indicating the strides between the elements. gl.uniform_matrix_stride: re
turns an array of glint indicating the strides between columns of a column-major matrix or a row-major matrix. gl.unif...
...indicating the block indices of the uniforms. gl.uniform_offset: re
turns an array of glint indicating the uniform buffer offsets. gl.uniform_array_stride: re
turns an array of glint indicating the strides between the elements. gl.uniform_matrix_stride: re
turns an array of glint indicating the strides between columns of a column-major matrix or a row-major matrix. gl.uniform_is_row_major: re
turns an array of glboolean indicating whether each of the uniforms is a row-major matrix or not. re
turn value depends on which information is requested using the pname parameter. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); var uniformoffsets = gl.getactiveuniforms(program, uniformindices, gl.uniform_offset); specifications specif...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
the webglrenderingcontext.checkframebufferstatus() method of the webgl api re
turns the completeness status of the webglframebuffer object. syntax glenum gl.checkframebufferstatus(target); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. re
turn value a glenum indicating the completeness status of the framebuffer or 0 if an error occurs. poss...
...bgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. re
turn value a glenum indicating the completeness status of the framebuffer or 0 if an error occurs. possible enum re
turn values: gl.framebuffer_complete: the framebuffer is ready to display. gl.framebuffer_incomplete_attachment: the attachment types are mismatched or not all framebuffer attachment points are framebuffer attachment complete. gl.framebuffer_incomplete_missing_attachment: there is no attachment. gl.framebuffer_incomplete_dimensions: height and width of the attachment are not the same. gl.frameb...
... framebuffer attachment complete. gl.framebuffer_incomplete_missing_attachment: there is no attachment. gl.framebuffer_incomplete_dimensions: height and width of the attachment are not the same. gl.framebuffer_unsupported: the format of the attachment is not supported or if depth and stencil attachments are not the same renderbuffer. ...
...nts are not the same renderbuffer. when using a webgl 2 context, the following values can be re
turned additionally: gl.framebuffer_incomplete_multisample: the values of gl.renderbuffer_samples are different among attached renderbuffers, or are non-zero if the attached images are a mix of renderbuffers and textures. when using the ovr_multiview2 extension, the following value can be re
turned additionally: ext.framebuffer_incomplete_view_targets_ovr: if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ... ...
WebGLRenderingContext.getActiveUniform() - Web APIs
the webglrenderingcontext.getactiveuniform() method of the webgl api re
turns a webglactiveinfo object containing size, type, and name of a uniform attribute. it is generally used when querying unknown uniforms either for debugging or generic library creation. syntax webglactiveinfo webglrenderingcontext.getactiveuniform(program, index); parameters program a webglprogram specifying the webgl shader program from which to obtain the uniform variable's information. index a gluint specifying the index of the uniform attribute to get. this value is an index 0 to n - 1 as re
turned by gl.getprogramparameter(program, gl.active_uniforms). re
turn value a webglactiveinfo object describing the uniform. ...
... parameters program a webglprogram specifying the webgl shader program from which to obtain the uniform variable's information. index a gluint specifying the index of the uniform attribute to get. this value is an index 0 to n - 1 as re
turned by gl.getprogramparameter(program, gl.active_uniforms). re
turn value a webglactiveinfo object describing the uniform. ...
...mpler_2d_array_shadow gl.sampler_cube_shadow gl.int_sampler_2d gl.int_sampler_3d gl.int_sampler_cube gl.int_sampler_2d_array gl.unsigned_int_sampler_2d gl.unsigned_int_sampler_3d gl.unsigned_int_sampler_cube gl.unsigned_int_sampler_2d_array when gl.linkprogram is called, webgl creates a list of active uniforms. these are possible values of the name attribute of re
turn values of getactiveuniform. webgl generates one or more entries in the list depending on the declared type of the uniform in the shader: single basic type: one entry with the name of the uniform. e.g. uniform vec4 a; will result in a. array of basic type: one entry with the name of the uniform suffixed with [0]. e.g. uniform vec4 b[]; will result in b[0]. struct type: one entry for each me...
...s own entries. e.g. uniform struct { float foo; vec4 bar; } d[2]; will result in: d[0].foo d[0].bar d[1].foo d[1].bar uniform blocks: one entry for each member. if the uniform block has an instance name, the block name is prefixed. e.g. uniform block { float foo; }; will result in foo, and uniform block { float bar; } e; will result in block.bar. the size attribute of the re
turn value corresponds to the length of the array for uniforms declared as arrays. otherwise, it is 1 (this includes interface blocks instanced with arrays). exceptions gl.invalid_value is generated if the program webglprogram is invalid (not linked, deleted, etc.). gl.invalid_value is generated if index is not in the range [0, gl.getprogramparameter(program, gl.active_uniforms) - 1]. examples ...
WebGLRenderingContext.getProgramParameter() - Web APIs
the webglrenderingcontext.getprogramparameter() method of the webgl api re
turns information about the given program. syntax any gl.getprogramparameter(program, pname); parameters program a webglprogram to get parameter information from. pname a glenum specifying the information to query. possible values: gl.delete_status: re
turns a glboolean indicating whether or not the program is flagged for deletion. gl.link_status: re
turns a glboolean indicating whether or not the last link operation was successful. gl.validate_status: re
turns a glboolean indicating whether or not the last validation operation was successful. ...
...ecifying the information to query. possible values: gl.delete_status: re
turns a glboolean indicating whether or not the program is flagged for deletion. gl.link_status: re
turns a glboolean indicating whether or not the last link operation was successful. gl.validate_status: re
turns a glboolean indicating whether or not the last validation operation was successful. gl.attached_shaders: re
turns a glint indicating the number of attached shaders to a program. gl.active_attributes: re
turns a glint indicating the number of active attribute variables to a program. gl.active_uniforms: re
turns a glint indicating the number of active uniform variables to a program. when using a webgl 2 context, the following values are available additionally: gl.transform_feedback_buffer_mode: re...
...s a glint indicating the number of attached shaders to a program. gl.active_attributes: re
turns a glint indicating the number of active attribute variables to a program. gl.active_uniforms: re
turns a glint indicating the number of active uniform variables to a program. when using a webgl 2 context, the following values are available additionally: gl.transform_feedback_buffer_mode: re
turns a glenum indicating the buffer mode when transform feedback is active. may be gl.separate_attribs or gl.interleaved_attribs. gl.transform_feedback_varyings: re
turns a glint indicating the number of varying variables to capture in transform feedback mode. ...
...context, the following values are available additionally: gl.transform_feedback_buffer_mode: re
turns a glenum indicating the buffer mode when transform feedback is active. may be gl.separate_attribs or gl.interleaved_attribs. gl.transform_feedback_varyings: re
turns a glint indicating the number of varying variables to capture in transform feedback mode. gl.active_uniform_blocks: re
turns a glint indicating the number of uniform blocks containing active uniforms. re
turn value re
turns the requested program information (as specified with pname). examples gl.getprogramparameter(program, gl.delete_status); specifications specification status comment webgl 1.0the definition of 'getprogramparameter' in that specification. recommendation ...
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
the webglrenderingcontext.getrenderbufferparameter() method of the webgl api re
turns information about the renderbuffer. syntax any gl.getrenderbufferparameter(target, pname); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. pname a glenum specifying the information to query. possible values: gl.renderbuffer_width: re
turns a glint indicating the width of the image of the currently bound renderbuffer. gl.renderbuffer_height: re
turns a glint indicating the height of the image of the currently bound renderbuffer. gl.renderbuffer_internal_format: re
turns a glenum indicating the internal format of the currently bound renderbuffer. the default is gl...
...ossible values: gl.renderbuffer_width: re
turns a glint indicating the width of the image of the currently bound renderbuffer. gl.renderbuffer_height: re
turns a glint indicating the height of the image of the currently bound renderbuffer. gl.renderbuffer_internal_format: re
turns a glenum indicating the internal format of the currently bound renderbuffer. the default is gl.rgba4. possible re
turn values: gl.rgba4: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits. gl.rgb565: 5 red bits, 6 green bits, 5 blue bits. gl.rgb5_a1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.depth_component16: 16 depth bits. gl.stencil_index8: 8 stencil bits. gl.renderbuffer_green_size: re
turns a glint that is the resolution size (in bits) for the green color. gl.r...
...: 4 red bits, 4 green bits, 4 blue bits 4 alpha bits. gl.rgb565: 5 red bits, 6 green bits, 5 blue bits. gl.rgb5_a1: 5 red bits, 5 green bits, 5 blue bits, 1 alpha bit. gl.depth_component16: 16 depth bits. gl.stencil_index8: 8 stencil bits. gl.renderbuffer_green_size: re
turns a glint that is the resolution size (in bits) for the green color. gl.renderbuffer_blue_size: re
turns a glint that is the resolution size (in bits) for the blue color. gl.renderbuffer_red_size: re
turns a glint that is the resolution size (in bits) for the red color. gl.renderbuffer_alpha_size: re
turns a glint that is the resolution size (in bits) for the alpha component. gl.renderbuffer_depth_size: re
turns a glint that is the resolution size (in bits) for the depth component. gl.renderbu...
... resolution size (in bits) for the blue color. gl.renderbuffer_red_size: re
turns a glint that is the resolution size (in bits) for the red color. gl.renderbuffer_alpha_size: re
turns a glint that is the resolution size (in bits) for the alpha component. gl.renderbuffer_depth_size: re
turns a glint that is the resolution size (in bits) for the depth component. gl.renderbuffer_stencil_size: re
turns a glint that is the resolution size (in bits) for the stencil component. when using a webgl 2 context, the following value is available additionally: gl.renderbuffer_samples: re
turns a glint indicating the number of samples of the image of the currently bound renderbuffer. re
turn value depends on the requested information (as specified with pname). either a glint or a gle...
WebGLRenderingContext.getUniform() - Web APIs
the webglrenderingcontext.getuniform() method of the webgl api re
turns the value of a uniform variable at a given location. syntax any gl.getuniform(program, location); parameters program a webglprogram containing the uniform attribute. location a webgluniformlocation object containing the location of the uniform attribute to get. ...
... the webglrenderingcontext.getuniform() method of the webgl api re
turns the value of a uniform variable at a given location. syntax any gl.getuniform(program, location); parameters program a webglprogram containing the uniform attribute. location a webgluniformlocation object containing the location of the uniform attribute to get. ...
... the webglrenderingcontext.getuniform() method of the webgl api re
turns the value of a uniform variable at a given location. syntax any gl.getuniform(program, location); parameters program a webglprogram containing the uniform attribute. location a webgluniformlocation object containing the location of the uniform attribute to get. ...
...rm() method of the webgl api re
turns the value of a uniform variable at a given location. syntax any gl.getuniform(program, location); parameters program a webglprogram containing the uniform attribute. location a webgluniformlocation object containing the location of the uniform attribute to get. ...
Hello GLSL - Web APIs
e = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) re
turn; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader)...
...r(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
... « previousnext » ...
... « previousnext » ...
Hello vertex attributes - Web APIs
script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) re
turn; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader)...
...r(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
... « previousnext » ...
... « previousnext » ...
Raining rectangles - Web APIs
-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); var gl, timer, rainingrect, scoredisplay, missesdisplay; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) re
turn; gl.enable(gl.scissor_test); rainingrect = new rectangle(); timer = settimeout(drawanimation, 17); document.queryselector("canvas") .addeventlistener("click", playerclick, false); var displays = document.queryselectorall("strong"); scoredisplay = displays[0]; missesdisplay = displays[1]; } var score = 0, misses = 0; function drawanimation () { gl.scissor(rainingrect.posi...
... var randnums = getrandomvector(); rect.size = [ 5 + 120 * randnums[0], 5 + 120 * randnums[1] ]; rect.position = [ randnums[2]*(gl.drawingbufferwidth - rect.size[0]), gl.drawingbufferheight ]; rect.velocity = 1.0 + 6.0*math.random(); rect.color = getrandomvector(); gl.clearcolor(rect.color[0], rect.color[1], rect.color[2], 1.0); function getrandomvector() { re
turn [math.random(), math.random(), math.random()]; } } function getrenderingcontext() { var canvas = document.queryselector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to ...
... « previousnext » ...
... « previousnext » ...
Scissor animation - Web APIs
in : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); // variables to hold the webgl context, and the color and // position of animated squares. var gl, color = getrandomcolor(), position; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) re
turn; gl.enable(gl.scissor_test); gl.clearcolor(color[0], color[1], color[2], 1.0); // unlike the browser window, vertical position in webgl is // measured from bottom to top. in here we set the initial // position of the square to be at the top left corner of the // drawing buffer. position = [0, gl.drawingbufferheight]; var button = document.queryselector("button"); var timer; ...
...ition chosen randomly, and vertical // position at the top of the drawing buffer. ...
... « previousnext » ...
... « previousnext » ...
Textures from code - Web APIs
length(fragmentposition); float distancesqrd = distance * distance; gl_fragcolor = vec4( 0.2/distancesqrd, 0.1/distancesqrd, 0.0, 1.0 ); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) re
turn; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader)...
...r(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.queryselector("p").innerhtml = "shader program did not link successfully. ...
... « previousnext » ...
... « previousnext » ...
WebRTC API - Web APIs
rotocol (sctp) transport and also provides a way to access the underlying datagram transport layer security (dtls) transport over which sctp packets for all of an rtcpeerconnection's data channels are sent and received. dictionaries rtcconfiguration used to provide configuration options for an rtcpeerconnection. rtciceserver defines how to connect to a single ice server (such as a stun or
turn server). rtcrtpcontributingsource contains information about a given contributing source (csrc) including the most recent time a packet that the source contributed was played out. events bufferedamountlow the amount of data currently buffered by the data channel—as indicated by its bufferedamount property—has decreased to be at or below the channel's minimum buffered data size, as spe...
...entity and security these apis are used to manage user identity and security, in order to authenticate the user for a connection. rtcidentityprovider enables a user agent is able to request that an identity assertion be generated or validated. rtcidentityassertion represents the identity of the remote peer of the current connection. if no peer has yet been set and verified this interface re
turns null. once set it can't be changed. rtcidentityproviderregistrar registers an identity provider (idp). rtcidentityevent represents an identity assertion generated by an identity provider (idp). this is usually for an rtcpeerconnection. the only event sent with this type is identityresult. rtcidentityerrorevent represents an error associated with the identity provider (idp). this is usually...
.... establishing a connection: the perfect negotiation pattern perfect negotiation is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two. signaling and two-way video calling a tutorial and example which
turns a websocket-based chat system created for a previous example and adds support for opening video calls among participants. the chat server's websocket connection is used for webrtc signaling. codecs used by webrtc a guide to the codecs which webrtc requires browsers to support as well as the optional ones supported by various popular browsers. included is a guide to help you choose the best cod...
...media transport and use of rtp webrtc security architecture transports for rtcweb related supporting protocols interactive connectivity establishment (ice): a protocol for network address translator (nat) traversal for offer/answer protocol session traversal utilities for nat (stun) uri scheme for the session traversal utilities for nat (stun) protocol traversal using relays around nat (
turn) uniform resource identifiers an offer/answer model with session description protocol (sdp) session traversal utilities for nat (stun) extension for third party authorization webrtc statistics webrtc statistics api specifications specification status comment webrtc 1.0: real-time communication between browsers candidate recommendation the initial defini...
Geometry and reference spaces in WebXR - Web APIs
mple the individual xr device is, code written using webxr will still work, within the limitations of the available hardware. regardless of the type of reference space you choose, its type is xrreferencespace or is a type derived from xrreferencespace. the currently available reference space types, which are defined by the xrreferencespacetype enumeration, are shown below. the reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is re
turned for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement t...
... space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
...t which the y coordinate is always 0, unless a floor is otherwise established. these space types are not viable if the rooms have uneven floors or floors whose height above ground level vary, since they don't support the avatar's vertical position changing. the primary reference space types the viewer reference space corresponds to the viewer's position in space; it's used by the xrviewerpose re
turned by the xrframe method getviewerpose(). it's not typically used directly otherwise. the only real exception is that you are likely to use the viewer reference space when performing the xr scene inline within web content. the local reference space is typically used to describe a relatively small area, such as a single room. it is not only always available when using an immersive session mode (im...
...ew location. for a more detailed look at how to use reference spaces to manage the player's viewpoint, see the article in the case of our game avatar example, it's rare for an avatar (or any other moving creature or machine) to be a simple blob sliding around the world. they usually have additional form, as well as internal movement, such as moving legs, arms that swing as they walk, a head that
turns or bobs, weapons that move around, and so forth. bring these to life using standard webgl techniques and a positioning matrix or xrrigidtransform to shift the objects to the correct position relative to the effective origin. device limitations on reference spaces some xr devices simply can't be made to support a given experience, despite the efforts the api goes to to make up for any missing c...
Migrating from webkitAudioContext - Web APIs
the latter version 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 ...
... 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 of audioparam.settargetvalueattime the ...
... start, other arguments are // the argument to the |start()| method of the audiobuffersourcenode. function startsource() { var src = arguments[0]; var startargs = array.prototype.slice.call(arguments, 1); src.onended = function() { sources.splice(sources.indexof(src), 1); } sources.push(src); src.start.apply(src, startargs); } function activesources() { re
turn sources.length; } var src0 = context.createbuffersource(); var src0 = context.createbuffersource(); // set buffers and other parameters... startsource(src0, 0); startsource(src1, 0); // some time later, query the number of sources... console.log(activesources()); renaming of wavetable the wavetable interface has been renamed to periodicwave. here is how you can port old code u...
...de, these values are 0 and 1, respectively. note that these bounds are not enforced by the engine, and are merely used for informational purposes. as an example, it's perfectly valid to set a gain value to 2, or even -1. in order to find out these nominal values, you can consult the specification. the units attribute as implemented in webkitaudiocontext implementations is unused, and always re
turns 0. there is no reason why you should need this attribute. removal of mediaelementaudiosourcenode.mediaelement the mediaelement attribute of mediaelementaudiosourcenode has been removed. you can keep a reference to the media element used to create this node if you need to access it later. removal of mediastreamaudiosourcenode.mediastream the mediastream attribute of mediastreamaudiosourcen...
Using IIR filters - Web APIs
response (iir) filter; this type of filter can be used to implement tone control devices and graphic equalizers, and the filter response parameters can be specified, so that it can be tuned as needed. this article looks at how to implement one, and use it in a simple example. demo our simple example for this guide provides a play/pause button that starts and pauses audio play, and a toggle that
turns an iir filter on and off, altering the tone of the sound. it also provides a canvas on which is drawn the frequency response of the audio, so you can see what effect the iir filter has. you can check out the full demo here on codepen. also see the source code on github. it includes some different coefficient values for different lowpass frequencies — you can change the value of the filternu...
... node: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = audioctx.createiirfilter(feedforward, feedback); we need a sound source to play. we set this up using a custom function, playsoundnode(), which creates a buffer source from an existing audiobuffer, attaches it to the default destination, starts it playing, and re
turns it: function playsourcenode(audiocontext, audiobuffer) { const soundsource = audiocontext.createbuffersource(); soundsource.buffer = audiobuffer; soundsource.connect(audiocontext.destination); soundsource.start(); re
turn soundsource; } this function is called when the play button is pressed. the play button html looks like this: <button class="button-play" role="switch" data-playing...
...n the play button is pressed. the play button html looks like this: <button class="button-play" role="switch" data-playing="false" aria-pressed="false">play</button> and the click event listener starts like so: playbutton.addeventlistener('click', function() { if (this.dataset.playing === 'false') { srcnode = playsourcenode(audioctx, sample); ... }, false); the toggle that
turns the iir filter on and off is set up in the similar way. first, the html: <button class="button-filter" role="switch" data-filteron="false" aria-pressed="false" aria-describedby="label" disabled></button> the filter button's click handler then connects the iirfilter up to the graph, between the source and the detination: filterbutton.addeventlistener('click', function() { if (this.dataset.
...ta. all three of these have to be of type float32array and all be of the same size. // arrays for our frequency response const totalarrayitems = 30; let myfrequencyarray = new float32array(totalarrayitems); let magresponseoutput = new float32array(totalarrayitems); let phaseresponseoutput = new float32array(totalarrayitems); let's fill our first array with frequency values we want data to be re
turned on: myfrequencyarray = myfrequencyarray.map(function(item, index) { re
turn math.pow(1.4, index); }); we could go for a linear approach, but it's far better when working with frequencies to take a log approach, so let's fill our array with frequency values that get larger further on in the array items. now let's get our response data: iirfilter.getfrequencyresponse(myfrequencyarray, mag...
Using the Web Storage API - Web APIs
alstorage and sessionstorage properties are members of) — invoking one of these will create an instance of the storage object, through which data items can be set, retrieved, and removed. a different storage object is used for the sessionstorage and localstorage for each origin — they function and are controlled separately. so, for example, initially calling localstorage on a document will re
turn a storage object; calling sessionstorage on a document will re
turn a different storage object. both of these can be manipulated in the same way, but separately. feature-detecting localstorage to be able to use localstorage, we should first verify that it is supported and available in the current browsing session. testing for availability note: this api is available in current versions of all...
...rage space, but storage is actually available. our feature detection should take these scenarios into account. ...
...ble. our feature detection should take these scenarios into account. ...
...ustomization values to the storage. if there are already values there, we run setstyles() to update the page styling with the stored values. note: you could also use storage.length to test whether the storage object is empty or not. getting values from storage as noted above, values can be retrieved from storage using storage.getitem(). this takes the key of the data item as an argument, and re
turns the data value. for example: function setstyles() { var currentcolor = localstorage.getitem('bgcolor'); var currentfont = localstorage.getitem('font'); var currentimage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style...
Functions and classes available to Web Workers - Web APIs
y 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, and use associated functionality. 40 (40) no support (yes) no support textencoder and textdecoder create and re
turn a new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings. 20 (20) no support no support no support url workers can use the static methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker. workers can also create a new url using the url() constructor and call any normal method on th...
...ew textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings. 20 (20) no support no support no support url workers can use the static methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker. workers can also create a new url using the url() constructor and call any normal method on the re
turned object. 21 (21) and 26 (26) for url() constructor no support no support no support webgl with offscreencanvas webgl (web graphics library) is a javascript api for rendering interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. in about:config, set gfx.offscreencanvas.enabled to true. ...
...pport no support webgl with offscreencanvas webgl (web graphics library) is a javascript api for rendering interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. in about:config, set gfx.offscreencanvas.enabled to true. no support no support no support websocket creates and re
turns a new websocket object; this mimics the behavior of the standard websocket() constructor. 37 (37) 11.0 (yes) (yes) worker creates a new worker. yes, workers can spawn more workers. 3.5 (1.9.1) 10.0 enabled since chrome 69 no support workerglobalscope the global scope of workers. this objects defines worker-specific functions. (yes) 10.0 (...
...s. 3.6 (1.9.2) 10.0 (yes) (yes) workernavigator the subset of the navigator interface available to workers. basic implementation (yes) appcodename, product, taintenabled(): 28 (28) online: 29 (29) navigatorlanguage: (yes) appname, appversion, online, platform, useragent: 10.0 other: no support (yes) (yes) xmlhttprequest creates and re
turns a new xmlhttprequest object; this mimics the behavior of the standard xmlhttprequest() constructor. note that the responsexml and channel attributes on xmlhttprequest always re
turn null. basic: 3.5 (1.9.1) response and responsetype are available since 10 (10) timeout and ontimeout are available since 13 (13) (yes) (yes) (yes) ...
Window.getSelection() - Web APIs
the window.getselection() method re
turns a selection object representing the range of text selected by the user or the current position of the caret. syntax selection = window.getselection(); re
turn value a selection object. when cast to string, either by appending an empty string ("") or using selection.tostring(), this object re
turns the text selected. when called on an <iframe> that is not displayed (eg. where display: none is set) firefox will re
turn null, whereas other browsers will re
turn a selection object with selection.type set to none. examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object...
...ype set to none. examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring() method is called and the re
turned value is passed to the function. this can make the object appear to be a string when used with other functions when it is really an object with properties and methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or method such as length or substr directly on a selection object will ...
... a string when used with other functions when it is really an object with properties and methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or method such as length or substr directly on a selection object will result in an error if it does not have that property or method and may re
turn unexpected results if it does. to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object. selectedtext is a string (selected text). related objects you can call document.getselection(), which works identically to window.getselection(). it is worth noting that currently getselection() doesn't work on the ...
...tically to window.getselection(). it is worth noting that currently getselection() doesn't work on the content of <textarea> and <input> elements in firefox, edge (legacy) and internet explorer. htmlinputelement.setselectionrange() or the selectionstart and selectionend properties could be used to work around this. notice also the difference between selection and focus. document.activeelement re
turns the focused element. specifications specification status comment selection apithe definition of 'window.getselection()' in that specification. working draft new spec. ...
Window.innerWidth - Web APIs
the interior height of the window—the height of the layout viewport—can be obtained from the innerheight property. syntax let intviewportwidth = window.innerwidth; value an integer value indicating the width of the window's layout viewport in pixels. this property is read-only, and has no default value. to change the window's width, use one of the window methods for resizing windows, such as resizeby() or resizeto(). ...
...e the window's width, use one of the window methods for resizing windows, such as resizeby() or resizeto(). usage notes if you need to obtain the width of the window minus the scrollbar and borders, use the root <html> element's clientwidth property instead. the innerwidth property is available on any window or object that behaves like a window, such as a frame or tab. ...
...zeby() or resizeto(). usage notes if you need to obtain the width of the window minus the scrollbar and borders, use the root <html> element's clientwidth property instead. the innerwidth property is available on any window or object that behaves like a window, such as a frame or tab. ...
...rders, use the root <html> element's clientwidth property instead. the innerwidth property is available on any window or object that behaves like a window, such as a frame or tab. example // this will re
turn the width of the viewport var intframewidth = window.innerwidth; // this will re
turn the width of the frame viewport within a frameset var intframewidth = self.innerwidth; // this will re
turn the width of the viewport of the closest frameset var intframesetwidth = parent.innerwidth; // this will re
turn the width of the viewport of the outermost frameset var intouterframesetwidth = top.innerwidth; specification specification status comment css object model (cssom) view modulethe definition of 'window.innerwidth' in that specification. working draft ...
window.location - Web APIs
though window.location is a read-only location object, you can also assign a domstring to it. this means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'. see location for all available properties. ...
...nullam ultrices dolor ac dolor imperdiet ullamcorper. suspendisse quam libero, luctus auctor mollis sed, m...
...th an animated page scroll: var showbookmark = (function () { var _usehash, _scrollx, _scrolly, _nodex, _nodey, _itframe, _scrollid = -1, _bookmark, /* * nduration: the duration in milliseconds of each frame * nframes: number of frames for each scroll */ nduration = 200, nframes = 10; function _next () { if (_itframe > nframes) { clearinterval(_scrollid); _scrollid = -1; re
turn; } _isbot = true; document.documentelement.scrolltop = math.round(_scrolly + (_nodey - _scrolly) * _itframe / nframes); document.documentelement.scrollleft = math.round(_scrollx + (_nodex - _scrollx) * _itframe / nframes); if (_usehash && _itframe === nframes) { location.hash = _bookmark; } _itframe++; } function _chkowner () { if (_isbot) { _isbot = false; re
turn; } if (_scrol...
...if (_usehash && _itframe === nframes) { location.hash = _bookmark; } _itframe++; } function _chkowner () { if (_isbot) { _isbot = false; re
turn; } if (_scrollid > -1) { clearinterval(_scrollid); _scrollid = -1; } } if (window.addeventlistener) { window.addeventlistener("scroll", _chkowner, false); } else if (window.attachevent) { window.attachevent("onscroll", _chkowner); } re
turn function (sbookmark, busehash) { var onode = document.queryselector(sbookmark); _scrolly = document.documentelement.scrolltop; _scrollx = document.documentelement.scrollleft; _bookmark = sbookmark; _usehash = busehash === true; _nodex = onode.offsetleft; _nodey = onode.offsettop; _itframe = 1; if (_scrollid === -1) { _scrollid = setinterval(_next, math.round(nduration / nf...
Window.openDialog() - Web APIs
fferently. the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments. they may be referenced in the javascript of the window at any time, including during the execution of a load handler. these parameters may be used, then, to pass arguments to and from the dialog window. the call to opendialog() re
turns immediately. if you want the call to block until the user has closed the dialog, supply modal as a windowfeatures parameter. note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. syntax newwindow = opendialog(url, name, features, arg1, arg2, ...) newwindow the opened window url the url to be loaded in the newly opened windo...
...ation. features see window.open() for details. arg1, arg2, ... the arguments to be passed to the new window (optional). example var win = opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); notes new features all - initially activates (or deactivates ("all=no")) all chrome (except the behavior flags chrome, dialog and modal). these can be overridden (so "menubar=no,all"
turns on all chrome except the menubar.) this feature is explicitly ignored by window.open(). window.opendialog() finds it useful because of its different default assumptions. default behavior the chrome and dialog features are always assumed on, unless explicitly
turned off ("chrome=no"). opendialog() treats the absence of the features parameter the same way window.open() does; that is, an empty st...
... parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window. to access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code. (another example). re
turning values from the dialog since window.close() erases all properties associated with the dialog window (i.e. the variables specified in the javascript code which gets loaded from the dialog), it is not possible to pass re
turn values back past the close operation using globals (or any other constructs). to be able to pass values back to the caller, you have to supply some object via the extra pa...
...ed in the javascript code which gets loaded from the dialog), it is not possible to pass re
turn values back past the close operation using globals (or any other constructs). to be able to pass values back to the caller, you have to supply some object via the extra parameters. you can then access this object from within the dialog code and set properties on it, containing the values you want to re
turn or preserve past the window.close() operation. var retvals = { address: null, delivery: null }; opendialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retvals); if you set the properties of the retvals object in the dialog code as described below, you can now access them via the retvals array after the opendialog() call re
turns. inside the dialog code, you can set the pro...
Window.prompt() - Web APIs
esult = window.prompt(message, default); parameters message optional a string of text to display to the user. can be omitted if there is nothing to show in the prompt window. default optional a string containing the default value displayed in the text input field. note that in internet explorer 7 and 8, if you do not provide this parameter, the string "undefined" is the default value. re
turn value a string containing the text entered by the user, or null. example let sign = prompt("what's your sign?"); if (sign.tolowercase() == "scorpio") { alert("wow! i'm a scorpio too!"); } // there are many ways to use the prompt feature sign = window.prompt(); // open the blank prompt window sign = prompt(); // open the blank prompt window sign = window.prompt('are you feeling lucky...
... the following text is shar...
... prompt window sign = window.prompt('are you feeling lucky'); // open the window with text "are you feeling lucky" sign = window.prompt('are you feeling lucky', 'sure'); // open the window with text "are you feeling lucky" and default value "sure" when the user clicks the ok button, text entered in the input field is re
turned. if the user clicks ok without entering any text, an empty string is re
turned. if the user clicks the cancel button, this function re
turns null. the above prompt appears as follows (in chrome on os x): notes a prompt dialog contains a single-line textbox, a cancel button, and an ok button, and re
turns the (possibly empty) text the user entered into that textbox. the following text is shared between this article, dom:window.confirm and dom:window.alert dialog boxes ...
...ull support 12firefox full support 1ie full support 4notes full support 4notes notes this function has no effect in the modern ui/metro version of internet explorer for windows 8. it does not display a prompt to the user, and always re
turns undefined. it is not clear whether this is a bug or intended behavior. desktop versions of ie do implement this function.opera full support 3notes full support 3notes notes starting with opera 33, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari ...
WindowOrWorkerGlobalScope - Web APIs
rfaces can, of course, add more features in addition to the ones listed below. note: windoworworkerglobalscope is a mixin and not an interface; you can't actually create an object of type windoworworkerglobalscope. properties these properties are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.caches read only re
turns 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.crossoriginisolated read only re
turns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call. windoworworkerglobalscope.indexeddb read only ...
...as storing assets for offline use, and generating custom responses to requests. windoworworkerglobalscope.crossoriginisolated read only re
turns 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; re
turns an idbfactory object. windoworworkerglobalscope.issecurecontext read only re
turns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only re
turns the origin of the global scope, serialized as a string. methods these methods are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobals...
...encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and re
turns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code compl...
...n imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being re
turned to a javascript caller, but before handling callbacks and other tasks. this lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. window...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
the writablestreamdefaultwriter() constructor creates a new writablestreamdefaultwriter object instance. note: you generally wouldn't use this constructor manually; instead, you'd use the writablestream.getwriter() method. syntax var writablestreamdefaultwriter = new writablestreamdefaultwriter(stream); parameters stream the writablestream to be written to. re
turn value an instance of the writablestreamdefaultwriter object. exceptions typeerror the provided stream value is not a writablestream, or it is locked to another writer already. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this fun...
...typeerror the provided stream value is not a writablestream, or it is locked to another writer already. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const...
...d streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { re
turn defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.lo...
...{ defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { re
turn new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, ...
WritableStreamDefaultWriter.close() - Web APIs
the close() method of the writablestreamdefaultwriter interface closes the associated writable stream. the underlying sink will finish processing any previously-written chunks, before invoking the close behavior. during this time any further attempts to write will fail (without erroring the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. re
turn value a promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. ...
...uring the process. exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const...
...d streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { re
turn defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.lo...
...{ defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { re
turn new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, ...
WritableStreamDefaultWriter.write() - Web APIs
the write() property of the writablestreamdefaultwriter interface writes a passed chunk of data to a writablestream and its underlying sink, then re
turns a promise that resolves to indicate the success or failure of the write operation. note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. syntax var promise = writablestreamdefaultwriter.write(chunk); parameters chunk a block of binary data to pass to the writablestream. re
turn value a promise, which fulfills with the undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. exceptions typeerror the target stream is...
...ted. exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which re
turns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() re
turn promises that are processed to deal with success or failure of chunks and streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const...
...d streams. const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { re
turn defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.lo...
...{ defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { re
turn new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, ...
HTML in XMLHttpRequest - Web APIs
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. ...
...en 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) re
turn false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { re
turn true; } re
turn 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...
...ame time. thus, to detect html support, a test html file is needed on the server. ...
...(new regexp("(?:(?:.(?!<\\s*" + aexec[1] + "[^>]*[>]))*.?<\\s*" + aexec[1] + "[^>]*[>](?:.(?!<\\s*\/\\s*" + aexec[1] + "\\s*>))*.?<\\s*\/\\s*" + aexec[1] + "\\s*>)*(?:.(?!<\\s*\/\\s*" + aexec[1] + "\\s*>))*.?", "i")).exec(ssrc.slice(ssrc.indexof(aexec[0]) + aexec[0].length)) || "" : ""; } var oreq = new xmlhttprequest(); oreq.open("get", "yourpage.html", true); oreq.onload = function () ...
XPathResult.booleanValue - Web APIs
exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. ...
XPathResult.numberValue - Web APIs
exceptions type_err in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. ...
... exceptions type_err in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. ...
... exceptions type_err in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. ...
... exceptions type_err in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. ...
XPathResult.singleNodeValue - Web APIs
exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpathexception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. ...
... exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpathexception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. ...
... exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpathexception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. ...
... exceptions type_err in case xpathresult.resulttype is not any_unordered_node_type or first_ordered_node_type, an xpathexception of type type_err is thrown. example the following example shows the use of the singlenodevalue property. ...
XPathResult.stringValue - Web APIs
exceptions type_err in case xpathresult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. ...
... exceptions type_err in case xpathresult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. ...
XRInputSource.targetRaySpace - Web APIs
its native origin tracks the position of the origin point of the target ray, and its orientation indicates the orientation of the controller device itself. these values, interpreted in the context of the input source's targetraymode, can be used both to fully interpret the device as an input source. <<<--- needs diagram showing targetrayspace relative to gripspace and world space --->>> to obtain an xrspace representing the input controller's position and orientation in virtual space, use the gripspace property. ...
...btain an xrspace representing the input controller's position and orientation in virtual space, use the gripspace property. syntax let targetrayspace = xrinputsource.targetrayspace; value an xrspace object—typically an xrreferencespace or xrboundedreferencespace—which represents the position and orientation of the input controller's target ray in virtual space. the native origin of the re
turned xrspace is located at the point from which the target ray is emitted, and the orientation of the space indicates the direction in which the target ray is pointing. usage notes all input sources—regardless of their targetraymode—have a valid targetrayspace. the exact meaning of this space varies, however, depending on the mode: every gaze input (targetraymode value of gaze), shares the ...
...nting. usage notes all input sources—regardless of their targetraymode—have a valid targetrayspace. the exact meaning of this space varies, however, depending on the mode: every gaze input (targetraymode value of gaze), shares the same xrspace object as their target ray space, since the gaze input comes from the viewer's head. this shared space represents the same location as the space re
turned by the xrsession method requestreferencespace(), but is maintained as a different object to allow for future enhancements to the api. the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame...
...ed as a different object to allow for future enhancements to the api. the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe method getpose() method, then use the re
turned xrpose object's transform to gather the spatial information you need. example this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a target ray outward from the user. for each such input, this example looks for inputs whose targetraymode...
XRWebGLLayer - Web APIs
splay on the device. in particular, it provides access to the webgl framebuffer and viewport to ease access to the context. although xrwebgllayer is currently the only type of framebuffer layer supported by webgl, it's entirely possible that future updates to the webxr specification may allow for other layer types and corresponding image sources. ...
...and re
turns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context. properties antialias read only a boolean value indicating whether or not the webgl context's framebuffer supports anti-aliasing. the specific type of anti-aliasing is determined by the user agent. framebuffer read only re
turns a webglframebuffer suitable for passing into the bindframebuffer() method. framebufferwidth read only re
turns the width of the xrwebgllayer's framebuffer. framebufferheight read only re
turns the height of the layer's framebuffer. ignoredepthvalues read only a boolean which indicates whether or not the webxr compositor should make use of the contents of the layer's depth buffer while com...
... bindframebuffer() method. framebufferwidth read only re
turns the width of the xrwebgllayer's framebuffer. framebufferheight read only re
turns the height of the layer's framebuffer. ignoredepthvalues read only a boolean which indicates whether or not the webxr compositor should make use of the contents of the layer's depth buffer while compositing the scene. methods getviewport() re
turns a new xrviewport instance representing the position, width, and height to which the webgl context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents. in this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer. static meth...
... position, width, and height to which the webgl context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents. in this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer. static methods getnativeframebufferscalefactor() re
turns the scaling factor that can be used to scale the resolution of the recommended webgl framebuffer resolution to the rendering device's native resolution. examples binding the layer to a webgl context this snippet, taken from drawing a frame in movement, orientation, and motion: a webxr example, shows how the xrwebgllayer is obtained from the xrsession object's rendering state and is then boun...
Architecture - Accessibility
examples of objects not embedded in text are the child options in list boxes and combo boxes. otherwise, use iahyperlink::getstartindex() to find the index in parent. in firefox, the results of getendindex will always be the startindex + 1, because links are always just represented by a single embedded object character (c) to get the next char fom a given of...
...herwise, continue processing with offset = the index at the end of the line. if the character at the offset is an embed, proceed to its corresponding accessible and recurse on the first character until a non-embed is found. otherwise, the offset marks the start of a new line. navigating to the next word follows a similar pattern. navigating previous requires re
turning to the embed character in the parent accessible when the point of regard reaches the end of text in the corresponding child accessible for the embed. see http://svn.gnome.org/viewcvs/lsr/tru...py?view=markup for a bsd implementation. (e) to grab a subtree of content: although under windows text content is still exposed in leaf nodes of role_text, it is no longer necessary to visit those nodes.
...ne. you can test this in a given editor by pressing the end key on a line, to see whether the caret is shown past the end of the line. to doublecheck, hit the delete key and see if it removes the first char of the next line. ...
...the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the mozilla document hierarchy are in the original design document for newatk. ...
@supports - CSS: Cascading Style Sheets
s condition consists of one or more name-value pairs combined by conjunctions (and), disjunctions (or), and/or negations (not). precedence of operators can be defined with parentheses. declaration syntax the most basic supports condition is a simple declaration (a property name followed by a value, separated by a colon). the declaration must be surrounded by parentheses. the following example re
turns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} function syntax the second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized. selector() tests if the browser supports the tested selector syntax. the following example retu...
...he functions themselves are still being standardized. selector() tests if the browser supports the tested selector syntax. the following example re
turns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one. the following example re
turns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity. the following examples are both valid: @supports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} note: there is n...
...pports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} note: there is no need to enclose the not operator between two parentheses at the top level. to combine it with other operators, like and and or, the parentheses are required. the and operator the and operator creates a new expression from the conjunction of two shorter expressions. it re
turns true only if both of the shorter expressions are also true. the following example re
turns true if and only if the two shorter expressions are simultaneously true: @supports (display: table-cell) and (display: list-item) {} multiple conjunctions can be juxtaposed without the need of more parentheses. the following are both equivalent: @supports (display: table-cell) and (display: list-item) an...
...tem) {} multiple conjunctions can be juxtaposed without the need of more parentheses. the following are both equivalent: @supports (display: table-cell) and (display: list-item) and (display:run-in) {} @supports (display: table-cell) and ((display: list-item) and (display:run-in)) {} the or operator the or operator creates a new expression from the disjunction of two shorter expressions. it re
turns true if one or both of the shorter expressions is also true. the following example re
turns true if at least one of the two shorter expressions is true: @supports (transform-style: preserve) or (-moz-transform-style: preserve) {} multiple disjunctions can be juxtaposed without the need of more parentheses. the following are both equivalent: @supports (transform-style: preserve) or (-moz-transf...
Using media queries - CSS: Cascading Style Sheets
sing logical operators. media queries are case-insensitive. a media query computes to true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as true. queries involving unknown media types are always false. note: a style sheet with a media query attached to its <link> tag will still download even if the query re
turns false. nevertheless, its contents will not apply unless and until the result of the query changes to true. media types media types describe the general category of a device. except when using the not or only logical operators, the media type is optional and the all type will be implied. all suitable for all devices. print intended for paged material and documents viewed on a screen in p...
...h of the viewport including width of scrollbar logical operators the logical operators not, and, and only can be used to compose a complex media query. you can also combine multiple media queries into a single rule by separating them with commas. and the and operator is used for combining multiple media features together into a single media query, requiring each chained feature to re
turn true in order for the query to be true. it is also used for joining media features with media types. not the not operator is used to negate a media query, re
turning true if the query would otherwise re
turn false. if present in a comma-separated list of queries, it will only negate the specific query to which it is applied. if you use the not operator, you must also specify a media type. note:...
...0px) simply as screen, ignoring the remainder of the query, and applying its styles on all screens. if you use the only operator, you must also specify a media type. , (comma) commas are used to combine multiple media queries into a single rule. each query in a comma-separated list is treated separately from the others. thus, if any of the queries in a list is true, the entire media statement re
turns true. in other words, lists behave like a logical or operator. targeting media types media types describe the general category of a given device. although websites are commonly designed with screens in mind, you may want to create styles that target special devices such as printers or audio-based screenreaders. for example, this css targets printers: @media print { ... } you can also target ...
...ice matches any one of various media types, features, or states. for instance, the following rule will apply its styles if the user's device has either a minimum height of 680px or is a screen device in portrait mode: @media (min-height: 680px), screen and (orientation: portrait) { ... } taking the above example, if the user had a printer with a page height of 800px, the media statement would re
turn true because the first query would apply. likewise, if the user were on a smartphone in portrait mode with a viewport height of 480px, the second query would apply and the media statement would still re
turn true. inverting a query's meaning the not keyword inverts the meaning of an entire media query. it will only negate the specific media query it is applied to. (thus, it will not apply to eve...
attr() - CSS: Cascading Style Sheets
used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. the attr() css function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. it can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is re
turned. /* simple usage */ attr(data-count); attr(title); /* with type */ attr(src url); attr(data-count number); attr(data-width px); /* with fallback */ attr(data-count number, 0); attr(src url, ""); attr(data-width px, inherit); attr(data-something, "default"); syntax values attribute-name is the name of an attribute on the html element referenced in the css. <type-or-unit> is a keywo...
...the given attribute is invalid, the attr() expression will be invalid too. if omitted, it defaults to string. the list of valid values are: keyword associated type comment default value string <string> the attribute value is treated as a css <string>. it is not reparsed, and in particular the characters are used as-is instead of css escapes being
turned into different characters. an empty string. color <color> the attribute value is parsed as a hash (3- or 6-value hash) or a keyword. it must be a valid css <string> value. leading and trailing spaces are stripped. currentcolor url <url> the attribute value is parsed as a string that is used inside a css url() function. relative url a...
... an invalid value. if not set, css will use the default value defined for each <type-or-unit>. ...
...on. editor's draft changed it to work like var(). property values involving attr() are valid at parse time, and the validation of the attribute value is deferred to computed value time. css values and units module level 3the definition of 'attr()' in that specification. candidate recommendation added two optional parameters; can be used on all properties; may re
turn values other than <string>. these changes are experimental and may be dropped during the cr phase if browser support is too small. css level 2 (revision 1)the definition of 'attr()' in that specification. recommendation limited to the content property; always re
turns a <string>. ...
transition-delay - CSS: Cascading Style Sheets
ion: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backgro...
...ction: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:1s; transition-timing-function: linear; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backgrou...
...ction: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:2s; transition-timing-function: linear; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backgrou...
... working draft initial definition ...
transition-duration - CSS: Cascading Style Sheets
ut; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration:0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backg...
...n-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:1s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backg...
...n-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:2s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } re
turn el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height backg...
... working draft initial definition ...
Making content editable - Developer guides
) or affect an entire line (indenting). when using contenteditable, calling execcommand() will affect the currently active editable element. differences in markup generation use of contenteditable across different browsers has been painful for a long time because of the differences in generated markup between browsers. for example, even something as simple as what happens when you press enter/re
turn to create a new line of text inside an editable element was handled differently across the major browsers (firefox inserted <br> elements, ie/opera used <p>, chrome/safari used <div>). fortunately, in modern browsers things are somewhat more consistent. as of firefox 60, firefox will be updated to wrap the separate lines in <div> elements, matching the behavior of chrome, modern opera, edge, and...
...e="text/javascript"> var odoc, sdeftxt; function initdoc() { odoc = document.getelementbyid("textbox"); sdeftxt = odoc.innerhtml; if (document.compform.switchmode.checked) { setdocmode(true); } } function formatdoc(scmd, svalue) { if (validatemode()) { document.execcommand(scmd, false, svalue); odoc.focus(); } } function validatemode() { if (!document.compform.switchmode.checked) { re
turn true ; } alert("uncheck \"show html\"."); odoc.focus(); re
turn false; } function setdocmode(btosource) { var ocontent; if (btosource) { ocontent = document.createtextnode(odoc.innerhtml); odoc.innerhtml = ""; var opre = document.createelement("pre"); odoc.contenteditable = false; opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent)...
...document.execcommand("defaultparagraphseparator", false, "div"); } else { if (document.all) { odoc.innerhtml = odoc.innertext; } else { ocontent = document.createrange(); ocontent.selectnodecontents(odoc.firstchild); odoc.innerhtml = ocontent.tostring(); } odoc.contenteditable = true; } odoc.focus(); } function printdoc() { if (!validatemode()) { re
turn; } var oprntwin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oprntwin.document.open(); oprntwin.document.write("<!doctype html><html><head><title>print<\/title><\/head><body onload=\"print();\">" + odoc.innerhtml + "<\/body><\/html>"); oprntwin.document.close(); } </script> <style type="text/css"> .intlink { cursor: ...
...box { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform" method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;re
turn true;}re
turn false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.selectedindex=0;"> <option selected>- formatting -</option> <option value="h1">title 1 <h1></option> <option value="h2">title 2 <h2></option> <option value="h3">title 3 <h3></option> <option value="h4">title 4 <h4></opt...
<input type="tel"> - HTML: Hypertext Markup Language
include other explanatory text nearby. see pattern validation below for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...d attributes are available to telephone number input fields. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect whether or not to allow autocorrect while editing this input field. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses the enter or re
turn key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. firefox for android only. autocorrect a safari extension, the autocorrect attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. permitted values are: on enable automatic correction of typos, as well as p...
...ile the user is editing this field. permitted values are: on enable automatic correction of typos, as well as processing of text substitutions if any are configured. off disable automatic correction and text substitutions. mozactionhint a mozilla extension, supported by firefox for android, which provides a hint as to what sort of action will be taken if the user presses the enter or re
turn key while editing the field. this information is used to decide what kind of label to use on the enter key on the virtual keyboard. note: this has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. to see the status of the change being implemented in firefox, see bug 1490661. permitted values are: go, done, next, search, and send. the browser decides, u...
...g suggested values taking it a step farther, you can provide a list of default phone number values from which the user can select. to do this, use the list attribute. this doesn't limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. this also offers hints to autocomplete. the list attribute specifies the id of a <datalist> element, which in
turn contains one <option> element per suggested value; each option's value is the corresponding suggested value for the telephone number entry box. <label for="telno">phone number: </label> <input id="telno" name="telno" type="tel" list="defaulttels"> <datalist id="defaulttels"> <option value="111-1111-1111"> <option value="122-2222-2222"> <option value="333-3333-3333"> <option value="344-4...
<input type="text"> - HTML: Hypertext Markup Language
de other explanatory text nearby. see specifying a pattern for further details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...lcheck are: false disable spell checking for this element. true enable spell checking for this element. "" (empty string) or no value follow the element's default behavior for spell checking. this may be based upon a parent's spellcheck setting or other factors. an input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. the value re
turned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. non-standard attributes the following non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indic...
...lowing non-standard attributes are also available on some browsers. as a general rule, you should avoid using them unless it can't be helped. attribute description autocorrect a string indicating whether or not autocorrect is on or off. safari only. mozactionhint a string indicating the type of action that will be taken when the user presses the enter or re
turn key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. firefox for android only. autocorrect a safari extension, the autocorrect attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. permitted values are: on enable automatic correction of typos, as well as ...
...e the user is editing this field. permitted values are: on enable automatic correction of typos, as well as processing of text substitutions if any are configured. off disable automatic correction and text substitutions. mozactionhint a mozilla extension, supported by firefox for android, which provides a hint as to what sort of action will be taken if the user presses the enter or re
turn key while editing the field. this information is used to decide what kind of label to use on the enter key on the virtual keyboard. note: this has been standardized as the global attribute enterkeyhint, but is not yet widely implemented. to see the status of the change being implemented in firefox, see bug 1490661. permitted values are: go, done, next, search, and send. the browser decides, u...
Content-Location - HTTP
this distinction may seem abstract without examples. ...
...icate the url of a resource transmitted as the result of content negotiation. location and content-location are different. location indicates the url of a redirect, while content-location indicates the direct url to use to access the resource, without further content negotiation in the future. location is a header associated with the response, while content-location is associated with the data re
turned. this distinction may seem abstract without examples. header type entity header forbidden header name no syntax content-location: <url> directives <url> a relative (to the request url) or absolute url. examples requesting data from a server in different formats let's say a site's api can re
turn data in json, xml, or csv formats. if the url for a partic...
...r type entity header forbidden header name no syntax content-location: <url> directives <url> a relative (to the request url) or absolute url. examples requesting data from a server in different formats let's say a site's api can re
turn data in json, xml, or csv formats. ...
...ion the next time it requests that document. the server could also consider other content negotiation headers, such as accept-language. pointing to a new document (http 201 created) say you're creating a new blog post through a site's api: put /new/post host: example.com content-type: text/markdown # my first blog post! i made this through `example.com`'s api. i hope it worked. the site re
turns a generic success message confirming the post was published. the server specifies where the new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success! indicating the url of a transaction's result say you have a <form> for sending money to another user of a site. <form action="/send-payment" method="post...
HTTP response status codes - HTTP
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 re
turned 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 or backups of another resource. except for that specific case, the "200 ok" response is preferred to this status. 204 no content there is no content to send for this request, but the headers may be useful. the user-agent may upda...
...hide the existence of a resource from an unauthorized client. this response code is probably the most famous one due to its frequent occurrence on the web. 405 method not allowed the request method is known by the server but has been disabled and cannot be used. for example, an api may forbid delete-ing a resource. the two mandatory methods, get and head, must never be disabled and should not re
turn this error code. 406 not acceptable this response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent. 407 proxy authentication required this is similar to 401 but authentication is needed to be done by a proxy. 408 request timeout this response is sent on an idle connection by some s...
... deleted with this status code. 411 length required server rejected the request because the content-length header field is not defined and the server requires it. 412 precondition failed the client has indicated preconditions in its headers which the server does not meet. 413 payload too large request entity is larger than limits defined by server; the server might close the connection or re
turn an retry-after header field. 414 uri too long the uri requested by the client is longer than the server is willing to interpret. 415 unsupported media type the media format of the requested data is not supported by the server, so the server is rejecting the request. 416 range not satisfiable the range specified by the range header field in the request can't be fulfilled; it's possible that ...
...ested a resource that cannot legally be provided, such as a web page censored by a government. server error responses 500 internal server error the server has encountered a situation it doesn't know how to handle. 501 not implemented the request method is not supported by the server and cannot be handled. the only methods that servers are required to support (and therefore that must not re
turn this code) are get and head. 502 bad gateway this error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 503 service unavailable the server is not ready to handle the request. common causes are a server that is down for maintenance or that is overloaded. note that together with this response, a user-friendly pa...
Concurrency model and the event loop - JavaScript
cting and processing events, and executing queued sub-tasks. this model is quite different from models in other languages like c and java. runtime concepts the following sections explain a theoretical model. modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. ...
...-tasks. this model is quite different from models in other languages like c and java. runtime concepts the following sections explain a theoretical model. modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. ...
...models in other languages like c and java. runtime concepts the following sections explain a theoretical model. modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. function foo(b) { let a = 10 re
turn a + b + 11 } function bar(x) { let y = 3 re
turn foo(x * y) } console.log(bar(7)) //re
turns 42 when calling bar, a first frame is created containing bar's arguments and local variables. when bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables. when foo re
turns, the top frame element is popped out of the stack (leaving only bar's call frame). when bar re
turns, the stack is empty. heap objects are allocated in a h...
...ough sending messages via the postmessage method. this method adds a message to the other runtime if the latter listens to message events. never blocking a very interesting property of the event loop model is that javascript, unlike a lot of other languages, never blocks. handling i/o is typically performed via events and callbacks, so when the application is waiting for an indexeddb query to re
turn or an xhr request to re
turn, it can still process other things like user input. legacy exceptions exist like alert or synchronous xhr, but it is considered a good practice to avoid them. beware: exceptions to the exception do exist (but are usually implementation bugs, rather than anything else). specifications specification html living standardthe definition of 'event loops'...
static - JavaScript
one https://github.com/mdn/interactive-examples and send us a pull request. syntax static methodname() { ... } examples using static in classes the following example demonstrates several things: how a static method is implemented on a class. that a class with a static member can be sub-classed. how a static method can and cannot be called. class triple { static triple(n = 1) { re
turn n * 3; } } class biggertriple extends triple { static triple(n) { re
turn super.triple(n) * super.triple(n); } } console.log(triple.triple()); // 3 console.log(triple.triple(6)); // 18 var tp = new triple(); console.log(biggertriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'. calling static met...
... // 18 var tp = new triple(); console.log(biggertriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'. calling static methods from another static method in order to call a static method within another static method of the same class, you can use the this keyword. ...
...affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'. calling static methods from another static method in order to call a static method within another static method of the same class, you can use the this keyword. class staticmethodcall { static staticmethod() { re
turn 'static method has been called'; } static anotherstaticmethod() { re
turn this.staticmethod() + ' from another static method'; } } staticmethodcall.staticmethod(); // 'static method has been called' staticmethodcall.anotherstaticmethod(); // 'static method has been called from another static method' calling static methods from a class constructor and other methods static methods are not directly accessible using the this keyword from non-static methods. you need t...
...ss name: classname.static_method_name() or by calling the method as a property of the constructor: this.constructor.static_method_name(). class staticmethodcall { constructor() { console.log(staticmethodcall.staticmethod()); // 'static method has been called.' console.log(this.constructor.staticmethod()); // 'static method has been called.' } static staticmethod() { re
turn 'static method has been called.'; } } specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
Array.isArray() - JavaScript
the array.isarray() method determines whether the passed value is an array. array.isarray([1, 2, 3]); // true array.isarray({foo: 123}); // false array.isarray('foobar'); // false array.isarray(undefined); // false syntax array.isarray(value) parameters value the value to be checked. re
turn value true if the value is an array; otherwise, false. description if the value is an array, true is re
turned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always re
turned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. if (!array.isarray) { array.isarray = function(arg) { ...
...ue is re
turned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always re
turned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
...is an array” for more details. given a typedarray instance, false is always re
turned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
... re
turn object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls re
turn true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls re
turn false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(undefined); array.isarray(17); array.isarray('array'); array.isarray(true); array.isarray(false); array.isarray(new uint8array(32)); array.isarray({ __proto__: array.prototype }); instanceof vs isarray when checking for array instance, array.isarray is preferred over instanceof because it works through iframes. var i...
DataView - JavaScript
memory differently depending on machine architecture — see endianness for an explanation. dataview accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256, true /* littleendian */); // int16array uses the platform's endianness. re
turn new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations. as a workaround, you could implement your own getuint64() function to obtain a value with precision up to number.max_safe_integer, which could suffic...
...t number into two 32-bit (4-byte) parts const left = dataview.getuint32(byteoffset, littleendian); const right = dataview.getuint32(byteoffset+4, littleendian); // combine the two 32-bit values const combined = littleendian? left + 2**32*right : 2**32*left + right; if (!number.issafeinteger(combined)) console.warn(combined, 'exceeds max_safe_integer. precision may be lost'); re
turn combined; } alternatively, if you need full 64-bit range, you can create a bigint. further, although native bigints are much faster than user-land library equivalents, bigints will always be much slower than 32-bit integers in javascript due to the nature of their variable size. const bigint = window.bigint, bigthirtytwo = bigint(32), bigzero = bigint(0); function getuint64bigint(dataview, byt...
... instance properties dataview.prototype.buffer the arraybuffer referenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at constr...
... instance properties dataview.prototype.buffer the arraybuffer referenced by this view. fixed at construction time and thus read only. dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer. fixed at construction ti...
Date.prototype[@@toPrimitive] - JavaScript
if hint is "string" or "default", [@@toprimitive]() tries to call the tostring method. if the tostring property does not exist, it tries to call the valueof method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror. ...
... if hint is "string" or "default", [@@toprimitive]() tries to call the tostring method. if the tostring property does not exist, it tries to call the valueof method and if the valueof does not exist either, [@@toprimitive]() throws a typeerror. ...
...]() throws a typeerror. if hint is "number", [@@toprimitive]() first tries to call valueof, and if that fails, it calls tostring. javascript calls the [@@toprimitive]() method to convert an object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. ...
...o convert an object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. examples re
turning date primitives const testdate = new date(1590757517834); // "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('string'); // re
turns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('number'); // re
turns "1590757517834" testdate[symbol.toprimitive]('default'); // re
turns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.@@toprimitive' in that specification. ...
Date.prototype.toString() - JavaScript
"sat" space month name: 3 letter english month name, e.g. ...
..."sat" space month name: 3 letter english month name, e.g. ...
...le 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 dateobj.tostring() re
turn value a string representing the given date. description date instances inherit their tostring() method from date.prototype, not object.prototype. date.prototype.tostring() re
turns a string representation of the date in the format specified in ecma-262 which can be summarised as: week day: 3 letter english week day name, e.g. "sat" space month name: 3 letter english month name, e.g. "sep" space date: 2 digit day in month, e.g. "01" space year: 4 digit year, e.g. "2018" space hour: 2 digit hour of day, e.g. "14" colon minute: 2 digit minute of hour, e.g. "53" ...
...of: space left bracket, i.e. "(" an implementation dependent string representation of the timezone, which might be an abbreviation or full name (there is no standard for names or abbreviations of timezones), e.g. "line islands time" or "lint" right bracket, i.e. ")" e.g. "sat sep 01 2018 14:53:26 gmt+1400 (lint)" until ecmascript 2018 (edition 9), the format of the string re
turned by date.prototype.tostring was implementation dependent. therefore it should not be relied upon to be in the specified format. the tostring() method is automatically called when a date is to be represented as a text value, e.g. console.log(new date()), or when a date is used in a string concatenation, such as var today = 'today is ' + new date(). tostring() is a generic method, it does not re...
Error.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified error object. syntax e.tostring() re
turn value a string representing the specified error object. description the error object overrides the object.prototype.tostring() method inherited by all objects. ...
...antics are as follows (assuming object and string have their original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ? 'error' : string(name); var msg = this.message; msg = (msg === undefined) ? ...
...nd string have their original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ? 'error' : string(name); var msg = this.message; msg = (msg === undefined) ? ...
... original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ? 'error' : string(name); var msg = this.message; msg = (msg === undefined) ? ...
Function.caller - JavaScript
notes note that in case of recursion, you can't reconstruct the call stack using this property. ...
...strict, async function and generator function callers. description if the function f was invoked by the top level code, the value of f.caller is null, otherwise it's the function that called f. it's also null for strict, async function and generator function callers. this property replaces the obsolete arguments.caller property of the arguments object. the special property __caller__, which re
turned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons. notes note that in case of recursion, you can't reconstruct the call stack using this property. consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -...
... ...
...) function like this: var f = stop; var stack = 'stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the loop would never stop. examples checking the value of a function's caller property the following code checks the value a function's caller property. function myfunc() { if (myfunc.caller == null) { re
turn 'the function was called from the top!'; } else { re
turn 'this function\'s caller was ' + myfunc.caller; } } specifications not part of any standard. ...
Math.cbrt() - JavaScript
description because cbrt() is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor). ...
...x3=the uniqueysuch thaty3=x\mathtt{math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x 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 math.cbrt(x) parameters x a number. ...
... re
turn value the cube root of the given number. description because cbrt() is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor). ...
...is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor). ...
Math.cosh() - JavaScript
description because cosh() is a static method of math, you always use it as math.cosh(), rather than as a method of a math object you created (math is not a constructor). ...
... be expressed using the constant e: math.cosh(x)=ex+e-x2\mathtt{\operatorname{math.cosh(x)}} = \frac{e^x + e^{-x}}{2} 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 math.cosh(x) parameters x a number. ...
... syntax math.cosh(x) parameters x a number. re
turn value the hyperbolic cosine of the given number. description because cosh() is a static method of math, you always use it as math.cosh(), rather than as a method of a math object you created (math is not a constructor). ...
...ath, you always use it as math.cosh(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.cosh = math.cosh || function(x) { re
turn (math.exp(x) + math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.cosh = math.cosh || function(x) { var y = math.exp(x); re
turn (y + 1 / y) / 2; }; examples using math.cosh() math.cosh(0); // 1 math.cosh(1); // 1.5430806348152437 math.cosh(-1); // 1.5430806348152437 specifications specification ecmascript (ecma-262)the definition of 'math.cosh' in that specification. ...
Math.imul() - JavaScript
description math.imul() allows for 32-bit integer multiplication with c-like semantics. this feature is useful for projects like emscripten. ...
... description math.imul() allows for 32-bit integer multiplication with c-like semantics. this feature is useful for projects like emscripten. because imul() is a static method of math, you always use it as math.imul(), rather than as a method of a math object you created (math is not a constructor). ...
...ere math.imul may prove performant in current browsers. polyfill this can be emulated with the following function: if (!math.imul) math.imul = function(a, b) { var ahi = (a >>> 16) & 0xffff; var alo = a & 0xffff; var bhi = (b >>> 16) & 0xffff; var blo = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value re
turn ((alo * blo) + (((ahi * blo + alo * bhi) << 16) >>> 0) | 0); }; however, the following function is more performant because it is likely that browsers in which this polyfill would be used do not optimize with an internal integer type in javascript, instead using floating points for all numbers. if (!math.imul) math.imul = function(opa, opb) { opb |= 0; // ensure that opb is an integer. opa wil...
...0001 // 0x1fffff7fc00001 < number.max_safe_integer /*0x1fffffffffffff*/ var result = (opa & 0x003fffff) * opb; // 2. we can remove an integer coersion from the statement above because: // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 // 0x1fffffff800001 < number.max_safe_integer /*0x1fffffffffffff*/ if (opa & 0xffc00000 /*!== 0*/) result += (opa & 0xffc00000) * opb |0; re
turn result |0; }; examples using math.imul() math.imul(2, 4); // 8 math.imul(-1, 8); // -8 math.imul(-2, -2); // 4 math.imul(0xffffffff, 5); // -5 math.imul(0xfffffffe, 5); // -10 specifications specification ecmascript (ecma-262)the definition of 'math.imul' in that specification. ...
Math.tan() - JavaScript
because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor). ...
... because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor). ...
...er. 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 math.tan(x) parameters x a number representing an angle in radians. re
turn value the tangent of the given number. description the math.tan() method re
turns a numeric value that represents the tangent of the angle. because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor). examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following function...
.... because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor). examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and re
turns the tangent. function gettandeg(deg) { var rad = deg * math.pi/180; re
turn math.tan(rad); } specifications specification ecmascript (ecma-262)the definition of 'math.tan' in that specification. ...
Number.isInteger() - JavaScript
sinteger() method determines whether the passed value is an integer. 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 number.isinteger(value) parameters value the value to be tested for being an integer. ...
...hub 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 number.isinteger(value) parameters value the value to be tested for being an integer. re
turn value a boolean indicating whether or not the given value is an integer. description if the target value is an integer, re
turn true, otherwise re
turn false. if the value is nan or infinity, re
turn false. ...
...hub.com/mdn/interactive-examples and send us a pull request. syntax number.isinteger(value) parameters value the value to be tested for being an integer. re
turn value a boolean indicating whether or not the given value is an integer. description if the target value is an integer, re
turn true, otherwise re
turn false. if the value is nan or infinity, re
turn false. the method will also re
turn true for floating point numbers that can be represented as integer. ...
...ng an integer. re
turn value a boolean indicating whether or not the given value is an integer. description if the target value is an integer, re
turn true, otherwise re
turn false. if the value is nan or infinity, re
turn false. the method will also re
turn true for floating point numbers that can be represented as integer. ...
Number.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
...ns a string representing the source code of the object. syntax numobj.tosource() number.tosource() re
turn value a string representing the source code of the object. examples native function for the built-in number object, tosource() re
turns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() re
turns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Object.prototype.__lookupSetter__() - JavaScript
__lookupsetter__ can be used to obtain a reference to the setter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor(). ...
...__lookupsetter__ can be used to obtain a reference to the setter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor(). ...
...__lookupsetter__ can be used to obtain a reference to the setter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor(). ...
...__lookupsetter__ can be used to obtain a reference to the setter function. it is now possible to do this in a standardized way using object.getownpropertydescriptor(). ...
Object.entries() - JavaScript
if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));. 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. ...
...((a, b) => b[0].localecompare(a[0]));. 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 object.entries(obj) parameters obj the object whose own enumerable string-keyed property [key, value] pairs are to be re
turned. re
turn value an array of the given object's own enumerable string-keyed property [key, value] pairs. description object.entries() re
turns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object. the ordering of the properties is the same as that given by looping over the property values of the object manually. ...
... examples const obj = { foo: 'bar', baz: 42 }; console.log(object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // array like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.entries(obj)); ...
...ike object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // array like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.entries(anobj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] // getfoo is property which isn't enumerable const myobj = object.create({}, { getfoo: { value() { re
turn this.foo; } } }); myobj.foo = 'bar'; console.log(object.entries(myobj)); // [ ['foo', 'bar'] ] // non-object argument will be coerced to an object console.log(object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // re
turns an empty array for any primitive type, since primitives have no own properties console.log(object.entries(100)); // [ ] // iterate through key-value gracefully ...
Object.getOwnPropertyDescriptor() - JavaScript
the object.getownpropertydescriptor() method re
turns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). the object re
turned is mutable but mutating it has no effect on the original property's configuration. 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 object.getownpropertydescriptor(obj, prop) parameters obj the object in which to look for the property. prop the name or symbol of the property whose description is to be retrieved. ...
...ctive 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 object.getownpropertydescriptor(obj, prop) parameters obj the object in which to look for the property. prop the name or symbol of the property whose description is to be retrieved. re
turn value a property descriptor of the given property if it exists on the object, undefined otherwise. description this method permits examination of the precise description of a property. a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineprope...
... is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...e: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object first argument will be coerced to an object at first. object.getownpropertydescriptor('foo', 0); // typeerror: "foo" is not an object // es5 code object.getownpropertydescriptor('foo', 0); // object re
turned by es2015 code: { // configurable: false, // enumerable: true, // value: "f", // writable: false // } specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptor' in that specification. ...
Object.keys() - JavaScript
the object.keys() method re
turns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. 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 object.keys(obj) parameters obj the object of which the enumerable's own properties are to be re
turned. re
turn value an array of strings that represent all the enumerable properties of the given object. description object.keys() re
turns an array whose elements are strings corresponding to the enumerable properties found directly upon object. the ordering of the properties is the same as that given by looping...
... hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !({ tostring: null }).propertyisenumerable('tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; re
turn function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw new typeerror('object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++...
... for a simple browser polyfill, see javascript - object.keys browser compatibility. examples using object.keys // simple array const arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like obj...
... non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. from es2015 onwards, a non-object argument will be coerced to an object. // in es5 object.k...
handler.defineProperty() - JavaScript
const p = new proxy(target, { defineproperty: function(target, property, descriptor) { } }); parameters the following parameters are passed to the defineproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property whose description is to be retrieved. descriptor the descriptor for the property being defined or modified. re
turn value the defineproperty() method must re
turn a boolean indicating whether or not the property has been successfully defined. description the handler.defineproperty() method is a trap for object.defineproperty(). interceptions this trap can intercept these operations: object.defineproperty() reflect.defineproperty() invariants if the following invariants are violated, the proxy will t...
...ded as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object. a property may not be non-configurable, if a corresponding configurable property of the target object exists. if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an exception. ...
...en object.defineproperty(target, prop, descriptor) will not throw an exception. in strict mode, a false re
turn value from the defineproperty() handler will throw a typeerror exception. examples trapping of defineproperty the following code traps object.defineproperty(). ...
... ...
handler.getOwnPropertyDescriptor() - JavaScript
https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { getownpropertydescriptor: function(target, prop) { } }); parameters the following parameters are passed to the getownpropertydescriptor() method. this is bound to the handler. target the target object. prop the name of the property whose description should be retrieved. re
turn value the getownpropertydescriptor() method must re
turn an object or undefined. description the handler.getownpropertydescriptor() method is a trap for object.getownpropertydescriptor(). interceptions this trap can intercept these operations: object.getownpropertydescriptor() reflect.getownpropertydescriptor() invariants if the following invariants are violated, the proxy will throw a...
... a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. ...
...object. the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an exception. examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor(). ...
... re
turn { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" // 10 the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { getownpropertydescriptor: function(target, prop) { re
turn undefined; } }); object.getownpropertydescriptor(p, 'a'); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[getownproperty]]' in that specification. ...
handler.isExtensible() - JavaScript
d 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 p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method. this is bound to the handler. target the target object. ...
...ntribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method. this is bound to the handler. target the target object. re
turn value the isextensible() method must re
turn a boolean value. description the handler.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must re
turn the same value as object.isextensible(target). examples ...
....isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must re
turn the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); re
turn true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. ...
...es trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); re
turn true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. const p = new proxy({}, { isextensible: function(target) { re
turn false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification. ...
handler.preventExtensions() - JavaScript
hub 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 p = new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method. this is bound to the handler. target the target object. re
turn value the preventextensions() method must re
turn a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(pr...
...preventextensions() method must re
turn a boolean value. description the handler.preventextensions() method is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only re
turns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). ...
...the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only re
turns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); re
turn true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant. ...
...eventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); re
turn true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant. const p = new proxy({}, { preventextensions: function(target) { re
turn true; } }); object.preventextensions(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[preventextensions]]' in that specification. ...
Reflect.defineProperty() - JavaScript
the static reflect.defineproperty() method is like object.defineproperty() but re
turns a boolean. 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 reflect.defineproperty(target, propertykey, attributes) parameters target the target object on which to define the property. propertykey the name of the property to be defined or modified. attributes the attributes for the property being defined or modified. re
turn value a boolean indicating whether or not the property was successfully defined. exceptions a typeerror, if target is not an object. description the reflect.defineproperty method allows ...
...ng defined or modified. re
turn value a boolean indicating whether or not the property was successfully defined. exceptions a typeerror, if target is not an object. description the reflect.defineproperty method allows precise addition to or modification of a property on an object. for more details, see the object.defineproperty which is similar. one key difference: object.defineproperty re
turns the object or throws a typeerror if the property has not been successfully defined. reflect.defineproperty, however, simply re
turns a boolean indicating whether or not the property was successfully defined. examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property defini...
...n successfully defined. reflect.defineproperty, however, simply re
turns a boolean indicating whether or not the property was successfully defined. examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property definition has been successful with object.defineproperty, which re
turns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property. ...
... obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property definition has been successful with object.defineproperty, which re
turns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property. ] because reflect.defineproperty re
turns a boolean success status, you can just use an if...else block here: if (reflect.defineproperty(target, property, attributes)) { // success } else { // failure } specifications specification ecmascript (ecma-262)the definition of 'reflect.defineproperty' in that specification. ...
Reflect.has() - JavaScript
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 reflect.has(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to check. ...
...f the property to check. re
turn value a boolean indicating whether or not the target has the property. exceptions a typeerror, if target is not an object. description the reflect.has method allows you to check if a property is in an object. it works like the in operator as a function. ...
...ct. description the reflect.has method allows you to check if a property is in an object. it works like the in operator as a function. ...
...function. examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // re
turns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { re
turn k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has re
turns true for any inherited properties, like the in operator: const a = {foo: 123} const b = {__proto__: a} const c = {__proto__: b} // the prototype chain is: c -> b -> a reflect.has(c, 'foo') // true specifications specification ecmascript (ecma-262)the definition of 'reflect.has' in that specification. ...
RegExp.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
...urns a string representing the source code of the object. syntax regexobj.tosource() re
turn value a string representing the source code of the given regexp object. examples native function for the built-in regexp object, tosource() re
turns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() re
turns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
String.prototype.codePointAt() - JavaScript
the codepointat() method re
turns a non-negative integer that is the unicode code point value. 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 str.codepointat(pos) parameters pos position of an element in str to re
turn the code point value from. re
turn value a number representing the code point value of the character at the given pos. if there is no element at pos, re
turns undefined. description if there is no element at the specified position, undefined is re
turned. if no utf-16 surrogate pair begins at pos, the code unit at pos is re
turned. polyfill the following extends strings to include the ...
...number(position) : 0; if (index != index) { // better `isnan` index = 0; } // account for out-of-bounds indices: if (index < 0 || ...
...codepointat = function(position) { if (this == null) { throw typeerror(); } var string = string(this); var size = string.length; // `tointeger` var index = position ? ...
... if ( // check if it’s the start of a surrogate pair first >= 0xd800 && first <= 0xdbff && // high surrogate size > index + 1 // there is a next code unit ) { second = string.charcodeat(index + 1); if (second >= 0xdc00 && second <= 0xdfff) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae re
turn (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } re
turn first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codep...
String length - JavaScript
ecmascript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. ...
... ecmascript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. previously, no maximum length was specified. in firefox, strings have a maximum length of 2**30 - 2 (~1gb). ...
...the length of strings, it's the arity of the string function (loosely, the number of formal parameters it has), which is 1. ...
...cters you need something like this: function getcharacterlength (str) { // the string iterator that is used here iterates over characters, // not mere code units re
turn [...str].length; } console.log(getcharacterlength('a\ud87e\udc04z')); // 3 // while not recommended, you could add this to each string as follows: object.defineproperty(string.prototype, 'charlength', { get () { re
turn getcharacterlength(this); } }); console.log('a\ud87e\udc04z'.charlength); // 3 examples basic usage let x = 'mozilla'; let empty = ''; console.log(x + ' is ' + x.length + ' code units long'); /* "mozilla is 7 code units long" */ console.log('the empty string has a length of ' + empty.length); // expected output: "the empty string has a length of 0" assigning to length let mystring = "b...
String.prototype.repeat() - JavaScript
exceptions rangeerror: repeat count must be non-negative. ...
...alled, concatenated together. 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 str.repeat(count) parameters count an integer between 0 and +infinity, indicating the number of times to repeat the string. re
turn value a new string containing the specified number of copies of the given string. exceptions rangeerror: repeat count must be non-negative. rangeerror: repeat count must be less than infinity and not overflow maximum string size. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfi...
... var str = '' + this; // to convert string to integer. count = +count; // check nan if (count != count) count = 0; if (count < 0) throw new rangeerror('repeat count must be non-negative'); if (count == infinity) throw new rangeerror('repeat count must be less than infinity'); count = math.floor(count); if (str.length == 0 || count == 0) re
turn ''; // ensuring count is a 31-bit integer allows us to heavily optimize the // main part. but anyway, most current (august 2014) browsers can't handle // strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) throw new rangeerror('repeat count must not overflow maximum string size'); var maxcount = str.length * count; count = math.floor(math.log(co...
...rowsers can't handle // strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) throw new rangeerror('repeat count must not overflow maximum string size'); var maxcount = str.length * count; count = math.floor(math.log(count) / math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxcount - str.length); re
turn str; } } examples using repeat 'abc'.repeat(-1) // rangeerror 'abc'.repeat(0) // '' 'abc'.repeat(1) // 'abc' 'abc'.repeat(2) // 'abcabc' 'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0) // rangeerror ({ tostring: () => 'abc', repeat: string.prototype.repeat }).repeat(2) // 'abcabc' (repeat() is a generic method) specifications ...
String.prototype.replaceAll() - JavaScript
the pattern can be a string or a regexp, and the replacement can be a string or a function to be called for each match. the original string is left unchanged. 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. ...
...es and send us a pull request. syntax const newstr = str.replaceall(regexp|substr, newsubstr|function) when using a `regexp` you must have to set the global ("g") flag; otherwise, it will throw a typeerror: "replaceall must be called with a global regexp". parameters regexp (pattern) a regexp object or literal with the global flag. the matches are replaced with newsubstr or the value re
turned by the specified function. a regexp without the global ("g") flag will throw a typeerror: "replaceall must be called with a global regexp". substr a string that is to be replaced by newsubstr. it is treated as a literal string and is not interpreted as a regular expression. newsubstr (replacement) the string that replaces the substring specified by the specified regexp or substr parameter. ...
... or substr parameter. a number of special replacement patterns are supported; see the "specifying a string as a parameter" section below. function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. the arguments supplied to this function are described in the "specifying a function as a parameter" section below. re
turn value a new string, with all matches of a pattern replaced by a replacement. description this method does not change the calling string object. it simply re
turns a new string. specifying a string as a parameter the replacement string can include the following special replacement patterns: pattern inserts $$ inserts a "$". $& inserts the matched substr...
...ed substring. $n where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a regexp object. note that this is 1-indexed. specifying a function as a parameter you can specify a function as the second parameter. in this case, the function will be invoked after the match has been performed. the function's result (re
turn value) will be used as the replacement string. (note: the above-mentioned special replacement patterns do not apply in this case.) note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global. the arguments to the function are as follows: possible name supplied value match the mat...
String.prototype.slice() - JavaScript
the slice() method extracts a section of a string and re
turns it as a new string, without modifying the original string. 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 str.slice(beginindex[, endindex]) parameters beginindex the zero-based index at which to begin extraction. if negative, it is treated as str.length + beginindex. (for example, if beginindex is -3 it is treated as str.length - 3.) if beginindex is greater than or equal to str.length, slice() re
turns an empty string. endindex optional the zero-based index before which to end extraction. the character at this index will not be inc...
...changes to the text in one string do not affect the other string. slice() extracts up to but not including endindex. ...
...changes to the text in one string do not affect the other string. slice() extracts up to but not including endindex. ...
... str3 = str1.slice(4, -2), str4 = str1.slice(12), str5 = str1.slice(30); console.log(str2) // output: he morn console.log(str3) // output: morning is upon u console.log(str4) // output: is upon us. console.log(str5) // output: "" using slice() with negative indexes the following example uses slice() with negative indexes. let str = 'the morning is upon us.' str.slice(-3) // re
turns 'us.' str.slice(-3, -1) // re
turns 'us' str.slice(0, -1) // re
turns 'the morning is upon us' this example counts backwards from the end of the string by 11 to find the start index and forwards from the start of the string by 16 to find the end index. console.log(str.slice(-11, 16)) // => "is u" here it counts forwards from the start by 11 to find the start index and backwards from the end...
String.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
... this method is usually called internally by javascript and not explicitly in web code. ...
...the source code of the object. syntax string.tosource() str.tosource() re
turn value a string representing the source code of the calling object. examples native function for the built-in string object, tosource() re
turns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() re
turns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Symbol.species - JavaScript
//github.com/mdn/interactive-examples and send us a pull request. description the species accessor property allows subclasses to override the default constructor for objects. ...
... allows subclasses to override the default constructor for objects. property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to re
turn array objects in your derived array class myarray. ...
... objects. property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to re
turn array objects in your derived array class myarray. for example, when using methods such as map() that re
turn the default constructor, you want these methods to re
turn a parent array object, instead of the myarray object. ...
...ight want to re
turn array objects in your derived array class myarray. for example, when using methods such as map() that re
turn the default constructor, you want these methods to re
turn a parent array object, instead of the myarray object. the species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { re
turn array; } } let a = new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof myarray); // false console.log(mapped instanceof array); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.species' in that specification. ...
TypedArray.prototype.every() - JavaScript
typedarray.every(callback[, thisarg]) parameters callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array every was called upon. thisarg optional. value to use as this when executing callback. re
turn value true if the callback function re
turns a truthy value for every array element; otherwise, false. description the every method executes the provided callback function once for each element present in the typed array until it finds one where callback re
turns a falsy value (a value that becomes false when converted to a boolean). if such an element is found, the every method immediately retu...
... callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to every, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. ...
... callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. ...
... value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the typed array on which it is called. examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10. function isbigenough(element, index, array) { re
turn element >= 10; } new uint8array([12, 5, 8, 130, 44]).every(isbigenough); // false new uint8array([12, 54, 18, 130, 44]).every(isbigenough); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. new uint8array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false new uint8array([12, 54, 18, 130, 44]).every(elem => elem >= 10)...
TypedArray.prototype.find() - JavaScript
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 typedarray.find(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. ...
...rray.find(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the array find was called upon. thisarg optional. object to use as this when executing callback. re
turn value a value in the array if an element passes the test; otherwise, undefined. description the find method executes the callback function once for each element present in the typed array until it finds one where callback re
turns a true value. if such an element is found, find immediately re
turns the value of that element. otherwise, find re
turns undefined. callback is invoked only for indexes...
...will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited. ...
...find visits that element's index; elements that are deleted are not visited. examples find a prime number in a typed array the following example finds an element in the typed array that is a prime number (or re
turns undefined if there is no prime number). function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { re
turn false; } } re
turn element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification. ...
TypedArray.prototype.reduce() - JavaScript
teractive 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 reduce method executes the callback function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the typed array over which iteration is occurring. ...
...vided, then previousvalue will be equal to the first value in the typed array and currentvalue will be equal to the second. if the typed array is empty and no initialvalue was provided, typeerror would be thrown. ...
...provided but the typed array is empty, the solo value would be re
turned without calling callback. polyfill this method uses the same algorithm as array.prototype.reduce(), so the same polyfill can be used here: simply replace array.prototype.reduce with typedarray.prototype.reduce. examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduce(function(a, b) { re
turn a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduce' in that specification. ...
TypedArray.prototype.slice() - JavaScript
this method has the same algorithm as array.prototype.slice(). typedarray is one of the typed array types here. 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 typedarray.slice([begin[, end]]) parameters begin optional zero-based index at which to begin extraction. a negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. if begin is undefined, slice begins from index 0. ...
...but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (typedarray.length). re
turn value a new typed array containing the extracted elements. description the slice method does not alter. it re
turns a shallow copy of elements from the original typed array. if a new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. if (!uint8arra...
... copy of elements from the original typed array. if a new element is added to either typed array, the other typed array is not affected. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. ...
... object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { re
turn new uint8array(array.prototype.slice.call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples re
turn a portion of an existing typed array const uint8 = new uint8array([1,2,3]); uint8.slice(1); // uint8array [ 2, 3 ] uint8.slice(2); // uint8array [ 3 ] uint8.slice(-2); // uint8array [ 2, 3 ] uint8.slice(0,1); // uint8array [ 1 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.slice' in that specification. ...
WeakRef - JavaScript
ipt engine's garbage collector may destroy the object and reclaim its memory. if that happens, you can't get the object from a weak reference anymore. note: please see the avoid where possible section below. correct use of weakref takes careful thought, and it's best avoided if possible. constructor weakref() creates a new weakref object. instance methods weakref.prototype.deref() re
turns the weakref object's target object, or undefined if the target object has been reclaimed. avoid where possible correct use of weakref takes careful thought, and it's best avoided if possible. it's also important to avoid relying on any specific behaviors not guaranteed by the specification. when, how, and whether garbage collection occurs is down to the implementation of any given javascript ...
...in apis. notes on weakrefs some notes on weakrefs: if your code has just created a weakref for a target object, or has gotten a target object from a weakref's deref method, that target object will not be reclaimed until the end of the current javascript job (including any promise reaction jobs that run at the end of a script job). that is, you can only "see" an object get reclaimed between
turns of the event loop. this is primarily to avoid making the behavior of any given javascript engine's garbage collector apparent in code — because if it were, people would write code relying on that behavior, which would break when the garbage collector's behavior changed. (garbage collection is a hard problem; javascript engine implementers are constantly refining and improving how it works.) i...
...ionregistry, the weakref's target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls deref on a weakref for the object, it will receive undefined. you cannot change the target of a weakref, it will always only ever be the original target object or undefined when that target has been reclaimed. a weakref might never re
turn undefined from deref, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object. examples using a weakref object this example starts a counter shown in a dom element, stopping when the element doesn't exist anymore: class counter { constructor(element) { // remember a weak reference to the dom element this.ref = new weakref(elem...
...se the garbage collector may never decide to reclaim the object. ...
Lexical grammar - JavaScript
are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is considered as white space). line terminator characters code point name abbreviation description escape sequence u+000a line feed <lf> new line character in unix systems. \n u+000d carriage re
turn <cr> new line character in commodore and early mac systems. \r u+2028 line separator <ls> wikipedia u+2029 paragraph separator <ps> wikipedia comments comments are used to add hints, notes, suggestions, or warnings to javascript code. this can make it easier to read and understand. they can also be used to disable code to prevent it fro...
...you want to run scripts directly from shell. you must only use the #! comment style to specify a javascript interpreter. in all other cases just use a // comment (or mulitiline comment). keywords reserved keywords as of ecmascript 2015 break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof new re
turn super switch this throw try typeof var void while with yield future reserved keywords the following are reserved as future keywords by the ecmascript specification. they have no special functionality at present, but they might at some future time, so they cannot be used as identifiers. these are always reserved: enum the following are only reserved when they are found in stric...
... 1. a semicolon is inserted before, when a line terminator or "}" is encountered that is not allowed by the grammar. { 1 2 } 3 // is transformed by asi into { 1 2 ;} 3; 2. a semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input strea...
...as a postfix operator applying to variable b, because a line terminator occurs between b and ++. a = b ++c // is transformend by asi into a = b; ++c; 3. a semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. these statements with "no lineterminator here" rules are: postfixexpressions (++ and --) continue break re
turn yield, yield* module re
turn a + b // is transformed by asi into re
turn; a + b; specifications specification ecmascript (ecma-262)the definition of 'lexical grammar' in that specification. ...
function declaration - JavaScript
engines. statements optional the statements which comprise the body of the function. description a function created with a function declaration is a function object and has all the properties, methods and behavior of function objects. see function for detailed information on functions. a function can also be created using an expression (see function expression). by default, functions re
turn undefined. to re
turn any other value, the function must have a re
turn statement that specifies the value to re
turn. conditionally created functions functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. for conditiona...
... statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. for conditional function creation, use function expressions instead. var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (false) { function foo(){ re
turn 1; } } // in chrome: // 'foo' name is hoisted. typeof foo is undefined // // in firefox: // 'foo' name is hoisted. typeof foo is undefined // // in edge: // 'foo' name is not hoisted. typeof foo is undefined // // in safari: // 'foo' name is hoisted. typeof foo is function the results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' n...
...is hoisted. typeof foo is undefined // // in edge: // 'foo' name is not hoisted. typeof foo is undefined // // in safari: // 'foo' name is hoisted. typeof foo is function the results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (true) { function foo(){ re
turn 1; } } // in chrome: // 'foo' name is hoisted. typeof foo is undefined // // in firefox: // 'foo' name is hoisted. typeof foo is undefined // // in edge: // 'foo' name is not hoisted. typeof foo is undefined // // in safari: // 'foo' name is hoisted. typeof foo is function function declaration hoisting function declarations in javascript are hoisted to the top of the enclosing function or glo...
...the enclosing function or global scope. you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; examples using function the following code declares a function that re
turns the total amount of sales, when given the number of units sold of products a, b, and c. function calc_sales(units_a, units_b, units_c) { re
turn units_a * 79 + units_b * 129 + units_c * 699; } specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification. ...
Codecs used by WebRTC - Web media technologies
ompletion of ice candidate gathering, then fetch the list. let codeclist = null; peerconnection.addeventlistener("icegatheringstatechange", (event) => { if (peerconnection.icegatheringstate === "complete") { const senders = peerconnection.getsenders(); senders.foreach((sender) => { if (sender.track.kind === "video") { codeclist = sender.getparameters().codecs; re
turn; } }); } codeclist = null; }); the event handler for icegatheringstatechange is established; in it, we look to see if the ice gathering state is complete, indicating that no further candidates will be collected. the method rtcpeerconnection.getsenders() is called to get a list of all the rtcrtpsender objects used by the connection. with that in hand, we walk through the list of s...
...be collected. the method rtcpeerconnection.getsenders() is called to get a list of all the rtcrtpsender objects used by the connection. with that in hand, we walk through the list of senders, looking for the first one whose mediastreamtrack indicates that it's track's kind is video, indicating that the track's data is video media. we then call that sender's getparameters() method and, from the re
turned rtcrtpsendparameters object, we set codeclist to the codecs property and re
turn to the caller. if no video track is found, we set codeclist to null. on re
turn, then, codeclist is either null to indicate that no video tracks were found or it's an array of rtcrtpcodecparameters objects, each describing one permitted codec configuration. of special importance in these objects: the payloadtype pr...
...once the list has been split up, they're concatenated back together with the entries matching the given mimetype first, followed by all of the other codecs. the rearrange...
...cat(othercodecs); } this code is just splitting the codec list into two arrays: one containing codecs whose mime type matches the one specified by the mimetype parameter, and the other with all the other codecs. once the list has been split up, they're concatenated back together with the entries matching the given mimetype first, followed by all of the other codecs. the rearranged list is then re
turned to the caller. default codecs unless otherwise specified, the default—or, more accurately, preferred—codecs requested by each browser's implementation of webrtc are shown in the table below. preferred codecs for webrtc in major web browsers audio video chrome edge firefox vp9 (firefox 46 and later) vp8 op...
Populating the page: how browsers work - Web Performance
ch can cause delays. dns lookup the first step of navigating to a web page is finding where the assets for that page are located. if you navigate to https://example.com, the html page is located on the server with ip address of 93.184.216.34. if you’ve never visited this site, a dns lookup must happen. your browser requests a dns lookup, which is eventually fielded by a name server, which in
turn responds with an ip address. after this initial request, the ip will likely be cached for a time, which speeds up subsequent requests by retrieving the ip address from the cache instead of contacting a name server again. dns lookups usually only need to be done once per hostname for a page load. however, dns lookups must be done for each unique hostname the requested page references. if your fon...
...ad, tcp slow start is the reason why the initial response is 14kb, and why web performance optimization calls for focusing optimizations with this initial 14kb response in mind. tcp slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion. congestion control as the server sends data in tcp packets, the user's client confirms delivery by re
turning acknowledgements, or acks. the connection has a limited capacity depending on hardware and network conditions. if the server sends too many packets too quickly, they will be dropped. meaning, there will be no acknowledgement. the server registers this as missing acks. congestion control algorithms use this flow of sent packets and acks to determine a send rate. parsing once the browser recei...
... the server sends too many packets too quickly, they will be dropped. meaning, there will be no acknowledgement. the server registers this as missing acks. congestion control algorithms use this flow of sent packets and acks to determine a send rate. parsing once the browser receives the first chunk of data, it can begin parsing the information received. parsing is the step the browser takes to
turn the data it receives over the network into the dom and cssom, which is used by the renderer to paint a page to the screen. the dom is the internal representation of the markup for the browser. the dom is also exposed, and can be manipulated through various apis in javascript. even if the request page's html is larger than the initial 14kb packet, the browser will begin parsing and attempting to...
...the body’s descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn’t know the dimensions of, such as our image. the first time the size and position of nodes are determined is called layout. subsequent recalculations of node size and locations are called reflows. in our example, suppose the initial layout occurs before the image is re
turned. since we didn't declare the size of our image, there will be a reflow once the image size is known. paint the last step in the critical rendering path is painting the individual nodes to the screen, the first occurence of which is called the first meaningful paint. in the painting or rasterization phase, the browser converts each box calculated in the layout phase to actual pixels on the scr...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
sists of three files: index.js, which contains the source 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) { re
turn 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 ob...
... }) .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 part, the code looks like this: if(subscription) { re
turn subscription; } if the user has already subscribed, we then re
turn the subscription object and move to the subscription part. if not, we initialize a new subscription: const response = await fetch('./vapidpublickey'); const vapidpublickey = await response.text(); const convertedvapidkey = urlbase64touint8array(vapidpublickey); the app fetches the server's public key and converts the response t...
...mozilla’s push service blog post. the app can now use the pushmanager to subscribe the new user. there are two options passed to the pushmanager.subscribe() method — the first is uservisibleonly: true, which means all the notifications sent to the user will be visible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key. re
turn registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the app first sends the subscription details as json to the server using fetch. fetch('./register', { method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ subscription: subsc...
...b-push module is used to set the vapid keys, and optionally generate them if they are not available yet. const webpush = require('web-push'); if (!process.env.vapid_public_key || !process.env.vapid_private_key) { console.log("you must set the vapid_public_key and vapid_private_key "+ "environment variables. you can use the following ones:"); console.log(webpush.generatevapidkeys()); re
turn; } webpush.setvapiddetails( 'https://serviceworke.rs/', process.env.vapid_public_key, process.env.vapid_private_key ); next, a module defines and exports all the routes an app needs to handle: getting the vapid public key, registering, and then sending notifications. you can see the variables from the index.js file being used: payload, delay and ttl. module.exports = function(app, route...
current - XPath
or self syntax). ...
...sed to get the context node in an xslt instruction. syntax current() re
turns a node-set containing only the current node. notes this function is an xslt-specific addition to xpath. it is not a part of the core xpath function library. for an outermost expression (an expression not occurring within another expression), the current node is always the same as the context node (which will be re
turned by the . or self syntax). the following two are symantically equivalent. <xsl:value-of select="current()"/> <xsl:value-of select="."/> in an inner expression (e.g. in square brackets), the current node is still the same as it would have been in an outermost expression. ...
...moreover, the latter two are semantically equivalent. <xsl:value-of select="current()"/> <xsl:value-of select="foo/bar[current() = x]"/> <xsl:variable name="current" select="current()"/> <xsl:value-of select="foo/bar[$current = x]"/> and the next code is also semantically equivalent to the latter two, since the . occurs in an outermost expression. ...
... defined xslt 1.0 12.4 gecko support supported. ...
l10n - Archive of obsolete content
alizable code, read the localization tutorial. note that you can't currently use localize strings appearing in content scripts or html files, but you can share the localized strings you want by assigning it's values to a json serializable object. globals functions get(identifier, count, placeholder1...n) this function takes a string parameter which it uses as an identifier to look up and re
turn a localized string in the locale currently set for firefox. localized strings are supplied by the add-on developer in .properties files stored in the add-ons "locale" directory. the gettext tools uses "_" for the name of the function that retrieves localized strings. for compatibility with tools that expect this syntax, you can assign this function to "_": var _ = require("sdk/l10n").get; give...
...this enables you to write functional, localizable code without localizing any strings - just make the identifiers the default language: var _ = require("sdk/l10n").get; console.log(_("hello!")); however, this will make it more difficult to maintain your code if you have many localizations, because any changes to the identifier values break all your .properties files. if...
...o not include the count parameter, you can supply one or more placeholder strings that are to be inserted into the translated string at locations defined by the translator. if you supply multiple placeholders, each one is a separate string parameter. var _ = require("sdk/l10n").get; console.log(_("home_town", "alan", "norwich")); see the tutorial on placeholder support for more information. re
turns string : the localized string referenced by the identifier parameter passed in, or the identifier itself if no referent for the identifier can be found. ...
querystring - Archive of obsolete content
tional optional parameters: querystring.stringify({ foo: 'bar', baz: 4 }, ';', ':'); // => 'foo:bar;baz:4' parameters fields : object the data to convert to a query string. separator : string the string to use as a separator between each name:value pair. by default this is "&". assignment : string the string to use between each name and its corresponding value. by default this is "=". re
turns string : the query string. parse(querystring, separator, assignment) parse a query string into an object containing name:value pairs: querystring.parse('foo=bar&baz=bla') // => { foo: 'bar', baz: 'bla' } optionally separator and assignment arguments may be passed to override default '&' and '=' characters: querystring.parse('foo:bar|baz:bla', '|', ':') // => { foo: 'bar', baz: 'bla' } ...
... override default '&' and '=' characters: querystring.parse('foo:bar|baz:bla', '|', ':') // => { foo: 'bar', baz: 'bla' } parameters querystring : string the query string. separator : string the string to use as a separator between each name:value pair. by default this is "&". assignment : string the string to use between each name and its corresponding value. by default this is "=". re
turns object : an object containing the components of the query string as name : value pairs. escape(query) the escape function used by stringify to encodes a string safely matching rfc 3986 for application/x-www-form-urlencoded. parameters query : string the query string to escape. re
turns string : the escaped query string. unescape(query) the unescape function used by parse to decode a str...
...s name : value pairs. escape(query) the escape function used by stringify to encodes a string safely matching rfc 3986 for application/x-www-form-urlencoded. parameters query : string the query string to escape. re
turns string : the escaped query string. unescape(query) the unescape function used by parse to decode a string safely. parameters query : string an escaped query string. re
turns string : the unescaped string. ...
self - Archive of obsolete content
json file. data the data object is used to access data that was bundled with the add-on. this data lives in the add-on's data/ directory, immediately below the package.json file. all files in this directory will be copied into the xpi and made available through the data object. the package specification article explains the package.json file. methods data.load(name) the data.load() method re
turns the contents of an embedded data file, as a string. it is most useful for data that will be modified or parsed in some way, such as json, xml, plain text, or perhaps an html template. for data that can be displayed directly in a content frame, use data.url(). parameters name : string the filename to be read, relative to the package's data directory. each package that uses the self module will...
...ta file, as a string. it is most useful for data that will be modified or parsed in some way, such as json, xml, plain text, or perhaps an html template. for data that can be displayed directly in a content frame, use data.url(). parameters name : string the filename to be read, relative to the package's data directory. each package that uses the self module will see its own data directory. re
turns string : the file contents. data.url(name) the data.url() method re
turns a resource:// url that points at an embedded data file. it is most useful for data that can be displayed directly in a content frame. the url can be passed to a content frame constructor, such as the panel: var self = require("sdk/self"); var mypanel = require("sdk/panel").panel({ contenturl: self.data.url("myfile.ht...
...m firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: var mypanel = require("sdk/panel").panel({ contenturl: "./myfile.html" }); mypanel.show(); parameters name : string the filename to be read, relative to the package's data directory. each package that uses the self module will see its own data directory. re
turns string : resource:// url pointing to the given location under data. ...
tabs - Archive of obsolete content
bject that triggered the event. methods pin() pins this tab as an app tab. unpin() unpins this tab. close(callback) closes this tab. parameters callback : function a function to be called when the tab finishes its closing process. this is an optional argument. reload() reloads this tab. activate() makes this tab active, which will bring this tab to the foreground. getthumbnail() re
turns thumbnail data uri of the page currently loaded in this tab. attach(options) attach one or more scripts to the document loaded in the tab. note that by attaching inside ready event, this becomes tab-centric: if the user navigates to a new page in the same tab, then the content scripts will be reattached to the new page. example var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) ...
...er receives a message from content scripts. listeners are passed a single argument, the message posted from the content script. optional. onerror function a function called when the content worker receives an error from content scripts. listeners are passed a single argument, error, which is the error posted from the content script and an object of type error. optional re
turns worker : the worker object can be used to communicate with the content script. see content scripts guide to learn the details. properties id the unique id for the tab. this property is read-only. title the title of the tab (usually the title of the page currently loaded in the tab) this property can be set to change the tab title. url the url of the page currently loaded in the tab. this...
...ge currently loaded in the tab. this property can be set to load a different url in the tab. favicon the url of the favicon for the page currently loaded in the tab. this property is read-only. this property is deprecated. from version 1.15, use the favicon module's getfavicon() function instead. contenttype this is currently an experimental api, so we might change it in future releases. re
turns the mime type that the document currently loaded in the tab is being rendered as. this may come from http headers or other sources of mime information, and might be affected by automatic type conversions performed by either the browser or extensions. this property is read-only. index the index of the tab relative to other tabs in the application window. this property can be set to change its ...
dev/panel - Archive of obsolete content
</body> <script src="./my-panel.js"></script> </html> here's a script that uses volcan.js to get the selected tab and display its url: // my-panel.js var content = document.getelementbyid("content"); window.addeventlistener("message", function(event) { var debuggee = event.ports[0]; volcan.connect(debuggee). then(listtabs). ...
...the messages actors can accept are methods of those objects. the message type becomes the method name. ...
...ebugging protocol are volcan.js objects. the messages actors can accept are methods of those objects. the message type becomes the method name. for example, the root actor object has a method listtabs and the stylesheet actor object has a method getstylesheets. any additional parameters sent in the message become arguments to the method. if a message is expected to get a reply, then the method re
turns a promise which is fulfilled with the reply. if the message reply in the remote debugging protocol would contain an actor id, then in volcan.js the object that fulfills the promise contains that actor instance. if the message reply contains some json object, then in volcan.js the object that fulfills the promise includes a corresponding json object. if an actor can send notifications, as in the...
event/target - Archive of obsolete content
given options and registers listeners for the ones that look like event listeners. on(type, listener) registers an event listener that is called every time events of specified type are emitted. worker.on('message', function (data) { console.log('data received: ' + data) }); parameters type : string the type of event. listener : function the listener function that processes the event. ...
...ters listeners for the ones that look like event listeners. on(type, listener) registers an event listener that is called every time events of specified type are emitted. worker.on('message', function (data) { console.log('data received: ' + data) }); parameters type : string the type of event. listener : function the listener function that processes the event. ...
...the type of event. listener : function the listener function that processes the event. re
turns eventtarget : re
turns the eventtarget instance once(type, listener) registers an event listener that is called only once: the next time an event of the specified type is emitted. parameters type : string the type of event. listener : function the listener function that processes the event. re
turns eventtarget : re
turns the eventtarget instance removelistener(type, listener) removes an event listener for the given event type. parameters type : string the type of event. listener : function the listener function that processes the event. re
turns eventtarget : re
turns the eventtarget instance off() an alias for removelistener. ...
test/utils - Archive of obsolete content
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 callback. if the callback is defined, then the afterfn is considered asynchronous, and the callback must be invoked before the next test runs. ...
...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 callback. if the callback is defined, then the afterfn is considered asynchronous, and the callback must be invoked before the next test runs. ...
...ns. waituntil(predicate, interval) waituntil re
turns a promise that resolves upon the predicate re
turning a truthy value, which is called every interval milliseconds. parameters predicate : function a function that gets called every interval milliseconds to determine if the promise should be resolved. interval : number the frequency in milliseconds to execute predicate. defaults to 10. re
turns promise : waituntil re
turns a promise that becomes resolved once the predicate re
turns a truthy value. the promise cannot be rejected. ...
ui/button/action - Archive of obsolete content
destroying buttons when you've finished with a button, destroy it by calling its destroy() method. after that, any attempts to access any of its properties or to call any of its methods will throw exceptions. globals constructors actionbutton(options) creates an a...
...again. you can use the strings "window" or "tab" as shortcuts. for example, this add-on: creates a button with a default label opens a new tab sets a new label only for the new tab logs the result of accessing the global label, the window-specific label, and each of the 2 tab-specific labels va...
...you wish to set a specific state, or the string "tab" to select the currently active tab. state : object, null include this parameter only if you are setting state. it is an object containing all the properties you wish to set. for example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); to reset state, pass null: button.state("tab", null); re
turns state : if you have passed the second state argument to make this function a setter, it re
turns undefined. otherwise, it functions as a getter and re
turns the button's state for the specified object. this logs the state for the button associated with the currently active tab: console.log(button.state("tab")); this object represents a snapshot of the state at the time state() is called. it is ...
ui/button/toggle - Archive of obsolete content
updating checked you can update a toggle button's checked property in just the same way you update its other properties, but there's one extra thing you need to keep in mind. the checked property is not only updated directly by assignment, but is also updated when th...
...again. you can use the strings "window" or "tab" as shortcuts. for example, this add-on: creates a button with a default label opens a new tab sets a new label only for the new tab logs the result of accessing the global label, the window-specific label, and each of the ...
...you wish to set a specific state, or the string "tab" to select the currently active tab. state : object, null include this parameter only if you are setting state. it is an object containing all the properties you wish to set. for example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); to reset state, pass null: button.state("tab", null); re
turns state : if you have passed the second state argument to make this function a setter, it re
turns undefined. otherwise, it functions as a getter and re
turns the button's state for the specified object. this logs the state for the button associated with the currently active tab: console.log(button.state("tab")); this object represents a snapshot of the state at the time state() is called. it is ...
util/deprecate - Archive of obsolete content
experimental functions to deprecate code. globals functions deprecatefunction(fun, msg) dump to the console the error message given in the second argument, prefixed with "deprecated:", and print the stacktrace; then execute the function passed as first argument and re
turns its value. it does not raise an exception, but just displays the error message and continues to execute the function. ...
... this function is mostly used to flag usage of deprecated functions that are no longer available. ...
...alue. it does not raise an exception, but just displays the error message and continues to execute the function. this function is mostly used to flag usage of deprecated functions, that are still available but which we intend to remove in a future release. parameters fun : function the function to execute after the error message msg : string the error message to display re
turns * : the re
turned value from fun deprecateusage(msg) dump to the console the error message given, prefixed with "deprecated:", and print the stacktrace. it does not raise an exception, but just displays the error message and re
turns. this function is mostly used to flag usage of deprecated functions that are no longer available. parameters msg : string the error message to display ...
Display a Popup - Archive of obsolete content
html. you can run content scripts in the panel: although the script running in the panel can't directly access your main add-on code, you can exchange messages between the panel script and the add-on code. in this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the re
turn key, the contents of the <textarea> is sent to the main add-on code. the main add-on code logs the message to the console. the add-on consists of seven files: package.json: created when you run jpm init index.js: the main add-on code, that creates the button and panel get-text.js: the content script that interacts with the panel content text-entry.html: the panel content itself, specified ...
....port.emit("show"); }); // listen for messages called "text-entered" coming from // the content script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. text_entry.port.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); the content script "get-text.js" looks like this: // when the user hits re
turn, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; }...
... if you use a toggle button, you can attach the panel to the button. learning more to learn more about the panel module, see the panel api reference. to learn more about buttons, see the action button and toggle button api reference. ...
Localization - Archive of obsolete content
have four plural localizations: # ru-ru translations tomato_id[one]= %d помидор tomato_id[few]= %d помидора tomato_id[many]= %d помидоров tomato_id= %d помидоры the localization module itself understands the cldr definitions for each language, enabling it to map between, for example, "2" in the code and "few" in the ru-ru.properties file. then it retrieves and re
turns the localization appropriate for the count you supplied. placeholders the l10n module supports placeholders, allowing you to insert a string which should not be localized into one which is. the following "en-us" and "fr" ".properties" files include placeholders: # en-us translations hello_id= hello %s! # fr translations hello_id= bonjour %s ! to use placeholders, supply the placeholder st...
...ions. the label attribute of each option is displayed to the user. if the locale file has a entry with the value of the label attribute prefixed with "{name}_options." as its key, where {name} is the name of the preference, its value is used as a localized label. using identifiers if the localization system can't find an entry for a particular identifier using the current locale, then it just re
turns the identifier itself. this has the nice property that you can write localizable, fully functional add-ons without having to write any locale files. you can just use the default language strings as your identifier, and subsequently supply .properties files for all the additional locales you want to support. for example, in the case above you could use "hello!" as the identifier, and just have ...
...you can just use the default language strings as your identifier, and subsequently supply .properties files for all the additional locales you want to support. for example, in the case above you could use "hello!" as the identifier, and just have one .properties file for the "fr" locale: hello!= bonjour ! then when the locale is "en-us", the system would fail to find a .properties file, and re
turn "hello!". however, this approach makes it difficult to maintain an add-on which has many localizations, because you're using the default language strings both as user interface strings and as keys to look up your translations. this means that if you want to change the wording of a string in the default language, or fix a typo, then you break all your locale files. locale updater the locale u...
File I/O - Archive of obsolete content
nts.utils.import("resource://gre/modules/fileutils.jsm"); var file = fileutils.getfile("tmpd", ["suggestedname.tmp"]); file.createunique(components.interfaces.nsifile.normal_file_type, fileutils.perms_file); // do whatever you need to the created file alert(file.path); user input via nsifilepicker the file picker component, nsifilepicker, can be used to open standard open / save dialogs. it re
turns the user-specified file as nsifile. nsifile and path strings you can use nsifile.path to get a platform-specific path string, for example "c:\windows\system32" or "/usr/share". to get a url of a file, use nsiioservice.newfileuri(): // file is nsifile components.utils.import("resource://gre/modules/services.jsm"); var url = services.io.newfileuri(file); // url is a nsiuri; to get the string "...
...efore 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! re
turn; } // the file data is contained within inputstream. // you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read with content type hint it's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous i/o). in this case an nsicha...
...s.classes["@mozilla.org/intl/scriptableunicodeconverter"]. createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = "utf-8"; var istream = converter.converttoinputstream(data); // the last argument (the callback) is optional. netutil.asynccopy(istream, ostream, function(status) { if (!components.issuccesscode(status)) { // handle error! re
turn; } // data has been written to the file. }); copy a stream to a file this function copies all of the data from an input stream to a file asyncronously. it overwrites the file if it is there, and if it is not there it creates a file then writes into it. it takes an nsiinputstream and an nsifile as arguments, and uses netutil.jsm and fileutils.jsm. the callback argument is optional. functi...
On page load - Archive of obsolete content
oad or unload. ...
...ener("domcontentloaded", this.onpageload, false); }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered the event var win = doc.defaultview; // win is the window for the doc // test desired conditions and do something // if (doc.nodename != "#document") re
turn; // only documents // if (win != win.top) re
turn; //only top window. ...
... onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered the event var win = doc.defaultview; // win is the window for the doc // test desired conditions and do something // if (doc.nodename != "#document") re
turn; // only documents // if (win != win.top) re
turn; //only top window. // if (win.frameelement) re
turn; // skip iframes/frames alert("page is loaded \n" +doc.location.href); } } window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myextension.init(); },false); references if you need to have a more complicated listener (not just onload), use progress listeners. see also domcontentlo...
Delayed Execution - Archive of obsolete content
note: if an nsitimer is garbage collected, it will be deactivated and its callbacks will not fire. ...
....org/timer;1", "nsitimer", "initwithcallback"); function delay(timeout, func) { let timer = new timer(function () { // remove the reference so that it can be reaped. delete delay.timers[idx]; func(); }, timeout, ci.nsitimer.type_one_shot); // store a reference to the timer so that it's not reaped before it fires. ...
...er so that it's not reaped before it fires. let idx = delay.timers.push(timer) - 1; re
turn idx; } delay.timers = []; function repeat(timeout, func) { let timer = new timer(function () { func(); }, timeout, ci.nsitimer.type_repeating_slack); // store a reference to the timer so that it's not reaped before it fires. ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
on. registering your components this article explains how to register xpcom components in gecko 2.0 and later. building it as mentioned above, you'll probably want to build your extension immediately after creating your idl files in order to generate the c++ stubs for your component implementations. i'm assuming that you've already built firefox successfully. if not, re
turn immediately to the beginning of this article and don't come back til you have a functioning firefox.exe. do not pass go. do not collect $200. still here? okay, now we have to modify your .mozconfig (in the /mozilla/ root directory) so that your extension is built along with mozilla. add the following line at the end of the file: ac_add_options --enable-extensions=default,myextension...
...le; }; place the idl file in the public/ directory of your project or subproject. in the src/ directory, place the javascript file that implements the component. the component implementation will include the methods for retrieving the path or file for the extension's home directory: mylocation.prototype = { queryinterface: function(iid) { if (iid.equals(nsisupports)) re
turn this; if (iid.equals(myilocation)) re
turn this; components.re
turncode = components.results.ns_error_no_interface; re
turn null; }, get locationfile() { re
turn __location__.parent.parent; } } this assumes that the component resides in a subdirectory of the extension directory (by convention, this directory is called components/). the parent property of __loca...
... if (iid.equals(myilocation)) re
turn this; components.re
turncode = components.results.ns_error_no_interface; re
turn null; }, get locationfile() { re
turn __location__.parent.parent; } } this assumes that the component resides in a subdirectory of the extension directory (by convention, this directory is called components/). the parent property of __location__ re
turns the components/, and the parent of this is the extension directory. the last step is to modify the makefile of the source directory where you placed your javascript file so that it is copied into the appropriate location in the extension: export:: $(install) $(srcdir)/*.js $(final_target)/components now you can instantiate an instance of this component and use the locationfile p...
Custom about: URLs - Archive of obsolete content
boutpage_id = 'aa132730-2278-11e5-867f-0800200c9a66'; // make sure you generate a unique id from https://www.famkruithof.net/uuid/uuidgen const aboutpage_word = 'myaboutpage' const aboutpage_uri = 'data:text/html,hi this is the page that is shown when navigate to about:myaboutpage'; // const aboutpage_uri = 'chrome://myaboutaddon/content/index.html'; class aboutpage { static get classid() { re
turn components.id(`{${aboutpage_id}}`); } static get classdescription() { re
turn aboutpage_description; } static get contractid() { re
turn `@mozilla.org/network/protocol/about;1?what=${aboutpage_word}`; } static get queryinterface() { re
turn xpcomutils.generateqi([ci.nsiaboutmodule]); } constructor() { object.freeze(this); } geturiflags(auri) { re
turn ci.nsiaboutmodule.allow_scr...
...appinfo.version, '47.*') > 0) { const uri = services.io.newuri(aboutpage_uri, null, null); // greater than or equal to firefox48 so asecurity_or_aloadinfo is aloadinfo channel = services.io.newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = services.io.newchannel(aboutpage_uri, null, null); } channel.originaluri = auri; re
turn channel; } } class factory { constructor(component) { this.component = component; this.register(); object.freeze(this); } createinstance(outer, iid) { if (outer) { throw cr.ns_error_no_aggregation; } re
turn new this.component(); } register() { cm.registerfactory(this.component.classid, this.component.classdescription, ...
... factory.unregister(); // .... } and there you have it, your own custom about page. ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
one" settimeout("alert('attack!'); format_computer(); alert('done');", 100); as a general rule of thumb, just don't pass code around as strings and execute it by calling eval, settimeout and friends. alternative: use (anonymous) functions you can always create a small anonymous function to pass around instead. closures will ensure the code is still valid, even if your outer function already re
turned from execution. addeventlistener("load", function() { myaddon.init(); myaddon.onload(); }, true); function doxhr() { //... var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a new utility function that you may use to (partially) bind parameters to functions. addev...
... var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a new utility function that you may use to (partially) bind parameters to functions. addeventlistener("load", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() re
turns a new function. this is important to know in particular when you later want to call removeeventlistener: you'll have to pass the resulting function from the first .bind() call. calling .bind() again with removeeventlistener will not work. also, calling .bind() in a tight (inner) loop should be avoided for performance reasons, as calling .bind() does require some work and memory. overriding/ext...
...addtab = function() { // execute some action before the original function call. try { myaddon.onaddtab(arguments[0]); } catch (ex) { /* might handle this */ } // execute original function. var rv = _original.apply(gbrowser, arguments); // execute some action afterwards. try { myaddon.doneaddtab(rv); } catch (ex) { /* might handle this */ } // re
turn the original result re
turn rv; }; })(); this is admittedly a bit more verbose, but at the same time it should be easier to understand. you don't have to parse what the resulting function will look like in your mind. there won't be any problems if various add-ons override the same function (using this method). you don't have to care about parameter naming (or changes in naming in fut...
Connecting to Remote Content - Archive of obsolete content
synchronous mode. 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 re
turned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an xml document, the responsexml property will hold an xmldocument object that can be manipulated using dom methods. sometimes the server doesn't specify an xml content-type header, which is necessary f...
...t text = aevent.target.responsetext; let jsobject = json.parse(text); window.alert(jsobject.shops[1].name); // => "orange" window.alert(jsobject.total); // => 2; }; the javascript object can also be serialized back with the stringify method. let string = json.stringify(jsobject); xml content xml is possibly the most popular data interchange format. ...
...xsldocument = domparser.parsefromstream( filestream, null, filestream.available(), "text/xml"); // import the xslt stylesheet to the xslt processor xsltprocessor.importstylesheet(xsldocument); finally, you can either use nsixsltprocessor.transformtodocument() or nsixsltprocessor.transformtofragment() methods to transform the xml document. the nsixsltprocessor.transformtodocument() method re
turns a dom document with the results of the transformation, whereas, the nsixsltprocessor.transformtofragment() method re
turns a dom documentfragment node. in this example code, the first child of the xul document is appended to a xul element after the transformation. request.onload = function(aevent) { let responsexml = aevent.target.responsexml; let xulnode; // transform the xml document to...
Custom XUL Elements with XBL - Archive of obsolete content
ld is "private". a property is a little more robust. it is defined using a getter and setter method, allowing read-only and write-only properties, as well as more complex behavior. there are two properties defined in our binding, which are just meant for easier access to the two text attributes in the element. ...
...ss to the two text attributes in the element. we use the shorthand version of the property tag: <property name="name" onget="re
turn this.getattribute('name');" onset="this.setattribute('name', val);" /> there's a less compact version of the property tag that should be used if the getter or setter code involves more than one line of code: <property name="name"> <getter><![cdata[ re
turn this.getattribute('name'); ]]></getter> <setter><![cdata[ this.setattribute('name', val); ]]></setter> </property> properties can be accessed just the same as fields, and they're the ones we prefer for public members. when you add a node to a xul document using an xbl binding, all normal dom operations can be performed on it. you can move it around, delete it or clone it. but ther...
...perations, you must set it as an attribute and not an internal value. methods our "person" binding has a single method that removes the item from the list: <method name="remove"> <parameter name="aevent" /> <body><![cdata[ this.parentnode.removechild(this); ]]></body> </method> as you can see, it's very easy to define a method and the parameters it takes. you can also have a re
turn value using the re
turn keyword, just like on regular js code. the method uses the parent node to remove the person node. simple enough. you can do almost anything from xbl code, including using xpcom components, js code modules and available chrome scripts. the main setback is that you can't have script tags defined in a binding, so you depend on the scripts that have been included in the xul fi...
Adding preferences to an extension - Archive of obsolete content
ions dialog. please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the preferences button for your extension in the add-ons list. establish the defaults in order to set a default preference for the stock to monitor, we need to add a new folder to our extension's package, called "defaults", which in
turn contains another folder called "preferences". inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the ...
...references, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above. the javascript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface. to do that, we need to reimplement our code into an object. that involves
turning each function into a member of the stockwatcher class. let's take a look at each function in the class. startup() the stockwatcher.startup() function is called when our extension is first loaded. its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information p...
...her shutdown tasks we need to perform. shutdown: function() { this.prefs.removeobserver("", this); }, observe() the stockwatcher.observe() function is called whenever an event occurs on the preference branch we're watching. for details on how observers work, read up on the nsiobserver interface. observe: function(subject, topic, data) { if (topic != "nspref:changed") { re
turn; } switch(data) { case "symbol": this.tickersymbol = this.prefs.getcharpref("symbol").touppercase(); this.refreshinformation(); break; } }, the topic parameter indicates what type of event occurred. if it's not nspref:changed, we simply ignore the event, since all we're interested in is changes to the values of our preferences. once we've ...
Creating a dynamic status bar extension - Archive of obsolete content
rl, true); httprequest.onload = inforeceived; httprequest.send(null); } the httprequest variable will contain an xmlhttprequest object. this object is used to configure and run an http request on a web server, which we'll use to fetch the stock quote data. the fullurl variable is the complete url to use when requesting a stock quote. in this case, we're using yahoo's comma-separated values re
turn to fetch easily-parsed stock quote data for google (ticker symbol 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...
...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 re
turn. inforeceived() when the server responds to our request, our the inforeceived() function, which is embedded inside refreshinformation(), gets called automatically. we embed this function inside refreshinformation() so that its variable scope includes the variables used by that function. due to the way javascript works, if inforeceived() were outside refreshinformation(), it would not have access ...
...en: ' + fieldarray[5] + ' | ' + 'low: ' + fieldarray[6] + ' | ' + 'high: ' + fieldarray[7] + ' | ' + 'vol: ' + fieldarray[8]; } } the first thing we do here is get the status bar panel into the variable samplepanel by calling the document.getelementbyid() dom function. we need this so that we can make changes to the status bar panel itself. we then fetch the result re
turned by the web server into the variable output from the xmlhttprequest.responsetext property. the text we receive back from the server looks something like this: "goog",414.20,"5/1/2006","1:36pm",-3.74,417.85,419.44,412.19,4760215 we then parse the text. we use the split() string function to split the comma-separated value string into its individual parts, with each field in a separate element in...
Dehydra Object Reference - Archive of obsolete content
tes: __attribute__((user("customstring"))). variable objects dehydra presents ast nodes as variables. these types are used to represent variables, functions, assignments, etc. the following properties are usually available: property type description .name string the function or variable name. .type type object the type of this function or variable. .isstatic boolean flag .isre
turn boolean flag the variable is being re
turned. .isdecl boolean flag the variable is being declared (local variables only). .assign array of variable objects this variable is the lhs of an assignment. the value is an array of values that were assigned. .isfcall boolean flag the variable is being used as a function call. .arguments array of variable objects arguments used to make a functi...
...tes the aggregate type(class/struct) in the type system that this variable is a member of. .fieldof variable object provides the object being dereferenced, in the ast system. applicable when accessing member variables or nonstatic member functions of aggregate types, e.g. the "foo" variable would be a .fieldof membervar/fn in foo->membervar or foo->memberfn(). note that when constructing the re
turn value of a function (e.g. re
turn t();), no container variable is available; in this case, .isre
turn will be true (see function variable). variables can identified by their dehydradecl() prototype. function variable function objects are an extension of variable objects. the following additional properties are available on functions: property type description .isvirtual true or "pure" tr...
... types, true if the type stores unsigned values .bitfieldbits integer if the type represents a bitfield, the number of bits used by the bitfield .bitfieldof number type object if the type represents a bitfield, the base type of the bitfield. function type these represent the types functions and methods in the type system: property type description .type type object the function re
turn type. .parameters array of type objects the parameter types for the function. .isexplicit boolean flag true for constructors declared using the c++ explicit keyword template objects property type description .name string the name of the template, for example "nscomptr". .arguments array an array where arguments are either strings representing c++ constants or type objects. l...
Drag and Drop Example - Archive of obsolete content
e value of this attribute as the data of the drag. the boardobserver will need three functions, getsupportedflavours, ondragover and ondrop. the ondrop function will grab the data from the drag session and create a new element of the appropriate type. ...
...in this case, it only accepts text. we don't need to do anything special for the ondragover function, so no code is added in its body. the ondrop handler first uses the createelement function to create a new element of the type stored in the drag session. next, appendchild is called to add the new element to the stack, which is the...
... </window> var listobserver = { ondragstart: function (event, transferdata, action) { var txt = event.target.getattribute("elem"); transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/unicode", txt); } }; var boardobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("text/unicode"); re
turn flavours; }, ondragover: function (event, flavour, session) {}, ondrop: function (event, dropdata, session) { if (dropdata.data != "") { var elem = document.createelement(dropdata.data); event.target.appendchild(elem); elem.setattribute("left", "" + event.pagex); elem.setattribute("top", "" + event.pagey); elem.setattribute("label", dropdata.data); } ...
Building Firefox with Rust code - Archive of obsolete content
e a beta or custom toolchain build. our goal is to always ship a firefox release build with a stable rust toolchain release. if you don't have rust already, use the rustup tool to install it and update as new releases become available, or use the ./mach bootstrap command. the build system will generate a special 'rust unified library' crate, compiled to a static library (libgkrust.a) which is in
turn linked into xul, so all public symbols will be available to c++ code. if you have new rust libraries that code in libxul calls directly, then you should add the appropriate extern crate lines in toolkit/library/rust/shared/lib.rs, and add those libraries (crates) as dependencies in toolkit/library/rust/cargo.toml. if you want to call code in the "e10s" crate, you would add: extern crate e10s; ...
...vendor command, which installs the dependencies in third_party/rust. be sure the licenses of all dependent crates are compatible. cargo.lock files have also been checked in, so you will need to update those as well when appropriate. crates for unit tests can be added in a similar fashion to the files in toolkit/library/gtest/rust/. ...
... if you need to locally patch a third-party crate, you'll need to add a [replace] section to the referencing cargo.toml to declare that the vendored source shouldn't match the upstream release. ...
Introducing the Audio API extension - Archive of obsolete content
up audio element with 2 channel, 44.1khz audio stream. audiooutput.mozsetup(2, 44100); once this is done, the samples need to be created. those samples have the same format as the ones in the mozaudioavailable event. then the samples are written in the audio stream with the function mozwriteaudio(). it's important to note that not all the samples might get written in the stream. the function re
turns the number of samples written, which is useful for the next writing. you can see an example below: // write samples using a js array var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...]; var numbersampleswritten = audiooutput.mozwriteaudio(samples); // write samples using a typed array var samples = new float32array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numbersampleswritten = audioo...
... a pre-buffer equal to 500 ms, one would write an array of (2 * 44100 / 10) = 8820 samples, and a total of (currentsampleoffset + 2 * 44100 / 2). it's also possible to auto-detect the minimal duration of the pre-buffer, such that the sound is played without interruptions, and lag between writing and playback is minimal. to do this start writing the data in small portions and wait for the value re
turned by mozcurrentsampleoffset() to be greater than 0. var prebuffersize = samplerate * 0.020; // initial buffer is 20 ms var autolatency = true, started = new date().valueof(); ... // auto latency detection if (autolatency) { prebuffersize = math.floor(samplerate * (new date().valueof() - started) / 1000); if (audio.mozcurrentsampleoffset()) { // play position moved? autolatency = false; }...
...ner('loadedmetadata', loadedmetadata, false); function writeaudio(audio) { buffers.push(audio); // if there's buffered data, write that while(buffers.length > 0) { var buffer = buffers.shift(); var written = a2.mozwriteaudio(buffer); // // if all data wasn't written, keep it in the buffers: if(written < buffer.length) { buffers.unshift(buffer.slice(written)); re
turn; } } } </script> ...
Clipboard Test - Archive of obsolete content
<style></style> <style>.description{ display: block; font-size: 13pt; color: #444; font-style: italic; margin-bottom: 7px; } .method>.re
turns{display: none;} .method>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .method>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .method>.name>.param>.name:after{content: " as "; font-weight: normal; } .method>.params{display: block; color:#555;} .method>.params>.param{display: block; margin-bottom:5px;} .method>.params>.param>.name{font-weight:bold; margin-right:.5em; min-width:80px; display:inline-block;} .method>.params>.param>.description{display:inline-block; width:300px; vertical-align:top;margin-right:30px} .method>.params>.param>.type{display:inline-block; width:100px; vertical-align:top;font-weigh...
...vor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)re
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. flavorre
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var my...
...rns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()re
turns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" );var flavs = jetpack.clipboard.getclipboardflavors();// should equal ["html", "text"]console.log( flavs ); ...
File object - Archive of obsolete content
ame name of the file we want to work with. directories and pipelines are considered special files. pipelines either begin or end with the pipe (|) symbol. description filenames are specified as strings that have an implementation defined format. use of standard "file:" urls is encouraged. if no argument is supplied to the constructor, the current working directory is the file object that is re
turned. examples of possible prefix strings are "/" to indicate the unix root directory, "c:" to specify a windows drive letter, and "file:" to indicate a file url. when a file is constructed, leading and trailing spaces are removed from the filename, so new file(" abc.txt ") just creates a file called abc.txt. filenames starting and ending with the pipe symbol (|) are interpreted as pipes. rea...
...t a new location. file.renameto() removes the file. file.flush() flushes the operating system's write buffers for the file and blocks until any pending data has been committed to disk. file.seek() moves the file position pointer forward or backwards. file.read() read a fixed number of bytes from the file. file.readln() read line from the file. file.readall() read the entire file in, re
turning an array of lines. file.write() write bytes to the file. file.writeln() write bytes to the file, followed by a line separator, flushing the buffer if file.hasautoflush. file.writeall() writes an array of lines to the file, obeying the same semantics as writeln. file.list() get a list of files, potentially matching a regular expression filter, from the file. only has meaning when the fi...
...eying the same semantics as writeln. file.list() get a list of files, potentially matching a regular expression filter, from the file. only has meaning when the file is a directory. file.mkdir() create a directory. directory will be created in the same directory as the file, unless the file is a directory, in which case, the directory will be created in that directory. xxx file.tostring() re
turns the canonical path to the file. file.tourl() re
turns a file:// url describing the file relative to the local file system. url is uri-encoded. examples example: hello, world file.output.writeln("hello, world"); example: writing a new file var file = new file("myfile.txt"); file.open("write,create", "text"); file.writeln("the quick brown fox jumped over the lazy dogs"); file.close(); exam...
Using Breakpoints in Venkman - Archive of obsolete content
ve been set, along with the line number where the function begins whose code is being stopped. using breakpoints to debug when you set a breakpoint, you give venkman (or whatever debugger you're using) the opportunity to display information about the execution environment. one of the most important aspects of debugging a script or software program is the ability to examine variables—function re
turn values, errors, counters, variable scopes—as they change over the course of the script execution. the onflipx function in figure 1, for example, uses the variable newsign to figure out what image to use for the fish. when you set a breakpoint at line 81, you can start animation on the web page in the browser window and see venkman stop execution as it enters the onflipx function. stopped there,...
...egardless of result causes venkman to continue normal execution after running the breakpoint script. this can be useful to try out additional code, on the fly. stop regardless of result causes venkman to stop execution after executing the breakpoint script, allowing you to inspect program state. stop if result is true effectively makes this a conditional breakpoint. ...
...er executing the breakpoint script, allowing you to inspect program state. stop if result is true effectively makes this a conditional breakpoint. if the breakpoint script re
turns a true value (it doesn't have to strictly be a boolean true, any non-null, non-empty string, non-zero, non-undefined, and non-false value will do), execution will continue normally. if, on the other hand, the script re
turns a false value, venkman will stop execution at that point. early re
turn from caller with result will cause the function that the breakpoint is set in to re
turn the value of the breakpoint script as its result, immediatley after the breakpoint script completes. the pass exceptions to caller checkbox allows you to pass exceptions thrown by the breakpoint script directly to the caller. normally,...
modDateChanged - Archive of obsolete content
summary re
turns whether file has been modified since a certain date. method of file object syntax boolean moddatechanged (filespecobject asourcefolder, number anolddate); parameters the moddatechanged method has the following parameters: asourcefolder a filespecobject representing the file to be queried. anolddate a double representing the date. re
turns a boolean value indicating whether the file has been modified since the input date or has not. description most often, the date passed in as the second parameter in moddatechanged is the re
turned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared. example filesource1 = getfolder("program", "file1.txt"); filesource2 = getfolder("p...
...date or has not. description most often, the date passed in as the second parameter in moddatechanged is the re
turned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared. example filesource1 = getfolder("program", "file1.txt"); filesource2 = getfolder("program", "file2.txt"); err1 = file.moddate(filesource1); // the baseline re
turned err2 = file.moddatechanged(filesource1, err1); logcomment("file.moddatechanged should re
turn 'false' = " + err2); // the reason it expects false is we're comparing // the re
turn 'time stamp' value for // file1.txt with the actual file1.txt itself. ...
... baseline re
turned err2 = file.moddatechanged(filesource1, err1); logcomment("file.moddatechanged should re
turn 'false' = " + err2); // the reason it expects false is we're comparing // the re
turn 'time stamp' value for // file1.txt with the actual file1.txt itself. // thus, no change in 'time stamp' values. err3 = file.moddatechanged(filesource2, err1); logcomment("file.moddatechanged should re
turn 'true' = " + err2); // the reason it expects true is we're comparing // the re
turn 'time stamp' value for // file1.txt with another file, file2.txt, with a different // 'time stamp' value. ...
Methods - Archive of obsolete content
the xpinstall api. the majority of this api is now deprecated and as of gecko 1.9 no longer available. extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. methods dircreate creates a new directory. dirgetparent re
turns an object representing the parent directory. dirremove removes a directory. dirrename renames the specified directory. copy makes a copy of the specified file. diskspaceavailable re
turns the amount of disk space available in bytes. exists re
turns a boolean value indicating whether the specified file exists or not. execute queues a file for executing as part of the installation proces...
...nting the parent directory. dirremove removes a directory. dirrename renames the specified directory. copy makes a copy of the specified file. diskspaceavailable re
turns the amount of disk space available in bytes. exists re
turns a boolean value indicating whether the specified file exists or not. execute queues a file for executing as part of the installation process. isdirectory re
turns a boolean value indicating whether an object is a directory. isfile re
turns a boolean value indicating whether an object is a file. moddate re
turns a number representing the last modified date of the given file. moddatechanged specifies whether the last modification on a file is older than a specified date move moves a file from one location to another. remove removes a file. rename ...
...er an object is a directory. isfile re
turns a boolean value indicating whether an object is a file. moddate re
turns a number representing the last modified date of the given file. moddatechanged specifies whether the last modification on a file is older than a specified date move moves a file from one location to another. remove removes a file. rename renames a file in place. size re
turns the size of the file in bytes. windowsshortcut creates a windows shortcut for a file. macalias creates a macintosh alias for a file. windowsgetshortname re
turns the windows shortname of the path. windowsregisterserver registers dlls with the registry. ...
confirm - Archive of obsolete content
lacement - the underlying implementation can freely decide where each of the three buttons is placed. the following examples show the result of calling confirm() with three buttons 0='a', 1='b' and 2='c'. firefox on linux mozilla application suite on win32 it is therefore recommended to only use two buttons wherever possible, and to keep in mind that button 1 has the same re
turn value as "window closed" (see below). abutton0title custom title for button 0. abutton1title custom title for button 1. abutton2title custom title for button 2. acheckmsg a string to display as a checkbox label. acheckstate an object with a boolean value property representing the state of the checkbox: when the dialog...
... value property is updated according to the checkbox. var check = { value: false }; var button = confirm("are you sure you want to install foobar 0.1?", "confirm", std_yes_no_buttons, null, null, null, "install fluxcompensator 0.4 as well", check); re
turns the re
turn value is an integer indicating which button the user selected: value button 0 'cancel' or button 1. also: user closed the dialog window 1 'ok' or button 0 2 the third button previous versions of the xpinstall api stated the re
turn value of confirm() to be a boolean. that is incorrect, confi...
...alue is an integer indicating which button the user selected: value button 0 'cancel' or button 1. also: user closed the dialog window 1 'ok' or button 0 2 the third button previous versions of the xpinstall api stated the re
turn value of confirm() to be a boolean. that is incorrect, confirm() always re
turned a plain integer (in pre-gecko-1.8 versions either 0 or 1). notes the preferred method for detecting support for custom dialog boxes is querying the existence of the button constants. other approaches (e.g. buildid comparisons) are not recommended. if ("button_pos_0" in install) { // use extended confirm() method } else { // use classic confirm() method } ...
isKeyWritable - Archive of obsolete content
iskeywritable re
turns whether the given registry key is writable or not. method of winreg object syntax boolean iskeywritable( string key); parameters the method has the following parameter: key a string representing the path to the key re
turns a boolean value: true if the key is writable; false if not. ...
...lean iskeywritable( string key); parameters the method has the following parameter: key a string representing the path to the key re
turns a boolean value: true if the key is writable; false if not. ...
... the following parameter: key a string representing the path to the key re
turns a boolean value: true if the key is writable; false if not. ...
keyExists - Archive of obsolete content
keyexists re
turns whether the key exists. method of winreg object syntax boolean keyexists ( string key); parameters the method has the following parameter: key a string representing the path to the key re
turns boolean value description if the user does not have read access to the given key, this will also re
turn false. ...
...e method has the following parameter: key a string representing the path to the key re
turns boolean value description if the user does not have read access to the given key, this will also re
turn false. ...
... key a string representing the path to the key re
turns boolean value description if the user does not have read access to the given key, this will also re
turn false. ...
valueExists - Archive of obsolete content
valueexists re
turns whether a value for the given key exists. method of winreg object syntax boolean valueexists ( string key, string value ); parameters the method has the following parameters: key a string representing the path to the key. value a string representing the value being queried. re
turns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
... representing the path to the key. value a string representing the value being queried. re
turns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
...ue a string representing the value being queried. re
turns boolean value: true if the key exists and the user has read access to it, otherwise false. ...
Installer Script - Archive of obsolete content
ilable(dirpath); 7. // convert the available disk space into kilobytes 8. spaceavailable = parseint(spaceavailable / 1024); 9. // do the verification 10. if(spaceavailable < spacerequired) 11. { 12. logcomment("insufficient disk space: " + dirpath); 13. logcomment(" required : " + spacerequired + " k"); 14. logcomment(" available: " + spaceavailable + " k"); 15. re
turn(false); 16. } 17. re
turn(true); 18. } 19. var srdest = 17311; 20. var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); 21. logcomment("initinstall: " + err); 22. var communicatorfolder = getfolder("program"); 23. logcomment("communicatorfolder: " + communicatorfolder); 24. if (verifydiskspace(communicatorfolder, srdest)) 25. { 26. err = adddirectory("program", ...
...der, srdest)) 25. { 26. err = adddirectory("program", 27. "6.0.0.2000110807", 28. "bin", // jar source folder 29. communicatorfolder, // target folder 30. "", // target subdir 31. true ); // force flag 32. logcomment("adddirectory() re
turned: " + err); 33. // create the plugins folder next to mozilla 34. var pluginsfolder = getfolder("plugins"); 35. if (!fileexists(pluginsfolder)) 36. { 37. var ignoreerr = dircreate(pluginsfolder); 38. logcomment("dircreate() re
turned: " + ignoreerr); 39. } 40. else 41. logcomment("plugins folder already exists"); 42. var cf = getfolder("chrome"...
...isterchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/messenger/"); 57. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/navigator/"); 58. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/aim/"); 59. if (err==success) 60. { 61. err = performinstall(); 62. logcomment("performinstall() re
turned: " + err); 63. } 64. else 65. { 66. cancelinstall(err); 67. logcomment("cancelinstall() due to error: " + err); 68. } 69. } 70. else 71. cancelinstall(insufficient_disk_space); ...
Dynamically modifying XUL-based user interface - Archive of obsolete content
ons javascript defines the behavior, using dom apis to access the xul document. so what are the document object model apis? they are the interfaces that are used in any interaction of a script and a document. if you have ever written a script that interacts with a xul (or html) document, you have already used dom calls. the most well known dom method is probably document.getelementbyid(), which re
turns an element, given its id. you may also have used other calls, such as element.setattribute(), or, if you wrote an extension, the addeventlistener() method. all of these are defined in dom. there are also dom methods that create, move, or delete elements from a document. they will be demonstrated in a later section. right now, let's learn what a document is. what is a document? a document is a ...
...ument. appendchild() appends the node after all other nodes, while insertbefore() inserts the node before the node referenced by its second parameter. function createmenuitem(alabel) { const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createelementns(xul_ns, "menuitem"); // create a new xul menuitem item.setattribute("label", alabel); re
turn item; } var popup = document.getelementbyid("mypopup"); // a <menupopup> element var first = createmenuitem("first item"); var last = createmenuitem("last item"); popup.insertbefore(first, popup.firstchild); popup.appendchild(last); you can also use appendchild() and insertbefore() to move existing elements. for example you could move the item labeled "first item" to the end of popup by adding t...
...w widgets. widgets defined in xbl may choose to define some content which is inserted to the bound element, when the binding is attached. this content, called anonymous content, is not accessible through normal dom methods. you need to use the methods of nsidomdocumentxbl interface instead. for example: // gets the first anonymous child of the given node document.getanonymousnodes(node)[0]; // re
turns a nodelist of anonymous elements with anonid attribute equals el1 document.getanonymouselementbyattribute(node, "anonid", "el1"); see getanonymousnodes and getanonymouselementbyattribute in the xbl reference for more information. once you have an anonymous node, you can use regular dom methods to navigate and manipulate the rest of the nodes of that binding. see also a related chapter on dom...
Introduction to XUL - Archive of obsolete content
t values. javascript is most safely kept in a separate file and included in the xul file <html:script language="javascript" src="our.js"/> or relegated to the contents of a cdata section, to prevent the xml parser from choking on javascript which may look like xml content (a < character, for instance.) <html:script type="application/javascript"> <![cdata[ function lesser(a,b) { re
turn a < b ? a : b; } ]]> </html:script> javascript extensions mozilla has found it necessary to make a few extensions to javascript, to support new features not conceived of in a strictly browser environment. these are currently nonstandard, of course, and subject to change for now. individual extensions are described in individual documents dedicated to the features requiring the extensions...
...e interfaces can be found in the directory mozilla/rdf/content/public/idl. xuldocument xuldocument extends document in a fashion similar to htmldocument's extension interface xuldocument : document { element getelementbyid(in domstring id); nodelist getelementsbyattribute(in domstring name, in domstring value); }; getelementbyid works like html's getelementbyid. ...
... xulelement also supports other methods for hooking up broadcasters; a function performed automatically by the xul document loader and therefore not normally used in javascript. xul elements as mentioned above, a xul file is mostly an html file with xml syntax. ...
appendNotification - Archive of obsolete content
if another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. keep in mind that this is all xul so using html elements for styling might still need additional css in order to work as you might expect. ...
...ription is an object with the following properties: accesskey - the accesskey to appear on the button callback - function to be called when the button is activated. this function is passed three arguments: the <notification> the button is associated with the button description as passed to appendnotification. the element which was the target of the button press event. if the re
turn value from this function is not true, then the notification is closed. the notification is also not closed if an error is thrown. label - the label to appear on the button popup - the id of a popup for the button. if null, the button is not a button popup (e.g. a menu). the type property must also be set to "menu", or "menu-button". isdefault - if true, this is the default button. there c...
... .getmostrecentwindow("navigator:browser"); } if (typeof gbrowser === "undefined") { //if there is no gbrowser defined, get it var gbrowser = window.gbrowser; } function testnotificationbutton1callback(thenotification, buttoninfo, eventtarget) { window.alert("button 1 pressed"); //prevent notification from closing: re
turn true; }; function testnotificationbutton2callback(thenotification, buttoninfo, eventtarget) { window.alert("button 2 pressed"); //do not prevent notification from closing: }; function testnotificationcallback(reason) { window.alert("reason is: " + reason); }; let notifybox = gbrowser.getnotificationbox(); let buttons = []; let button1 = ...
removeItemAt - Archive of obsolete content
« xul reference home removeitemat( index ) re
turn type: element removes the child item in the element at the specified index. the method re
turns the removed item. ...
... « xul reference home removeitemat( index ) re
turn type: element removes the child item in the element at the specified index. the method re
turns the removed item. ...
... « xul reference home removeitemat( index ) re
turn type: element removes the child item in the element at the specified index. the method re
turns the removed item. ...
PopupEvents - Archive of obsolete content
nupopup. otherwise, the adjustfilemenu function would be called whenever the outer menupopup is opened and when the inner menupopup is opened. the bubbling of events applies to all popup events. the popupshown event the popupshown event is fired once a popup is already visible. when calling either the openpopup or openpopupatscreen methods, the popup will not actually be open before that method re
turns. the popupshown event will be fired when the ui is updated and the popup is visible. one possible use of the popupshown event is to open another menu. this technique, as shown in the following example, is needed if you wish to open a submenu programmatically. this is because you cannot open a submenu directly without first opening the parent menu. <script> function openfilemenu() { var fileme...
...menu programmatically. this is because you cannot open a submenu directly without first opening the parent menu. ...
...menu();"/> when the button is pressed, the openfilemenu function is called. within this function, a popupshown event listener is attached to the 'file' menu using the addeventlistener method. this will cause the filemenuopened function to be called when the popupshown event is fired on the 'file' menu. the filemenuopened function first checks that the target of the event is the right popup and re
turns early if not. next, the popupshown event listener is removed again. we need to make sure to do this to ensure that the event listener isn't added multiple times. finally, we use a similar technique as the openfilemenu function to open the 'open' submenu. the result is a button that opens both the outer menu and the inner menu. the popuphiding event when a popup is closed, the popuphiding event i...
Adding Methods to XBL-defined Elements - Archive of obsolete content
any though, in which case the method would take no parameters. the body element contains the script that is executed when the method is called. the names of the parameters are defined as variables in the script as if they had been passed as parameters. for example, the following javascript function would be written as an xbl method like so: function getmaximum(num1,num2) { if (num1 <= num2) re
turn num2; else re
turn num1; } xbl: <method name="getmaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 <= num2) re
turn num2; else re
turn num1; </body> </method> this function, getmaximum, re
turns the largest of the values, each passed as a parameter to the method. note that the less-than symbol has to be escaped because otherwise it would look like the...
...hild elements inside it. each element of the array stores each direct child element of the xbl-defined element. this special property cannot be accessed directly. instead, you must call the document's getanonymousnodes() method: var value=document.getanonymousnodes(element); here, 'element' should be set to a reference to the element that you want to get the anonymous content of. the function re
turns an array of elements, which is the anonymous content. to get elements below that, you can use the regular dom functions because they aren't hidden. note that it is possible for an xbl-bound element to be placed inside another one, in which case you will have to use the getanonymousnodes() function again. the following example creates a row of buttons: <binding id="buttonrow"> <content> <...
...o use the getanonymousnodes() function again. the following example creates a row of buttons: <binding id="buttonrow"> <content> <button label="yes"/> <button label="no"/> <button label="sort of"/> </content> </binding> to refer to each button, you can use the getanonymousnodes() function, passing it a reference to the element the binding is bound to as the parameter. in the re
turned array, the first button is stored in the first array element (getanonymousnodes(element)[0]), the second button is stored in the second array element and the third button is stored in the third array element. for code inside a binding method, you can pass 'this' as the parameter to getanonymousnodes(). the next example can be used to create text with a label. the method 'showtitle' can be used...
Creating Dialogs - Archive of obsolete content
s necessary because different platforms have a specific order in which the buttons appear. example dialog source view <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" ondialogaccept="re
turn dook();" ondialogcancel="re
turn docancel();"> <script> function dook(){ alert("you pressed ok!"); re
turn true; } function docancel(){ alert("you pressed cancel!"); re
turn true; } </script> <description value="select a button"/> </dialog> you may place any elements that you wish in a dialog. the dialog element has some additional attributes that windows do not have. the butto...
...ing more information you can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes. if you try the example above, you will find that the dook() function is called when the ok button is pressed and the docancel() function is called when the cancel button is pressed. the two functions dook() and docancel() both re
turn true, which indicates that the dialog should be closed. if the dialog shouldn't be closed, false should be re
turned instead. this would be used, for example, if an invalid value was entered in a field in the dialog. amongst other useful attributes are buttonlabelaccept - label to appear on the accept button egsave buttonaccesskeyaccept - access key to use for the accept button egs defaultbu...
...features <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="mydialog" title="my dialog" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="window.sizetocontent();" buttons="accept,cancel" buttonlabelaccept="set favourite" buttonaccesskeyaccept="s" ondialogaccept="re
turn dosave();" buttonlabelcancel="cancel" buttonaccesskeycancel="n" ondialogcancel="re
turn docancel();"> <script> function dosave(){ //dosomething() re
turn true; } function docancel(){ re
turn true; } </script> <dialogheader title="my dialog" description="example dialog"/> <groupbox flex="1"> <caption label="select favourite fruit"/> <radio id="orange" label="oranges ...
Manipulating Lists - Archive of obsolete content
h implement this interface have these methods. this includes the menulist, radiogroup and tabs elements. for example, to add a new item to a menulist, you can use the same syntax as for a listbox. the right kind of element will be appended in each situation. list selection the nsidomxulselectcontrolelement interface provides two additonal properties, selectedindex and selecteditem. the former re
turns the index of the selected item while the latter re
turns the selected element. for instance the selecteditem of a menulist will be the menuitem that is selected. if no item is selected, selectedindex will re
turn -1, while selecteditem will re
turn null. getting the selected item these two properties are commonly inspected during a select event, as in the following example: example 2 : source vi...
... select event is also fired when a radio button in a radiogroup is selected and when a tab is selected in a tabs element. however, menulists do not fire the select event; instead you can listen to the command event to handle when an item is selected. for the tabs element, it is often more convenient to use functions of the tabbox element instead. it also has a selectedindex function which will re
turn the index of the selected tab. however, to get the selected item, use the tabbox's selectedtab property instead. or, use the selectedpanel property to get the selected panel, that is, re
turn the content associated with the tab. changing the selection all of the selection related properties described above may also be assigned a new value to change the selection. in the next example, the selecte...
...teditems property holds a list of the items that are selected, while the selectedcount property holds the number of items selected. typically, you will use these properties to iterate over the list and perform some operation for each item. be careful when iterating over the selected items; if you modify the items in the list while iterating, the list will change and the selection properties may re
turn different values. this is one reason why it is useful to manipulate the list by the item rather than by index. deleting selected items the following example shows a method of deleting the selected items properly: example 4 : source view <script> function deleteselection(){ var list = document.getelementbyid('thelist'); var count = list.selectedcount; while (count--){ var item = list...
RDF Datasources - Archive of obsolete content
nc-rdf#extension the extension of the file, including the period. this property is only available on platforms that use file extensions. possible files roots nc:filesroot top level of the filesystem (usually the list of drives) a file url by using a file url for the ref attribute, you can select a specific directory to be re
turned. for example, you might use file:///windows or files:///usr/local. the files datasource is an example of a datasource that determines its resources only when necessary. we don't want every file in the filesystem to be determined before the data is displayed. instead, only the files and directories that the tree element (or other elements) will need to display at a given time will be de...
...row> </treeitem> </treechildren> </rule> </template> </tree> here, the data has been generated from the file. the ref attribute has been set to the root element in the rdf file, which is the top-level seq. this will give us a complete list of animals. if we wanted to, we could set the ref attribute to any of the other about attribute values to limit the set of data that is re
turned. for example, to display only the reptiles, use a value of http://www.some-fictitious-zoo.com/reptiles. setting the ref attribute example the example below shows how to display a particular piece of an rdf datasource by setting the ref attribute. example 3 : source view <window id="example-window" title="history list" xmlns:animals="http://www.some-fictitious-zoo.com/rdf#" xmlns="http:/...
...oo.com/rdf#name"/> </menupopup> </rule> </template> </button> </window> in this case only the mammals are desired, so we select the uri of the mammals list. you will notice that the value of the ref attribute in the example is http://www.some-fictitious-zoo.com/mammals which corresponds to one of the seq elements in the rdf file. this causes only the descendants of this list to be re
turned. two rules have been used here. the first rule catches all the resources that have their animals:specimens attribute set to 0. you can see this attribute in the rdf file on each of the description elements. some of them have a value of 0. so in these cases, rule one will match. because rule one has no content, nothing will be displayed for these ones. this is an effective way to hide data that ...
Tree Selection - Archive of obsolete content
the tree's view property and then retrieve the view's selection property. you can use the methods of the selection object to retrieve the set of selected items or modify the selection. because the selected items in a multiple selection tree are not necessarily contiguous, you can retrieve each block of contigous selections using the getrangecount() and getrangeat() functions. the first function re
turns the number of selection ranges there are. if only one value is selected, this value will be 1. you would then write a loop for the number of ranges, calling getrangeat() to get the actual indices of the start and end of the range. the getrangeat() function takes three arguments. the first is the range index. the second is an object which will be filled in by the function with the index of t...
...ar start = new object(); var end = new object(); var numranges = tree.view.selection.getrangecount(); for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("item " + v + " is selected."); } } we create two objects called 'start' and 'end'. then, we iterate over the set of ranges, the number of which is re
turned by the getrangecount() function. the getrangeat() function is called passing the range index and the start and end objects. this function will fill in the start and end indicies by assigning them to the 'value' property. so if the first range is from the third item to the seventh item, 'start.value' will be 2 (remember that indices start with 0, so we subtract one.) and 'end.value' will be 6. a...
...es by assigning them to the 'value' property. so if the first range is from the third item to the seventh item, 'start.value' will be 2 (remember that indices start with 0, so we subtract one.) and 'end.value' will be 6. an alert is displayed for each index. if you just want to find out if a specific row is selected, use can use the isselected() function. it takes a row index as an argument and re
turns true if that row is selected. alert(tree.view.selection.isselected(3)); modifying the tree selection the selection object has a number of functions which may be used to change the selection. the simplest function is the select() function, which deselects any rows that are currently selected and selects one specific row. for example, the following code will select the row at index 5: tree.view.s...
Trees - Archive of obsolete content
single widget which draws all of the data in the tree. this contrasts with the listbox, where individual listitem and listcell tags are used to specify the rows in the listbox. in a tree, all of the data to be displayed is supplied by a separate object, called a tree view. when it comes time to display a cell, the tree widget will call out to this tree view to determine what to display, which in
turn will be drawn by the tree. the tree is smart enough to only ask for information from the view for those rows that need to be displayed. this allows the view to be optimized such that it only needs to load the data for displayed content. for instance, a tree might have thousands of rows, yet most of them will be scrolled off the border of the tree, hidden from view. this means that the tree is sca...
... nested in the order above. the tags define the data to be displayed in the tree body. in this case, the tree uses the built-in tree view, called a content tree view, which uses the labels and values specified on these elements as the data for the tree. when the tree needs to display a row, the tree asks the content tree view for a cell's label by calling the view's getcelltext function, which in
turn gets the data from the label of the appropriate treecell. however, the three elements listed above are not displayed directly. they are used only as the source for the data for the view. thus, only a handful of attributes apply to the treeitem and related elements. for instance, you cannot change the appearance of the tree rows using the style attribute or with other css properties and the box r...
...ecolumnpicker attribute on the tree and set it to true if you would like to hide this button. if this button is hidden, the user will not be able to hide columns. make sure that you set an id attribute on each column or the hiding and showing of columns will not work in all versions of mozilla. the treechildren element surrounds all of the rows. inside the body are individual rows, which may in
turn contain other rows. for a simpler tree, each row is created with the treeitem and treerow elements. the treerow element surrounds all of the cells in a single row, while a treeitem element would surround a row and all of its children. trees with nested rows are described in the next section. inside the rows, you will put individual tree cells. these are created using the treecell element. you ca...
XPCOM Examples - Archive of obsolete content
element which calls the function switchfocus() with a parameter of the element that was selected from the menu. the function switchfocus(): first gets a reference to a component which implements the window mediator interface. next, we get the id attribute for the element. we can use the value of the id attribute as the resource. the function getwindowforresource() takes the resource and re
turns a window that matches it. this window, stored in the switchwindow variable, is the same as the javascript window object. this means that you can call any of the functions provided by it, one of which is the focus() function. cookies next, we will get a list of cookies that have been saved in the browser. the cookie service can be used for such a purpose. it implements the nsicookiemanager int...
... is opened, as indicated by the onpopupshowing attribute on the menulist. the first two lines of getcookies() get the menulist and remove all of the existing items in the menu. this is done because getcookies() is called every time the menu is opened and we don't want to leave the old items there each time. next, the cookie manager is retrieved. ...
...n the menu. this is done because getcookies() is called every time the menu is opened and we don't want to leave the old items there each time. next, the cookie manager is retrieved. the cookie manager has an enumerator method which re
turns an object which implements nsisimpleenumerator. this can be used to iterate over all of the cookies. an enumerator has a hasmoreelements() method which will re
turn true until we get to the last cookie. the getnext() method gets a cookie and moves the enumerator index to the next cookie. since an enumerator just re
turns a generic object, we need to queryinterface() it to an nsicookie before we can use it. in this case, we just use the instanceof operator to accomplish this. finally, an item is added to the menu for the cookie. the host, name and value proper...
XUL accessibility guidelines - Archive of obsolete content
s, move the focus to the next element before disabling, hiding, or destroying the focus element. the following example shows a javascript function that can be called before destroying an element to check for focus and move it if necessary. function movefocus(element) { if(element == document.commanddispatcher.focusedelement) { document.commanddispatcher.advancefocus(); re
turn true; } re
turn false; } changing focus unexpectedly can confuse or disorient users. a common example of this occurrence in the us is with phone number form fields. us phone numbers are often displayed on the web in two main formats xxx-xxx-xxxx or (xxx) xxx-xxxx. to enforce this pattern some forms provide three form fields. the problem occurs when a developer decides to add functiona...
...ould be able to reference a complete description of all major functionality of an application. also provide details on how to use long or complex help documentation. alerts provide accessible alerts for presenting important information to the user. use scripting or the notificationbox element to flag alerts. avoid using audio or visual alerts alone to signal urgent events. users who have audio
turned down or off and users who are deaf or hard of hearing may not be able to recognize audio only alerts. users with visual disabilities will not be able to observe alerts that are purely visual (unless such alerts are presented in functional text that is accessible to a screen reader). interactive elements avoid small targets, which are difficult to see and click on. verify that the layout and c...
...so have descriptive transcripts. usually captioning and transcribing go hand in hand, once you have one its easy to produce the other. learn more captioning webaim article: web captioning overview webaim resource: captioning resources animation animation, movement, and audio can all be distracting to some users with attention disorders. provide a mechanism for
turning media and movement on and off. flickering or flashing is not only just annoying to everyone, but at a rate more than 3 cycles per second it can cause a seizure in users with photosensitive epilepsy. if flickering or flashing is necessary then warn the user before it is displayed. testing media ensure that media alternatives are available in an accessible format. other issues custom widget...
arrowscrollbox - Archive of obsolete content
th scrolling for the corresponding arrowscrollbox. if not set explicitly, it will fall back to the smoothscroll attribute and then to the toolkit.scrollbox.smoothscroll preference. currently, smooth scrolling supports horizontal arrowscrollboxes only. tabindex type: integer gets and sets the value of the tabindex attribute. methods ensureelementisvisible( element ) re
turn type: no re
turn value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is. if the item is already visible, no scrolling occurs. scrollbyindex( lines ) re
turn type: no re
turn value scrolls the contents of the arrowscrollbox by a certain number of lines. a line is a single element. use a positive value as the lines ar...
...use a positive value as the pixels argument to scroll forward that many pixels, or a negative value to scroll backward that many pixels. ...
...use a positive value as the pixels argument to scroll forward that many pixels, or a negative value to scroll backward that many pixels. ...
editor - Archive of obsolete content
can be used to search for text in the document. webnavigation type: nsiwebnavigation this read-only property contains the nsiwebnavigation object for the document. most of its methods are callable directly on the element itself, such as goback and goforward. it also contains the load constants used by reloadwithflags and loaduriwithflags. methods geteditor( window ) re
turn type: nsieditor re
turns the editing interface for the editor which contains numerous methods for manipulating the document. pass the editor's contentwindow as the argument. gethtmleditor( window ) re
turn type: nsihtmleditor re
turns the html editing interface for the editor which contains methods for manipulating an html document. pass the editor's contentwindow as the argument. makeeditabl...
...specify text or html as the editortype. ...
...specify text or html as the editortype. ...
toolbox - Archive of obsolete content
customtoolbarcount firefox only type: integer the number of custom toolbars currently within the toolbox. externaltoolbars type: array of elements an array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. ...
... ex...
...ild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendcustomtoolbar( name, currentset ) firefox only re
turn type: element adds a custom toolbar to the toolbox with the given name. you can supply a comma-separated list of toolbar item ids as the second argument to add some items by default. the method re
turns the dom element for the created toolbar. collapsetoolbar( toolbar ) not in firefox re
turn type: no re
turn value collapse the given toolbar which should be contained within the toolbox. expandtoolbar( toolbar ) not in firefox re
turn type: no re
turn value expand the given toolbar which should be contained in the toolbox. related elements toolbar, toolbarbutton, toolbargrippy, too...
Mozilla release FAQ - Archive of obsolete content
s used milestone numbers (e.g. the milestone 7 release was known as m7). what is the relation between mozilla versions and netscape versions? the current arrangement between netscape (aol) and the mozilla project is that mozilla develops its own releases, and when netscape (aol) is preparing to make a release, it takes the current version of mozilla, makes modifications, and does its own qa. in re
turn for this, netscape (aol) contributes developers to work on the project. the netscape versions may have a different look/feel than mozilla versions, and also may add proprietary features. the netscape versions are all branded as netscape (aol) products. what resources are available to the mozilla community? webpages mozilla project homepage netscape developer program website mozillazine (ne...
...move the offending portions, and see if that fixes things. if not, post to netscape.public.mozilla.builds problems of this sort are currently most likely to happen in nspr, as it still uses the classic build system. it's doubtful that this will happen in the main tree. /usr/include/stdlib.h:196: previous declaration of `seed48' see section 3.7 nothing looks much like an error, except something re
turned error status your compiler has a switch (probably) that prints everything it's doing (i.e. programs spawned), which might help you find out what arguments it's passing to ld, or whatever, and thus perhaps enlighten you as to the problem. on gcc, try gcc -v (rest of command line). how long will mozilla take to build? a long time, but this will depend quite a bit on your system. ram will probably...
... of making a usable system. reinvention of the wheel is a poor use of volunteers. why don't we make a way to compress all the components of a webpage into one big file, and send that across? this breaks a lot of things that work currently. it is very difficult to determine what components of the webpage actually needs -- certain images may be shared between several pages, the user may have images
turned off or lack capabilities to use a certain type of media. dynamically generated pages make this nearly impossible. devising a system that would handle all of these situations would make web servers more complex, slower, and likely hurt the transfer time that this proposal is attempting to save. also, progressive display of the webpage would be completely gone with this idea. for these reasons, t...
NPN_GetURLNotify - Archive of obsolete content
the current plug-in instance. url pointer to the url of the request. can be of any type, such as http, ftp, news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns 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_u...
...or 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 re
turns 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 target is non-null, th...
...tify() as soon as possible. for requests that complete successfully: if the target is non-null, the browser calls npp_urlnotify() after it has finished loading the url. if the target is null, the browser calls npp_urlnotify() after closing the stream by calling npn_destroystream(). if this function is called with a target parameter value of _self or a parent to _self, this function should re
turn nperr_invalid_param. this is the only way to notify the plug-in once it is deleted. warning: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), npn_geturlnotify() does not notify the plug-in if notifydata is null. see bug 638367 for details. see also npn_geturl() npn_posturl() npn_posturlnotify() npp_urlnotify() npp ...
NPN NewStream - Archive of obsolete content
npmimetype type, const char* target, npstream** stream); parameters the function has the following parameters: instance pointer to current plug-in instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description npn_newstream creates a new stream of data produced by the plug-in and consumed by the browser. the mime parameter is the mime type of the plug-in to create. a plug-in can create another instance of itself by s...
...the plug-in can use this object in subsequent calls to npn_write to write data into the stream. when the plug-in has written all of its data into the stream, npn_destroystream terminates the stream and deallocates the npstream object. the target parameter is the name of the target window or frame, or one of several special target names. ...
...to the stream. when the plug-in has written all of its data into the stream, npn_destroystream terminates the stream and deallocates the npstream object. the target parameter is the name of the target window or frame, or one of several special target names. for parameter values and information about how to use them, see npn_geturl. if the new stream has the target of _self, this function should re
turn an invalid_param np error. see also npp_newstream, npp_write, npp_destroystream, npstream, npp ...
NPN_RequestRead - Archive of obsolete content
pp_write(). syntax #include <npapi.h> nperror npn_requestread(npstream* stream, npbyterange* rangelist); parameters the function has the following parameters: stream stream of type np_seek from which to read bytes. rangelist range of bytes in the form of a linked list of npbyterange objects, each of which specifies a request for a range of bytes. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description for a seekable stream, the browser sends data only in response to requests by the plug-in. the plug-in calls npn_requestread() to request data from a seekable stream. the plug-in can use this function to make one or more requests for range...
...uests multiple ranges (either through a list of npbyterange objects in a single call to npn_requestread(), or multiple calls to npn_requestread()), the browser can write individual ranges in any order, and with any number of npp_writeready() and npp_write() calls. the plug-in must allocate npbyterange objects, which the browser copies if necessary. the plug-in can free these as soon as the call re
turns. seekable streams are created by calling npp_newstream() with np_seek as the stype mode. the plug-in can call npn_requestread() on streams that were not initially in np_seek mode as long as the stream is inherently seekable; npn_requestread() automatically changes the mode to np_seek. if the stream is not inherently seekable, the stream must have been put in np_seek mode initially (since the ...
...e stream is inherently seekable; npn_requestread() automatically changes the mode to np_seek. if the stream is not inherently seekable, the stream must have been put in np_seek mode initially (since the browser must cache all the stream data on disk in order to access it randomly). if npn_requestread() is called on a stream that is not inherently seekable and not initially in mode np_seek, it re
turns the error code nperr_stream_not_seekable. typically, the only streams that are inherently seekable are those from in-memory or on-disk data, or from http servers that support byte-range requests. see also npp_newstream() npp_writeready() npp_write() npstream ...
NPSavedData - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary block of instance information saved after the plug-in instance is deleted; can be re
turned to the plug-in to restore the data in future instances of the plug-in. syntax typedef struct _npsaveddata { int32 len; void* buf; } npsaveddata; fields the data structure has the following fields: len length in bytes of the buffer pointed to by buf; set by the plug-in. buf pointer to a memory buffer allocated by the plug-in with npn_memalloc(). can be any reasonable size; its contents are private to the plug-in and are not modified by the browser. ...
...s of the buffer pointed to by buf; set by the plug-in. buf pointer to a memory buffer allocated by the plug-in with npn_memalloc(). can be any reasonable size; its contents are private to the plug-in and are not modified by the browser. description the npsaveddata object contains a block of per-instance information that the browser saves after the instance is deleted. this information can be re
turned to another instance of the same plug-in if the user re
turns to the web page that contains it. you can use the plug-in's npp_destroy() function to allocate an npsaveddata object using the npn_memalloc() function, fill in the fields, and re
turn it to the browser as an output parameter. see instance destruction for a code example that shows how to use npsaveddata. if the user revisits a web page t...
...after this, the plug-in is responsible for keeping or deleting the objects as necessary. ...
The global XML object - Archive of obsolete content
xmllist.prototype (xmllist.prototype is actually just xml.prototype) cannot be extended in the same conventional way as other constructors such as object. you can only define methods in xml.prototype and not fields. to add a method to xml.prototype, define xml.prototype.function::methodname or xml.prototype.function::[methodnamestring]. the following example defines the foocount() method, which re
turns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { re
turn this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // re
turns 3 ignorecomments true by default. this property tells e4x to ignore comment nodes when serializing and filtering. this means that if ignorecomments is true, the list re
turned by .comments() will be empty. obs...
...<foo/><foo/><foo/></foobar>.foocount() // re
turns 3 ignorecomments true by default. this property tells e4x to ignore comment nodes when serializing and filtering. this means that if ignorecomments is true, the list re
turned by .comments() will be empty. observe: var element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // re
turns 0 element.toxmlstring(); // re
turns <foo><bar/></foo> xml.ignorecomments = false; element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // re
turns 1 element.toxmlstring(); // re
turns <foo><!-- my comment --><bar/></foo> ignoreprocessinginstructions true by default. this property tells e4x to ignore processing instructions in xml when...
...ns 1 element.toxmlstring(); // re
turns <foo><!-- my comment --><bar/></foo> ignoreprocessinginstructions true by default. this property tells e4x to ignore processing instructions in xml when serializing and filtering. for example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // re
turns <foo><bar/></foo> xml.ignoreprocessinginstructions = false; var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // re
turns <foo><?process x="true"?><bar/><?process x="false"?></foo> ignorewhitespace true by default. ignores whitespace between nodes and leading and trailing whitespace...
Date.prototype.toLocaleFormat() - Archive of obsolete content
nt way. see also the newer version of date.prototype.tolocaledatestring(). this feature has been removed and will no longer work in firefox 58+. see warning: date.prototype.tolocaleformat is deprecated for more information and migration help. syntax dateobj.tolocaleformat(formatstring) parameters formatstring a format string in the same format expected by the strftime() function in c. re
turn value a string representing the given date using the specified formatting. description the tolocaleformat() method provides greater software control over the formatting of the generated date and/or time. names for months and days of the week are localized using the operating system's locale. however, ordering of the day and month and other localization tasks are not handled automatically since...
...t even be adequate. you might consider using some of the more general tolocale* methods of the date object or doing your own custom localization of the date to be displayed using some of the get* methods of the date object instead of using this method. examples using tolocaleformat() var today = new date(); var date = today.tolocaleformat('%a, %b %e, %y'); in this example, tolocaleformat() re
turns a string such as "wednesday, october 3, 2007". note that the format string in this example is not properly localized, which will result in the problems described above. polyfill when using the datejs library you can polyfill date.prototype.tolocaledatestring() like this: if (!date.prototype.tolocaleformat) { (function() { date.prototype.tolocaleformat = function(formatstring) { ...
...uch as "wednesday, october 3, 2007". note that the format string in this example is not properly localized, which will result in the problems described above. polyfill when using the datejs library you can polyfill date.prototype.tolocaledatestring() like this: if (!date.prototype.tolocaleformat) { (function() { date.prototype.tolocaleformat = function(formatstring) { re
turn this.format(formatstring); }; }()); } specifications not part of any standard. ...
VBArray.ubound - Archive of obsolete content
if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. ...
...if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. ...
...not supported in windows 8.x store a...
New in JavaScript 1.8.5 - Archive of obsolete content
e object and properties. bug 492840 object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. object.getownpropertydescriptor() re
turns a property descriptor for a named property on an object. bug 505587 object.keys() re
turns an array of all enumerable properties on an object. bug 307791 object.getownpropertynames() re
turns an array of all enumerable and non-enumerable properties on an object. bug 518663 ob...
... object.freeze() freezes an object: other code can't delete or change any properties. bug 492844 object.isfrozen() determines if an object was frozen. bug 492844 array.isarray() checks if a variable is an array. bug 510537 date.prototype.tojson() re
turns a json format string for a date object. function.prototype.bind() creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507 new ecmascript5 features get and set operators now allows the identifier t...
...g 429507 new ecmascript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 function.apply() can accept any array-like object as the arguments list, instead of only true arrays. strict mode support array.tostring() now works even on non-arrays by either re
turning the result of calling its join() method if one is available or by calling its tostring() method. other standardization work various non-standard syntaxes for defining getters and setters have been removed; ecmascript 5 defined syntax has not been changed. these were all pretty esoteric and rarely used; if this affects you, see this blog post for details.
Number.toInteger() - Archive of obsolete content
syntax number.tointeger(number) parameters number the value to be converted to an integer. ...
... syntax number.tointeger(number) parameters number the value to be converted to an integer. ...
... syntax number.tointeger(number) parameters number the value to be converted to an integer. ...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
ample of code that implements a primitive form of multiple inheritance is shown below. ...
...on addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below. // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { re
turn this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { re
turn this.age; }, setage: function(age) { this.age = age; } } // child class. inherits from namedthing and agedthing // as well as defining address function person(name, age, address){ addparent(this, na...
...this.age; }, setage: function(age) { this.age = age; } } // child class. ...
JavaObject - Archive of obsolete content
in addition, you can explicitly construct a javaobject using the object's java constructor with the packages keyword: new packages.javaclass(parameterlist) javaclassis the fully-specified name of the object's java class. parameters parameterlist an optional list of parameters, specified by the constructor of the java class. description the javaobject object is an instance of a java class that is created in or passed to javascript. ...
...= new java.lang.string("hello, world"); example: accessing methods of a java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public methods of java.lang.string. the following example uses the startswith method to check whether thestring begins with "hello". ...
...orld"); thestring.startswith("hello"); // re
turns true example: accessing inherited methods because getclass is a method of object, and java.lang.string extends object, the string class inherits the getclass method. consequently, getclass is also a method of the javaobject which instantiates string in javascript. ...
Reference - Archive of obsolete content
ting document discussing how to create and use private variables in objects, which is great if you want to protect the various properties within an object from being poked at accidentally. i also just read a document on proper inheritance using apply(). well if you combine the two, you can have inherited private variables: function myclass(){ var property = 5; this.tellme = function(){ re
turn property; } } function myotherclass(){ myclass.apply( this ); } var o = new myotherclass; alert( o.tellme() ); //alerts 5 as you'd expect — the preceding comment was added by psygnisfive (talk – contribs) on 22:23, 4 december 2006 terminology we need a terminology appendix. for example, "script" and "program" are synonymous. so are "current object" and "context object". we could als...
... oppisite as my first thought (see picture above). i say this because now the function is not available in object, as if the inheritance is : object->function->instance but... while also holding in account the previous example where it was avalable in both instances when prototyping object it should be : function->object->instance or (function=object)->instance and ofcourse function == object re
turn false ;) and the following statements also tells me that function == object although math is only an instance of object... which basicly says function != object alert(function instanceof object) //true alert(object instanceof function) //true alert(math instanceof object) //true alert(math instanceof function) //false note that the methods and properties for object in this reference are a...
...1.5 ..." pages to "... javascript 1.6 ..." ? then carefully update all links to the javascript 1.5 pages to link to the javascript 1.6 pages -- unless the links are specifically about javascript 1.5 ? then do it all over again when javascript 1.7, javascript 2.0, javascript xxxxii.1, etc. comes out ? make a footnote on each page, pointing to a page listing "hot new javascript features", which in
turn points to 1 page for 1.6, 1 page for 1.7, etc., listing all the differences from one version to the next ? this would be the simplest thing for us to write. but someone trying write some javascript 2.0, wanting a list of all the features it supports, might be annoyed at having to read through *all* the updates. make a footnote on each page, pointing to a page listing "hot new javascript features...
XForms Custom Controls Examples - Archive of obsolete content
inding id="output-image" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsixformsuiwidget"> <method name="refresh"> <body> var img = document.getanonymouselementbyattribute(this, "anonid", "content"); img.setattribute("src", this.stringvalue); re
turn true; </body> </method> </implementation> </binding> output showing xhtml <binding id="output-xhtml" extends="chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsixformsuiwidget"> <field name="_dom...
... var val = this.stringvalue; var newdom = this.domparser.parsefromstring(val, "text/xml"); var impnode = document.importnode(newdom.firstchild, true); // get content node, clean it, and update it var content = document.getanonymouselementbyattribute(this, "anoni...
...mport it. ...
Troubleshooting XForms Forms - Archive of obsolete content
a prefix must always be specified if the namespace is not the empty namespace. if your binding expression starts with a /, make sure the first thing is the name of the root node of the instance. if your binding expression contains a /, look for any containing xf:group, xf:repeat, xf:input or other elements that set the context node. instance(...) not working be aware that the instance(...) re
turns an element node, and not the document node. so with an instance like this: <xf:instance id="ins2" xmlns=""> <data> <value>42</value> </data> </xf:instance> you should use <output ref="instance('ins2')/value"/> to show the contents of the value element. (specification). repeat and tables not working unfortunately you cannot do: <table> <xf:repeat nodeset="..."> <tr> ...
...> <tr> ... </tr> </xf:repeat> </table> the xhtml modularization does not allow this. you either have to use css tables or repeat attributes, which at the moment are not working properly in the firefox xforms extension :( should be fixed by bug 306247 and bug 280368 respectively. submission not working if you are trying to replace="instance" make sure that the document being re
turned is xml. there will be an error on the javascript console if it is not. on most webservers you cannot use <submission method="post" action="file.xml"> to a static xml file. you need to use method="get", or <instance src="file.xml"> if the instance is always needed. if you are trying to submit to a different domain than the form is loaded from, make sure that you have allowed cross-domain sub...
...domain". read here for more information. conflicts with other plug-ins if you are using the noscript plugin you may notice that your put and/or post requests are being converted to get requests. in order to fix this, go to the noscript options dialog (right-click on the 's' icon on the status bar and select 'options...') and select the advanced tab. the xss sub-tab has the following options:
turn cross-site post requests into data-less get requests anti-xss protection exceptions you can temporarily fix the problem by unchecking the
turn cross-site post requests into data-less get requests check box. alternatively, for a long term fix you can enter an exception pattern in the anti-xss protection exceptions text area. if you are developing on your local machine using apache tomcat for ex...
Anatomy of a video game - Game development
ing a "find the differences between these two similar pictures"-type game. these games present two images to the user; they accept their click (or touch); they interpret the input as a success, failure, pause, menu interaction, etc.; finally, they calculate an updated scene resulting from that input. the game loop is advanced by the user's input and sleeps until they provide it. this is more of a
turn-based approach that doesn't demand a constant update every frame, only when the player reacts. other games demand control over each of the smallest possible individual timeslices. the same principles as above apply with a slight twist: each frame of animation progresses the cycle and any change in user input is caught at the first available
turn. this once-per-frame model is implemented in somet...
...of our new line if the previous one was not empty or terminated. * * let us also assume that mygame is previously defined. */ ;(function () { function main() { mygame.stopmain = window.requestanimationframe( main ); // your main loop contents } main(); // start the cycle })(); we now have a variable declared in our mygame namespace, which we call stopmain, that contains the id re
turned from our main loop's most recent call to requestanimationframe(). at any point, we can stop the main loop by telling the browser to cancel the request that corresponds to our token. window.cancelanimationframe( mygame.stopmain ); the key to programming a main loop, in javascript, is to attach it to whatever event should be driving your action and pay attention to how the different systems inv...
... 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). this value is re
turned as a decimal number accurate to a thousandth of a millisecond. it is known as a domhighrestimestamp but, for all intents and purposes, consider it a floating point number. note: systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. they should provide 0.001ms accuracy if they are capable of it, however. this val...
Building up a basic demo with PlayCanvas editor - Game development
we will add more later! to change its color we'll use the diffuse option in the entity inspector. click diffuse, then select the colored box next to the color label — it will open a color wheel. from here you can click your desired color or enter it in the bottom text field as a hex value. we've chosen a blue color with a hex value of 0095dd — enter this code in the text field and press re
turn for it to be accepted. note: yes, you read that right — you need to enter the hex value without the hash/pound symbol. now we can apply the colored material to the shape by clicking and dragging its icon from the bottom part of the screen (the little dot on the left hand side of the material's name — it can be a bit fiddly to select; just persevere) onto the box on the scene. so, at ...
...add the following line inside this function, to rotate the cube on every frame: this.entity.rotate(dt*10, dt*20, dt*30); in the line above this.entity refers to the object to which the script will be attached (the box); using the dt variable, which cont...
...be on every frame: this.entity.rotate(dt*10, dt*20, dt*30); in the line above this.entity refers to the object to which the script will be attached (the box); using the dt variable, which contains the delta time passed since the previous frame, we can rotate the box by a different amount around all three axes. save the changes using the save button in the top right of the code editor, then re
turn to the main editor tab. here, follow these steps: be sure you have the box selected on the scene. click on add component, then script in the entity inspector. at the bottom of the screen you can see the list of scripts available — for now there's only boxanimation.js — clicking it will add the animation script to the box object. the cylinder now we'll do the same steps for cylinder. f...
Audio for Web games - Game development
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 tra...
...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); re
turn track; } let's also create a playtrack() function, which we can call once a file has been fetched. we need an offset here, so if we have started one file playing, we have a record of how far through to start another file. start() takes two optional parameters. the first is when to commence playback and the second is where, which is our offset. let offset = 0; function playtrack(audiobuffer) ...
... playback and the second is where, which is our offset. ...
Efficient animation for web games - Game development
at any setup or processes that happen between the start of the animation and the callback being processed do not affect the start of the animation, and so that all the animations we start before the frame is processed are synchronised. to save battery life, it is best to only draw when there are things going on, so that would mean calling requestanimationframe (or your refresh function, which in
turn calls that) in response to events happening in your game. unfortunately, this makes it very easy to end up drawing things multiple times per frame. we would recommend keeping track of when requestanimationframe has been called and only having a single handler for it. there aren’t solid guarantees of what order things will be called in with requestanimationframe (though, in our experience, it is...
...ority was to write the code quickly to iterate on gameplay (and we’d certainly recommend doing this). we assumed that our own, naive code was making the game slower than we would like. to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there. ...
...ng the game slower than we would like. to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there. at this point, we
turned to the firefox javascript profiler, and this told us almost exactly what low-hanging-fruit was left to address to improve performance. as it
turned out, the code from some of the things mentioned above; the animation code had some corner cases where redraws were happening several times per frame, and some of the animations caused firefox to need to redraw everything (they were fine in other browsers, as it happens — that particular issue is now fixed). some of the third party code we were using was poorly optimised. a take-away to help...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
invoking the function symbol, which dynamically produces an anonymous, unique value. a symbol may be used as an object property. symbol can have an optional description, but for debugging purposes only. a symbol value represents a unique identifier. for example: // here are two symbols with the same description: let sym1 = symbol("sym") let sym2 = symbol("sym") console.log(sym1 === sym2) // re
turns "false" // symbols are guaranteed to be unique. // even if we create many symbols with the same description, // they are different values. note: if you are familiar with ruby's (or another language) that also has a feature called "symbols", please don’t be misguided. javascript symbols are different. symbol type is a new feature in ecmascript 2015. there is no ecmascript 5 equivalent for ...
...egistry are symbol.for() and symbol.keyfor(); these mediate between the global symbol table (or "registry") and the run-time environment. the global symbol registry is mostly built by javascript's compiler infrastructure, and the global symbol registry's content is not available to javascript's run-time infrastructure, except through these reflective methods. ...
...lobal symbol table (or "registry") and the run-time environment. the global symbol registry is mostly built by javascript's compiler infrastructure, and the global symbol registry's content is not available to javascript's run-time infrastructure, except through these reflective methods. ...
CSS and JavaScript accessibility best practices - Learn web development
. hiding things there are many instances where a visual design will require that not all content is shown at once. for example, in our tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use tab and enter/re
turn to select them). screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it. on the other hand, you shouldn't ...
...eft empty, the submit fails, and an error message box appears to tell you what is wrong. this kind of form validation is unobtrusive — you can still use the form absolutely fine without the javascript being available, and any sensible form implementation will have server-side validation active as well, because it is too easy for malicious users to bypass client-side validation (for example, by
turning javascript off in the browser). the client-side validation is still really useful for reporting errors — users can know about mistakes they make instantly, rather than having to wait for a round trip to the server and a page reload. this is a definite usability advantage. note: server-side validation has not been implemented in this simple demo. we've made this form validation pretty acc...
...to access the zoomed view by keyboard though — to allow that, we've included the last two lines, which run the functions when the image is focused and blurred (when focus stops). this can be done by tabbing over the image, because we've included tabindex="0" on it. the click event is interesting — it sounds mouse-dependent, but most browsers will activate onclick event handlers after enter/re
turn is pressed on a link or form element that has focus, or when such an element is tapped on a touchscreen device. this doesn't work by default however when you allow a non-default-focusable event to have focus using tabindex — in such cases you need to detect specifically when that exact key is pressed (see building keyboard accessibility back in). test your skills! you've reached the end of th...
WAI-ARIA basics - Learn web development
dated. you can for example only get content additions or removals read out. enhancing keyboard accessibility as discussed in a few other places in the module, one of the key strengths of html with respect to accessibility is the built-in keyboard accessibility of features such as buttons, form controls, and links. generally, you are able to use the tab key to move between controls, the enter/re
turn key to select or activate controls, and occasionally other controls as needed (for example the up and down cursor to move between options in a <select> box). however, sometimes you will end up having to write code that either uses non-semantic elements as buttons (or other types of control), or uses focusable controls for not quite the right purpose. you might be trying to fix some bad code you'...
...ple we first looked at in our css and javascript accessibility article (read keeping it unobtrusive for a full recap). at the end of this section we showed that we have included some aria attributes on the error message box that displays any validation errors when you try to submit the form: <div class="errors" role="alert" aria-relevant="all"> <ul> </ul> </div> role="alert" automatically
turns the element it is applied to into a live region, so changes to it are read out; it also semantically identifies it as an alert message (important time/context sensitive information), and represents a better, more accessible way of delivering an alert to a user (modal dialogs like alert() calls have a number of accessibility problems; see popup windows by webaim). an aria-relevant value of all i...
... there are a whole host of other roles that can identify non-semantic element structures as common ui features that go beyond what's available in standard html, for example combobox, slider, tabpanel, tree. you can see a number of useful examples in the deque university code library, to give you an idea of how such controls can be made accessible. let's go through an example of our own. we'll re
turn to our simple absolutely-positioned tabbed interface (see hiding things in our css and javascript accessibility article), which you can find at tabbed info box example (see source code). this example as-is works fine in terms of keyboard accessibility — you can happily tab between the different tabs and select them to show the tab contents. it is also fairly accessible too — you can scroll t...
Cascade and inheritance - Learn web development
pect, so you need to understand how these mechanisms work. also significant here is the concept of inheritance, which means that some css properties by default inherit values set on the current element's parent element, and some don't. this can also cause some behavior that you might not expect. let's start by taking a quick look at the key things we are dealing with, then we'll look at each in
turn and see how they interact with each other and your css. this can seem like a set of tricky concepts to understand. as you get more practice writing css, however, the way it works will become more obvious to you. the cascade stylesheets cascade — at a very simple level this means that the order of css rules matter; when two rules apply that have equal specificity the one that comes last in the...
... effect we would ever want! which properties are inherited by default and which aren't is largely down to common sense. controlling inheritance css provides four special universal property values for controlling inheritance. every css property accepts these values. inherit sets the property value applied to a selected element to be the same as that of its parent element. effectively, this "
turns on inheritance". initial sets the property value applied to a selected element to the initial value of that property. unset resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit, otherwise it acts like initial. note: there is also a newer value, revert, which has limited browser support. note: see origin of css declaratio...
...done — you've started getting familiar with the fundamental mechanics of css. next up, we'll look at selectors in detail. if you didn't fully understand the cascade, specificity, and inheritance, then don't worry! this is definitely the most complicated thing we've covered so far in the course, and is something that even professional web developers sometimes find tricky. we'd advise that you re
turn to this article a few times as you continue through the course, and keep thinking about it. refer back here if you start to come across strange issues with styles not applying as expected. it could be a specificity issue. overview: building blocks next in this module cascade and inheritance css selectors type, class, and id selectors attribute selectors pseudo-classes an...
Legacy layout methods - Learn web development
in the <style> element, add the following code, which gives the wrapper container a width of 980 pixels, with padding on the right hand side of 20 pixels. this leaves us with 960 pixels for our total column/g...
...n4">14</div> </div> now you've got a grid system working, you can simply define the rows and the number of columns in each row, then fill each container with your required content. great! creating a fluid grid our grid works nicely, but it has a fixed width. we really want a flexible (fluid) grid that will grow and shrink with the available space in the browser viewport. to achieve this we can
turn the reference pixel widths into percentages. the equation that
turns a fixed width into a flexible percentage-based one is as follows. target / context = result for our column width, our target width is 60 pixels and our context is the 960 pixel wrapper. we can use the following to calculate a percentage. 60 / 960 = 0.0625 we then move the decimal point 2 places giving us a percentage of 6.2...
... width: 90%; max-width: 980px; margin: 0 auto; } .wrapper { padding-right: 2.08333333%; } .row { display: flex; } .col { margin-left: 2.08333333%; margin-bottom: 1em; width: 6.25%; flex: 1 1 auto; background: rgb(255,150,150); } you can try making these replacements in your own example, or look at our flexbox-grid.html example code (see it running live also). here we are
turning each row into a flex container. with a flexbox-based grid we still need rows in order to allow us to have elements that add up to less than 100%. we set that container to display: flex. on .col we set the flex property's first value (flex-grow) to 1 so our items can grow, the second value (flex-shrink) to 1 so the items can shrink, and the third value (flex-basis) to auto. as our element has ...
create fancy boxes - Learn web development
let's do some fancy boxes. before we start getting into the practical side of it, make sure you are familiar with the css box model. it's also a good idea, but not a prerequisite, to be familiar with some css layout basics. ...
...the feeling that it's a "real" circle. */ padding : 1em; /* the border will make the circle visible. you could also use a background, as backgrounds are clipped by border radius */ border : 0.5em solid black; /* let's make sure we have a square. if it's not a square, we'll get an ellipsis rather than a circle ;) */ width : 4em; height : 4em; /* and let's
turn the square into a circle */ border-radius: 100%; } yes, we get a circle: backgrounds when we talk about a fancy box, the core properties to handle that are background-* properties. when you start fiddling with backgrounds it's like your css box is
turned into a blank canvas you'll fill. before we jump to some practical examples, let's step back a bit as there are two things you should kno...
...and could wish to have more boxes to create even more amazing styles. most of the time, that leads to polluting the dom by adding extra html element for the unique purpose of style. even if it is necessary, it's somewhat considered bad practice. one solution to avoid such pitfalls is to use css pseudo-elements. ...
Styling links - Learn web development
't mean that you shouldn't style links at all, just that you should not stray too far from the expected behaviour. you should at least: use underlining for links, but not for other things. if you don't want to underline links, at least highlight them in some other way. make them react in some way when hovered/focused, and in a slightly different way when activated. the default styles can be
turned off/changed using the following css properties: color for the text color. cursor for the mouse pointer style — you shouldn't
turn this off unless you've got a very good reason. outline for the text outline (an outline is similar to a border, the only difference being that border takes up space in the box and an outline doesn't; it just sits over the top of the background). the outline is...
... note: you are not just limited to the above properties to style your links — you are free to use any properties you like. ...
... own lines. in this case, we are creating a horizontal list of links, so in the third rule we set the display property to inline, which causes the list items to sit on the same line as one another — they now behave like inline elements. the fourth rule — which styles the <a> element — is the most complicated here; let's go through it step by step: as in previous examples, we start by
turning off the default text-decoration and outline — we don't want those spoiling our look. next, we set the display to inline-block — <a> elements are inline by default and, while we don't want them to spill onto their own lines like a value of block would achieve, we do want to be able to size them. inline-block allows us to do this. now onto the sizing! we want to fill up the whole width...
How do I start to design my website? - Learn web development
ction to your web project. summary when starting with a web project, many people focus on the technical side. of course you must be familiar with the technique of your craft, but what really matters is what you want to accomplish. yes, it seems obvious, but too many projects fail not from a lack of technical know-how, but from lack of goals and vision. so when you get an idea and want to
turn it into a website, there are a few questions you should answer before anything else: what exactly do i want to accomplish? how will a website help me reach my goals? what needs to be done, and in what order, to reach my goals? all of this is called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer. active learning th...
...l revolve around the same topic, having everything in one place will help us meet our goals and help our followers connect with us. how can a website help me reach my goals? by answering that, you'll find the best way to reach your goals and save yourself from wasted effort. what needs to be done, and in what order, to reach my goals? now that you know what you want to accomplish, it's time to
turn those goals into actionable steps. as a side note, your goals are not necessarily set in stone. they evolve over time even in the course of the project, especially if you run across unexpected obstacles or just change your mind. rather than go through a long explanation, let's go back to our example with this table: goals things to do let people hear your music ...
...are not web-related (e.g., record music, write articles). often those offline activities matter even more than the web side of the project. in sales, for instance, it's far more important and time-consuming to handle supply, payment, and shipment than to build a website where people can place orders. second, setting out actionable steps leads to new questions you'll need to answer. usually there
turn out to be more questions than we originally thought. (for example, should i learn how to do all this myself, ask someone to do it for me, or use third-party services?) conclusion as you can see, the simple idea "i want to make a website" generates a long to-do list, which only grows longer as you think about it. soon it may look overwhelming, but don't panic. you don't need to answer all the qu...
Other form controls - Learn web development
features, and how to implement them using html. multi-line text fields a multi-line text field is specified using a <textarea> element, rather than using the <input> element. <textarea cols="30" rows="8"></textarea> this renders like so: the main difference between a <textarea> and a regular single line text field is that users are allowed to include hard line breaks (i.e. pressing re
turn) that will be included when the data is submitted. <textarea> also takes a closing tag, and any default text you want it to contain should be put between the opening and closing tags. in contrast, the <input> is an empty element with no closing tag — any default value is put inside the value attribute. note that even though you can put anything inside a <textarea> element (including other htm...
... the meter bar: if the current value is in the prefered part of the range, the bar is green. if the current value is in the average part of the range, the bar is yellow. if the current value is in the worst part of the range, the bar is red. such a bar is created using a <meter> element. this is for implementing any kind of meter, for example a bar showing total space used on a disk, which
turns red when it starts to get full. <meter min="0" max="100" value="75" low="33" high="66" optimum="50">75</meter> the content inside the <meter> element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it. support for <progress> and <meter> is fairly good — there is no support in internet explorer, but other browsers support it well. test ...
...end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: other controls. summary as you'll have seen in the last few articles, there are a lot of different types of available form element. you don't need to remember all of these details at once, and can re
turn to these articles as often as you like to check up on details. now that you have a grasp of the html behind the different available form controls, we'll take a look at styling them. previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling...
The web and web standards - Learn web development
eated openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. ...
...as you go through the learning material presented here, you'll start to learn how this is made possible with some very clever design and implementation work. being a web developer is good the web industry is a very attractive market to enter if you are looking for a job. ...
...adopted a house-building analogy, html would be like the foundations and walls of the house, which give it structure and hold it together. cascading style sheets (css) is a rule-based language used to apply styles to your html, for example setting text and background colors, adding borders, animating things, or laying out a page in a certain way. as a simple example, the following code would
turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice. javascript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3d graphics. the following simple javascript will store...
Responsive images - Learn web development
ge includes a large landscape shot with a person in the middle when viewed on a desktop browser. when viewed on a mobile browser, that same image is shrunk down, making the person in the image very small and hard to see. it would probably be better to show a smaller, portrait image on mobile, which zooms in on the person. the <picture> element allows us to implement just this kind of solution. ...
...in this case, if the viewport width is 799px wide or less, the first <source> element's image will be displayed. if the viewport width is 800px or more, it'll be the second one. the srcset attributes contain the path to the image to display. just as we saw with <img> above, <source> can take a srcset attribute with multiple images referenced, as well as a sizes attribute...
.... so, you could offer multiple images via a <picture> element, but then also offer multiple resolutions of each one. realistically, you probably won't want to do this kind of thing very often. in all cases, you must provide an <img> element, with src and alt, right before </picture>, otherwise no images will appear. this provides a default case that will apply when none of the media conditions re
turn true (you could actually remove the second <source> element in this example), and a fallback for browsers that don't support the <picture> element. this code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below: note: you should use the media attribute only in art direction scenarios; when you do use media, don't also offer media conditions wi...
General asynchronous programming concepts - Learn web development
ing 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 re
turn, and until that happens, the entire program is essentially stopped from the perspective of the user. mac users, for example, sometimes experience this as the spinning rainbow-colored cursor (or "beachball" as it is often called). this cursor is how the operating system says "the current program you're using has had to stop and wait for something to finish up, and it's taking so long that i was w...
... 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 re
turning control to the browser, the browser can appear to be frozen. this is called blocking; the browser is blocked from continuing to handle user input and perform other tasks until the web app re
turns control of the processor. let's look at a couple of examples that show what we mean by blocking. in our simple-sync.html example (see it running live), we add a click event listener to a button so t...
...oth be available at the same time, then we might be ok, but this is unlikely. if task d tries to run when one of its inputs is not yet available, it will throw an error. to fix such problems, browsers allow us to run certain operations asynchronously. features like promises allow you to set an operation running (e.g. the fetching of an image from the server), and then wait until the result has re
turned before running another operation: main thread: task a task b promise: |__async operation__| since the operation is happening somewhere else, the main thread is not blocked while the async operation is being processed. we'll start to look at how we can write asynchronous code in the next article. exciting stuff, huh? keep reading! conclusion modern software design...
Test your skills: Functions - Learn web development
note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...lor of the rectangle. you'll want to clear the canvas before drawing, so that when the code is updated in the case of the live version, you don't get lots of rectangles drawn on top of one another. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. functions 3 in this task, you re
turn to the problem posed in task 1, with the aim of improving it. the three improvements we want you to make are: refactor the code that generates the random number into a separate function called random(), which takes as parameters two generic bounds that the random number should be between, and re
turns the result. update the choosename() function so that it makes use of the random number functi...
...ts we want you to make are: refactor the code that generates the random number into a separate function called random(), which takes as parameters two generic bounds that the random number should be between, and re
turns the result. update the choosename() function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and re
turns the result. print the re
turned result into the paragraph (para)'s textcontent. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and...
What is JavaScript? - Learn web development
ch bad things. note: there are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course. javascript running order when the browser encounters a block of javascript, it generally runs it in order, from top to bottom. this means that you need to be careful what order you put things in. ...
...ine 3) so that when the paragraph is clicked, the updatename() code block (lines 5–8) is run. the updatename() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display. if you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error re
turned in the browser developer console — typeerror: para is undefined. this means that the para object does not exist yet, so we can't add an event listener to it. note: this is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them. interpreted versus compiled code you might hear the terms interpreted and compiled in th...
...n event listener to it. note: this is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them. interpreted versus compiled code you might hear the terms interpreted and compiled in the context of programming. in interpreted languages, the code is run from top to bottom and the result of running the code is immediately re
turned. you don't have to transform the code into a different form before the browser runs it. the code is received in its programmer-friendly text form and processed directly from that. compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. for example, c/c++ are compiled into machine code that is then run by the computer. the program i...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
ext, go and find the newly-created todomvc/app/components/footer.js file and update it to the following: import component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class footercomponent extends component { @service('todo-data') todos; } now we need to go back to our todo-data.js file and add some functionality that will allow us to re
turn the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the “clear completed” functionality needs). in todo-data.js, add the following getter underneath the existing all() getter to define what the incomplete todos actually are: get incomplete() { re
turn this.todos.filter(todo => { re
turn todo.iscompleted ...
...he following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.incomplete.length === 1}} todo {{else}} todos {{/if}} left this will give us an error, however — in ember, these simple if statements can currently only test for a truthy/falsy value, not a more complex expression such as a comparison. to fix this, we'll have to add a getter to todo-data.js to re
turn the result of this.incomplete.length === 1, and then call that in our template. add the following new getter to todo-data.js, just below the existing getters. note that here we need this.incomplete.length, not this.todos.incomplete.length, because we are doing this inside the service, where the incomplete() getter is available directly (in the template, the contents of the service has been made ...
...that here we need this.incomplete.length, not this.todos.incomplete.length, because we are doing this inside the service, where the incomplete() getter is available directly (in the template, the contents of the service has been made available as todos via the @service('todo-data') todos; line inside the footer class, hence it being this.todos.incomplete.length there). ...
Introduction to client-side frameworks - Learn web development
n unordered list element (a <ul>). how do we make it? that could look something like this: function buildtodoitemel(id, name) { const item = document.createelement('li'); const span = document.createelement('span'); const textcontent = document.createtextnode(name); span.appendchild(textcontent) item.id = id; item.appendchild(span); item.appendchild(builddeletebuttonel(id)); re
turn item; } here, we use the document.createelement() method to make our <li>, and several more lines of code to create the properties and children it needs. the tenth line of this snippet references another build function: builddeletebuttonel(). it follows a similar pattern to the one we used to build a list item element: function builddeletebuttonel(id) { const button = document.createelement(...
...eeds. the tenth line of this snippet references another build function: builddeletebuttonel(). it follows a similar pattern to the one we used to build a list item element: function builddeletebuttonel(id) { const button = document.createelement('button'); const textcontent = document.createtextnode('delete'); button.setattribute('type', 'button'); button.appendchild(textcontent); re
turn button; } this button doesn't do anything yet, but it will later once we decide to implement our delete feature. the code that will render our items on the page might read something like this: function rendertodolist() { const frag = document.createdocumentfragment(); state.tasks.foreach(task => { const item = buildtodoitemel(task.id, task.name); frag.appendchild(item); }); whi...
... a webpage interactive. larger code base and abstraction frameworks allow you to write more declarative code – and sometimes less code overall – by dealing with the dom interactions for you, behind the scenes. this abstraction is great for your experience as a developer, but it isn't free. in order to translate what you write into dom changes, frameworks have to run their own code, which in
turn makes your final piece of software larger and more computationally expensive to operate. some extra code is inevitable, and a framework that supports tree-shaking (removal of any code that isn't actually used in the app during the build process) will allow you to keep your applications small, but this is still a factor you need to keep in mind when considering your app's performance, especially ...
Componentizing our Svelte app - Learn web development
emitted from child components. so props flow down from parent to child and events bubble up from child to parent. this pattern establishes a two-way flow of information, which is predictable and easier to reason about. let's look at how to emit our own events to re-implement the missing delete button functionality. to create custom events we'll use the createeventdispatcher utility. this will re
turn a dispatch() function that will allow us to emit custom events. when you dispatch an event you have to pass the name of the event and, optionally, an object with additional information that you want to pass to every listener. this additional data will be available on the detail property of the event object. note: custom events in svelte share the same api as regular dom events. moreover, you ca...
... let's create an update() function that will receive the changes and will emit an update event with the modified todo. add the following, again to the bottom of the <script> section: function update(updatedtodo) { todo = { ...todo, ...updatedtodo } // applies modifications to todo dispatch('update', todo) // emit update event } here we are using the spread syntax to re
turn the original todo with the modifications applied to it. next we'll create different functions to handle each user action. when the todo is in editing mode, the user can save or cancel the changes. when it's not in editing mode, the user can delete the todo, edit it, or toggle its status between completed and active. add the following set of functions below your previous function to handl...
...onent. in its <script> section, add this handler: function updatetodo(todo) { const i = todos.findindex(t => t.id === todo.id) todos[i] = { ...todos[i], ...todo } } we find the todo by id in our todos array, and update its content using spread syntax. in this case we could have also just used todos[i] = todo, but this implementation is more bullet-proof, allowing the todo component to re
turn only the updated parts of the todo. next we have to listen for the update event on our <todo> component call, and run our updatetodo() function when this occurs to change the name and completed status. update your <todo> call like this: {#each filtertodos(filter, todos) as todo (todo.id)} <todo {todo} on:update={e => updatetodo(e.detail)} on:remove={e => removetodo(e.detail)} ...
Implementing feature detection - Learn web development
(typically an entry point into using the api or other feature you are detecting for) exists in its parent object. if("geolocation" in navigator) { ... } property on element create an element in memory using document.createelement() and then check if a property exists on it. the example shown is a way of detecting html5 canvas support. function supports_canvas() { re
turn !!document.createelement('canvas').getcontext; } if(supports_canvas()) { ... } method on element re
turn value create an element in memory using document.createelement() and then check if a method exists on it. if it does, check what value it re
turns. see dive into html5 video formats detection test. property on element retains value create an element in mem...
...s, check what value it re
turns. see dive into html5 video formats detection test. property on element retains value create an element in memory using document.createelement(), set a property to a certain value, then check to see if the value is retained. see dive into html5 <input> types detection test. note: the double not in the above example (!!) is a way to force a re
turn value to become a "proper" boolean value, rather than a truthy/falsy value that may skew the results. the dive into html5 detecting html5 features page has a lot more useful feature detection tests besides the ones listed above, and you can generally find a feature detection test for most things by searching for "detect support for your-feature-here" in your favorite search engine. bear in mind...
...is applied to, which contains results of the feature detects as true/false properties. for example, load up our modernizr-css.html example in your browser, then try going to your javascript console and typing in modernizr. followed by some of those class names (they are the same here too). for example: modernizr.flexbox modernizr.websqldatabase modernizr.xhr2 modernizr.fetch the console will re
turn true/false values to indicate whether your browser supports those features or not. let's look at an example to show how you'd use those properties. first of all, make a local copy of the modernizr-js.html example file. attach the modernizr library to the html using a <script> element, as we have done in previous demos. put it above the existing <script> element, which is attaching the google...
Strategies for carrying out testing - Learn web development
etection, later on in the course). you might also notice that the button isn't usable using only the keyboard — this also needs to be remedied. maybe we could use some javascript to implement a keyboard control for the toggle, or use some other method entirely? these test criteria are useful, because: they give you a set of steps to follow when you are performing tests. they can be easily
turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to active the button using your mouse, and then the keyboard...") — see user testing, below. they can also provide a basis for writing automated tests. it is easier to write such tests if you know exactly what you want to test, and what the success conditions are (see using an automation tool to automate b...
...velopment server, so you are not putting the final site or change live until it is finished. you should get them to follow some steps and report the results they get. it is useful to provide a set of steps (sometimes called a script) so that you get more reliable results pertaining to what you were trying to test. we mentioned this in the what are you going to test section above — it is easy to
turn the test criteria detailed there into steps to follow. for example, the following would work for a sighted user: click the question mark button using the mouse on your desktop computer a few times. refresh the browser window. select and activate the question mark button using the keyboard on your desktop computer a few times. tap the question mark button a few times on your touch screen devi...
...t of users, providing a useful mechanism for getting a feature tested by a subset of users without the need for a separate development server. an example is django waffle flags. summary after reading this article you should now have a good idea of what you can do to identify your target audience/target browser list, and then effectively carry out cross-browser testing on that list. next we'll
turn our attention to the actual code issues your testing might uncover, starting with html and css. previous overview: cross browser testing next in this module introduction to cross-browser testing strategies for carrying out testing handling common html and css problems handling common javascript problems handling common accessibility problems implementing feature detection intro...
Adding a new event
edit related events like querying focused content information. touchevents.h this header file should be used for defining input events from touch devices. miscevents.h if the new event class isn't proper any header files above, you should use this. each event class should implement following methods manually. virtual internalfooevent* asfooevent() moz_override this method should just re
turn this. this method is used for retrieving sub class pointer avoiding to use static_cast. virtual widgetevent* duplicate() const moz_override this method should create a new instance with copying its members except widget. for copying the members, this should use assignfooeventdata() with true for acopytargets. and also, mflags should be just copied since assignfooeventdata() doesn't copy mflags.
...t interface in dom/interfaces/events/. however, in these days, this is not necessary. if all information of the event is stored by its internal event, c++ event handlers can access them with following code: ns_imethodimp aneventlistener::handleevent(nsidomevent* aevent) { internalfooevent* internalevent = aevent->getinternalnsevent()->asfooevent(); if (ns_warn_if(!internalevent)) { re
turn ns_error_unexpected; } dosomethingwith(internalevent->mbar); aevent->preventdefault(); re
turn ns_ok; } implement dom event class generate dom event implementation if it's possible if you're creating simple dom event class, it might be generated automatically. if it's possible, you just need to add an entry to generated_events_webidl_files in dom/webidl/moz.build. define and create do...
...tail. modify tests if you're in case 3, you can skip this section. you need to modify test_all_synthetic_events.html which tests if calling getmodifierstate() doesn't cause crash. you need to modify test_assign_event_data.html which tests if each attribute of dom event is copied by assignfooeventdata() properly. if your event cannot be fired easy, you should add the test but canrun should re
turn false and call todo(). if the new dom event is creatable with constructor, you need to modify test_eventctors.html or test_eventctors.xul which tests the behavior of event constructor. ...
Creating Custom Events That Can Pass Data
la 1.8.x branch this code is actually in mozilla/content/events/src/nseventlistenermanager.cpp this is quite an important file since this holds the createevent method which acts as a factory method dom events. the change you want to make is in nseventdispatcher::createevent(). ...
...you can find the prototypes for the function in nsiprivatedomevent. ...
...you can find the prototypes for the function in nsiprivatedomevent. your event in order for your event to work you must do the following: create a scriptable interface called nsidom{youreventname} inheriting from nsidomevent. a good place to put this .idl is in mozilla...
Eclipse CDT Manual Setup
the "entering directory..."/"leaving directory..." lines), and the build must not be silenced/quietened. conversely, note this very carefully: if you configure eclipse to invoke a build process that is parallelized, silenced, or that fails to identify the directory that the compiler is being run from, then it will mess up the compiler options that eclipse associates with your files, and that in
turn will significantly degrade the quality of the code assistance that eclipse will provide after it next re-indexes the code. these requirements aren't a very good fit with the typical mozilla developer's wish to minimize build times, implying parallelized, silenced builds. the consequences of the above observations are this: it is strongly recommended that you invoke your normal (re)builds fr...
...ur changes to eclipse's memory limits have taken effect and are present in eclipse/help > about eclipse > installation details > configuration. to avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below). ...
... select "general > content types", expand "text > c source file > c++ source file", click "add" and add "*.mm". ...
Experimental features in Firefox
see bug 1099557 for more details. release channel version added enabled by default? nightly 43 yes developer edition 43 no beta 43 no release 43 no preference name layout.css.control-characters.enabled or layout.css.control-characters.visible prope...
..., so they're both disabled by default. see bug 1057233 for more details. release channel version added enabled by default? nightly 33 no developer edition 33 no beta 33 no release 33 no preference name media.track.enabled dom document property: autoplaypolicy the document property autoplaypolicy re
turns a string indicating how the browser handles requests to automatically play media (either using the autoplay property on a media element or by attempting to trigger playback from javascript code. the spec for this api is still being written. the value changes over time depending on what the user is doing, their preferences, and the state of the browser in general. potential values include allowed...
...y're called to another node. see bug 918189 for more details. release channel version added enabled by default? nightly 31 yes developer edition 31 no beta 31 no release 31 no preference name layout.css.getboxquads.enabled geometryutils method: getboxquads() the geometryutils method getboxquads() re
turns the css boxes for a node relative to any other node or viewport. see bug 917755 for more details. release channel version added enabled by default? nightly 31 yes developer edition 31 no beta 31 no release 31 no preference name layout.css.convertfromnode.enable payment request api primary payment ...
Cross Process Object Wrappers
wrapper.addeventlistener("click", function() { console.log("they clicked"); }); }); mapping content documents to xul browsers a common pattern is to get the xul <browser> that corresponds to a content document. to enable this, gbrowser.getbrowserfordocument and gbrowser.getbrowserforcontentwindow can be passed a cpow for the content document and content window, respectively, and re
turn the xul <browser> that these documents / windows belong to. both re
turn null if no such browser can be found. limitations of cpows although cpows can be convenient they have several major limitations, which are listed below. cpows and platform apis you can't pass cpows into platform apis that expect to receive dom objects. for example, you can't pass a cpow into nsifocusmanager.setfocus(). ...
... allow unresponsive content process to make the whole browser unresponsive. see safe and unsafe cpows for more on this. performance although the wrapper looks just like an object completely contained in the chrome script scope, it's really just a reference to an object in the content process. when you access a property of the wrapper, it sends a synchronous message to the content process and re
turns the result. this means it is many times slower to use than an object. message ordering cpows can violate assumptions you might make about message ordering. consider this code: mm.addmessagelistener("gotloadevent", function (msg) { mm.sendasyncmessage("changedocumenturi", {newuri: "hello.com"}); let uri = msg.objects.document.documenturi; dump("received load event: " + uri + "\n"); }); ...
...can respond immediately to the cpow call: there is still a performance cost to the cpow in this situation, because the cpow call is an ipc call instead of a simple property access in the same process. however, the potential impact on responsiveness is much smaller. also, in this situation, the content process is in a known state. we know it's blocked waiting for the synchronous message to re
turn, and we know that won't change during the cpow call. this makes the cpow call much safer than it would otherwise be. this situation is thus called "safe cpow usage". all other uses of cpows are called "unsafe cpow usage". see also: https://mikeconley.ca/blog/2015/02/17/on-unsafe-cpow-usage-in-firefox-desktop-and-why-is-my-nightly-so-sluggish-with-e10s-enabled/ http://blog.lassey.us/2015/01/...
Limitations of chrome scripts
rally some variant of "do that in a frame script loaded into the content process". this is one of a pair of articles: the other one lists limitations of frame scripts. compatibility shims for many of the patterns described here we've implemented compatibility shims so the patterns still work. for example: whenever extensions try to access web content from the chrome process, the browser will re
turn a cross process object wrapper that gives the chrome code synchronous access to the content. you'll get the shims for your add-on by default, unless you set the multiprocesscompatible flag in your add-on's install manifest. however, these shims are not a substitute for migrating extensions: they are only a temporary measure, and will be removed eventually they can have a bad effect on respo...
...ells live in the content process, so they are also inaccessible: gbrowser.docshell; // null gbrowser.selectedbrowser.docshell; // null with the shim the shim will give you a cpow for the content object in these situations. in some situations, the content process may not be initialized when an add-on asks for access to its content. in this case, the shim will re
turn a javascript object that looks somewhat like a window or a document for about:blank. however, this "dummy" object is completely static and only exposes a few of the normal properties that windows and documents have. for this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. to make the shim unnecessary: factor the code that needs to access conte...
...yinterface(ci.nsihttpchannel); var domwindow = httpchannel.notificationcallbacks.getinterface(ci.nsiloadcontext).associatedwindow; } } in multiprocess firefox these patterns will no longer work: the getinterface call will fail. in multiprocess firefox, notificationcallbacks is a special object that tries to emulate the single-process notificationscallbacks object as best it can. it will re
turn a dummy nsiloadcontext when asked, but any attempt to get a window out of it will fail. there is an outstanding bug (bug 1108827) to implement a shim here that will make notificationcallbacks a cpow for the objects in the content process. the correct way to access the dom window is through a message manager. in an http observer, you can get the browser message manager for the window using cod...
mozbrowserfindchange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. ...
... activematchordinal a number indicating the position of the currently highlighted search result, e.g. 3 out of 5. ...
... activematchordinal a number indicating the position of the currently highlighted search result, e.g. 3 out of 5. ...
IPDL Best Practices
specifically, because allocpprotocol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protoco...
... specifically, because allocpprotocol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protocol tree due to an error, the auto pointer will attempt to trigger protocol ...
...out 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: re
turnresult(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 re
turnresult, at which point it will be deleted. it makes sense to fold construction and the first message together, as well as the penultimate and d...
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 re
turning results through callbacks passed to the functions. the callbacks may be called immediately while the initial function is still executing or shortly after, depending on when the requested data becomes available. accessing installed add-ons information about installed add-ons can be retrieved through the main addonmanager api. all of its functions are asynchronous, meaning that a callback function must be passed to receive the addon ...
...unction is still executing or shortly after, depending on when the requested data becomes available. accessing installed add-ons information about installed add-ons can be retrieved through the main addonmanager api. all of its functions are asynchronous, meaning that a callback function must be passed to receive the addon instances. the callback may well only be called after the api function re
turns. for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners. they must be registered through the addaddonlistener() ...
... an installlistener. a listener can be registered either for a specific install using the addlistener() method or for all installs using the addinstalllistener() method. finding updates add-ons can be checked for updates using the findupdates() method. it must be passed an updatelistener to receive information about compatibility information and new update information. any available update is re
turned as an addoninstall which is ready to be downloaded and installed. detecting add-on changes requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) you can also get lists of add-ons that, at startup, were changed in various ways. the getstartupchanges() method lets you find out which add-ons were installed, removed, updated, enabled, or disabled at application startup. for...
SourceMap.jsm
nal source files. names: an array of identifiers that can be referenced by individual mappings. sourceroot: optional. the url root from which all sources are relative. mappings: a string of base64 vlqs which contain the actual mappings. file: the generated filename this source map is associated with. ...
... line: the line number in the original source, or null if this information is not available. ...
...r between each of this source node's children. sep: the separator. sourcenode.prototype.replaceright(pattern, replacement) call string.prototype.replace on the very rightmost source snippet. useful for trimming whitespace from the end of a source node, etc. pattern: the pattern to replace. replacement: the thing to replace the pattern with. sourcenode.prototype.tostring() re
turn the string representation of this source node. walks over the tree and concatenates all the various snippets together to one string. sourcenode.prototype.tostringwithsourcemap(startofsourcemap) re
turns the string representation of this tree of source nodes, plus a sourcemapgenerator which contains all the mappings between the generated and original sources. the arguments are the same as those ...
Localization formats
ll the strings needing localization. that file will have the following structure: ;getting started débuter avec firefox the english content is designated by the semi-colon and the localizer provides the translation underneath. that content is placed into an array that is used by the php code later. ...
...alizer provides the translation underneath. that content is placed into an array that is used by the php code later. $array["getting started"] = "débuter avec firefox" the php code searches the array and re
turns the translation that is associated with the english term used by the web developer. see the example below. ...
... obvious powers of gettext. when english content is used as the value of the msgid, there is no need to place that content in a special repository. but, in the download day example, when changes were made to en-us, the web-developer had to push those changes to all the repositories of all the locales. localizers had to revisit an en-us repository to find the exact msgid, review the change, and re
turn to their repository to make changes. without having the exact content as the msgid, this process may cause several errors since the localizers cannot has to continually switch back-and-forth. in this case, the choice to use customized values for msgid was error-prone, onerous, and unfamiliar to localizers who are used to more customary gettext operations. ...
NSPR's Position On Abrupt Thread Termination
that it can happen at any time, to a thread that is coded correctly to handle both normal and exceptional situations, but will be unable to do so since it will be denied the opportunity to complete execution. it can happen because it called out of its own scope into some lazily implemented library. nspr's answer to this is that there is no abrupt thread termination. all threads must unwind and re
turn from their root function. if they cannot, because of some state corruption, then they must assume that the corruption, like the state, is shared, and their only resource is for the process to terminate. to make this solution work requires that a function that encounters an error be designed such that it first repairs its immediate state, and then reports that error to its caller. if the caller ca...
...he state, is shared, and their only resource is for the process to terminate. to make this solution work requires that a function that encounters an error be designed such that it first repairs its immediate state, and then reports that error to its caller. if the caller cannot deal with the failure, it must do the same. this process continues until the thread either recovers from the malady or re
turns from the root function. this is not all that difficult (though having done it a number of times to already existing code, i will admit it isn't much fun either). the implementation of either strategy within the nspr runtime is not difficult. that is not what this memo is about. this is about providing an api that coaxes people to do the right thing in as many ways as possible. the existence of e...
...lementation of either strategy within the nspr runtime is not difficult. that is not what this memo is about. this is about providing an api that coaxes people to do the right thing in as many ways as possible. the existence of exit() in the unix/c environment is a perfect example of how programmers will employ the most expediant solution available. the definition of the language c is such that re
turning from main() is a perfectly fine thing to do. but what percentage of c programs actually bother? in unix, with its complex definition of a protection domain, it happens to work (one might even say it's more efficient) to exit from anywhere. but threads are not processes. if threads have to maintain the same type of resource knowledge as a process, they loose all of their benefit. threads are an...
PRThreadState
a thread's thread state is either joinable or unjoinable. syntax #include <prthread.h> typedef enum prthreadstate { pr_joinable_thread, pr_unjoinable_thread } prthreadstate; enumerators pr_unjoinable_thread thread termination happens implicitly when the thread re
turns from the root function. the time of release of the resources assigned to the thread cannot be determined in advance. threads created with a pr_unjoinable_thread state cannot be used as arguments to pr_jointhread. pr_joinable_thread joinable thread references remain valid after they have re
turned from their root function until pr_jointhread is called. this approach facilitates management of the process' critical resources. description a thread is a critical resource and must be managed. the lifetime of a thre...
...e used as arguments to pr_jointhread. pr_joinable_thread joinable thread references remain valid after they have re
turned from their root function until pr_jointhread is called. this approach facilitates management of the process' critical resources. description a thread is a critical resource and must be managed. the lifetime of a thread extends from the time it is created to the time it re
turns from its root function. what happens when it re
turns from its root function depends on the thread state passed to pr_createthread when the thread was created. if a thread is created as a joinable thread, it continues to exist after re
turning from its root function until another thread joins it. the join process permits strict synchronization of thread termination and therefore promotes effectiv...
...ead was created. if a thread is created as a joinable thread, it continues to exist after re
turning from its root function until another thread joins it. the join process permits strict synchronization of thread termination and therefore promotes effective resource management. if a thread is created as an unjoinable (also called detached) thread, it terminates and cleans up after itself after re
turning from its root function. this results in some ambiguity after the thread's root function has re
turned and before the thread has finished terminating itself. ...
PR_AcceptRead
rfiledesc **acceptedsock, prnetaddr **peeraddr, void *buf, print32 amount, printervaltime timeout); parameters the function has the following parameters: listensock a pointer to a prfiledesc object representing a socket descriptor that has been called with the pr_listen function, also known as the rendezvous socket. acceptedsock a pointer to a pointer to a prfiledesc object. on re
turn, *acceptedsock points to the prfiledesc object for the newly connected socket. this parameter is valid only if the function re
turn does not indicate failure. peeraddr a pointer a pointer to a prnetaddr object. on re
turn, peeraddr points to the address of the remote socket. the prnetaddr object that peeraddr points to will be in the buffer pointed to by buf. this parameter is valid only if the f...
... buf a pointer to a buffer to hold data sent by the peer and the peer's address. this buffer must be large enough to receive amount bytes of data and two prnetaddr structures (thus allowing the runtime to align the addresses as needed). ...
...ntime to align the addresses as needed). amount the number of bytes of data to receive. does not include the size of the prnetaddr structures. if 0, no data will be read from the peer. timeout the timeout interval only applies to the read portion of the operation. pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses. re
turns a positive number indicates the number of bytes read from the peer. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_acceptread accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address. also, as its name suggests, pr_acceptread receives the first block of data sent by t...
PR_DetachThread
this call is needed only if you attached the thread using pr_attachthread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. ...
... this call is needed only if you attached the thread using pr_attachthread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. ...
... this call is needed only if you attached the thread using pr_attachthread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. ...
PR_EnumerateHostEnt
ehostent( printn enumindex, const prhostent *hostent, pruint16 port, prnetaddr *address); parameters the function has the following parameters: enumindex the index of the enumeration. to begin an enumeration, this argument is set to zero. to continue an enumeration (thereby getting successive addresses from the host entry structure), the value should be set to the function's last re
turned value. the enumeration is complete when a value of zero is re
turned. hostent a pointer to a prhostent structure obtained from pr_gethostbyname or pr_gethostbyaddr. port the port number to be assigned as part of the prnetaddr structure. this parameter is not checked for validity. address on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if ...
...you can retrieve the reason for the failure by calling pr_geterror. ...
...ed. hostent a pointer to a prhostent structure obtained from pr_gethostbyname or pr_gethostbyaddr. port the port number to be assigned as part of the prnetaddr structure. this parameter is not checked for validity. address on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the result of the call is greater than 0. re
turns the function re
turns one of the following values: if successful, the function re
turns the value you should specify in the enumindex parameter for the next call of the enumerator. if the function re
turns 0, the enumeration is ended. if unsuccessful, the function re
turns -1. you can retrieve the reason for the failure by calling pr_geterror. description pr_enumeratehostent is a stateless enumerator. the princip...
PR_FindSymbol
if the lib parameter is null, all libraries known to the runtime and the main program are searched in an unspecified order. ...
...if the lib parameter is null, all libraries known to the runtime and the main program are searched in an unspecified order. ...
...particular library given the identity of the library and a textual representation of the symbol in question. syntax #include <prlink.h> void* pr_findsymbol ( prlibrary *lib, const char *name); parameters the function has these parameters: lib a valid reference to a loaded library, as re
turned by pr_loadlibrary, or null. name a textual representation of the symbol to resolve. re
turns an untyped pointer. description this function finds and re
turns an untyped reference to the specified symbol in the specified library. if the lib parameter is null, all libraries known to the runtime and the main program are searched in an unspecified order. use this function to look up functions or data symbols in a shared library. getting a pointer to a symbol in a library does indicate th...
PR_FindSymbolAndLibrary
finds a symbol in one of the currently loaded libraries, and re
turns both the symbol and the library in which it was found. syntax #include <prlink.h> void* pr_findsymbolandlibrary ( const char *name, prlibrary **lib); parameters the function has these parameters: name the textual representation of the symbol to locate. lib a reference to a location at which the runtime will store the library in which the symbol was discovered. this location must be pre-allocated by the caller. re
turns if successful, re
turns a non-null pointer to the found symbol, and stores a pointer to the library in which it was found at the location pointed to by lib. if the symbol could not be found, re
turns null. description this function finds the specified symbol in one of the currently loaded ...
...ich the symbol was discovered. this location must be pre-allocated by the caller. re
turns if successful, re
turns a non-null pointer to the found symbol, and stores a pointer to the library in which it was found at the location pointed to by lib. if the symbol could not be found, re
turns null. description this function finds the specified symbol in one of the currently loaded libraries. it re
turns the address of the symbol. upon re
turn, the location pointed to by the parameter lib contains a pointer to the library that contains that symbol. the location must be pre-allocated by the caller. the function re
turns null if no such function can be found. the order in which the known libraries are searched in not specified. this function is equivalent to calling first pr_loadlibrary, then pr_fi...
...l. upon re
turn, the location pointed to by the parameter lib contains a pointer to the library that contains that symbol. the location must be pre-allocated by the caller. the function re
turns null if no such function can be found. the order in which the known libraries are searched in not specified. this function is equivalent to calling first pr_loadlibrary, then pr_findsymbol. the identity re
turned from this function must be the target of a pr_unloadlibrary in order to re
turn the runtime to its original state. ...
PR_GetError
nspr provides no direct interpretation of the number's value. nspr does use pr_seterror to set error numbers defined in error codes. ...
...nspr provides no direct interpretation of the number's value. nspr does use pr_seterror to set error numbers defined in error codes. ...
...nspr provides no direct interpretation of the number's value. nspr does use pr_seterror to set error numbers defined in error codes. ...
PR_NEXT_LINK
it can be used to traverse a list. the following element is not removed from the list. ...
...it can be used to traverse a list. the following element is not removed from the list. ...
...it can be used to traverse a list. the following element is not removed from the list. ...
PR_Now
to obtain monotonically increasing time stamps suitable for measuring elapsed time, use pr_intervalnow(). ...
...to obtain monotonically increasing time stamps suitable for measuring elapsed time, use pr_intervalnow(). ...
...to obtain monotonically increasing time stamps suitable for measuring elapsed time, use pr_intervalnow(). ...
PR_Open
pr_truncate 0x20 if the file exists, its length is truncated to 0. pr_sync 0x40 if set, each write will wait for both the file data and file status to be physically updated. pr_excl 0x80 with pr_create_file, if the file does not exist, the file is created. if the file already exists, no action and null is re
turned. mode when pr_create_file flag is set and the file is created, these flags define the access permission bits of the newly created file. this feature is currently only applicable on unix platforms. it is ignored by any other platform but it may apply to other platforms in the future. possible values of the mode parameter are listed in the table below. nam...
...the prfiledesc should be freed by calling pr_close. if the file was not opened successfully, a null pointer. description pr_open creates a file descriptor (prfiledesc) for the file with the pathname name and sets the file status ...
...the prfiledesc should be freed by calling pr_close. if the file was not opened successfully, a null pointer. description pr_open creates a file descriptor (prfiledesc) for the file with the pathname name and sets the file status flags of the file desc...
PR_OpenSharedMemory
* define values for pr_opensharememory(...,create) */ #define pr_shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment. size the size of the shared memory segment. flags options for creating the shared memory. mode same as passed to pr_open. re
turns pointer to opaque structure prsharedmemory, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name. when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory already exists, the funct...
...nter to opaque structure prsharedmemory, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name. when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory already exists, the function re
turns null with the error set to pr_file_exists_error. when parameter create is pr_shm_create and the shared memory already exists, a handle to that memory segment is re
turned. if the segment does not exist, it is created and a pointer to the related prsharedmemory structure is re
turned. when parameter create is 0, and the shared memory exists, a pointer to a prsharedmemory structure is re
turned. if...
...rror. when parameter create is pr_shm_create and the shared memory already exists, a handle to that memory segment is re
turned. if the segment does not exist, it is created and a pointer to the related prsharedmemory structure is re
turned. when parameter create is 0, and the shared memory exists, a pointer to a prsharedmemory structure is re
turned. if the shared memory does not exist, null is re
turned with the error set to pr_file_not_found_error. ...
PR_PREV_LINK
it can be used to traverse a list. the preceding element is not removed from the list. ...
...it can be used to traverse a list. the preceding element is not removed from the list. ...
...it can be used to traverse a list. the preceding element is not removed from the list. ...
PR_ReadDir
ry entry "." representing the current directory. pr_skip_dot_dot. skip the directory entry ".." representing the parent directory. pr_skip_both. skip both "." and ".." pr_skip_hidden. skip hidden files. on windows platforms and the mac os, this value identifies files with the "hidden" attribute set. on unix platform, this value identifies files whose names begin with a period ("."). ...
... hidden files. on windows platforms and the mac os, this value identifies files with the "hidden" attribute set. on unix platform, this value identifies files whose names begin with a period ("."). re
turns a pointer to the next entry in the directory. if the end of the directory is reached or an error occurs, null. the reason can be retrieved via pr_geterror. description pr_readdir re
turns a pointer to a directory entry structure: struct prdirentry { const char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name. the flags parameter is an enum of type prdirflags: typedef enum prdirflags { pr_skip_none = 0x0, pr_skip_dot = 0x1, pr_skip_dot_dot = 0x2, pr_skip_both = 0x3, ...
...char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name. the flags parameter is an enum of type prdirflags: typedef enum prdirflags { pr_skip_none = 0x0, pr_skip_dot = 0x1, pr_skip_dot_dot = 0x2, pr_skip_both = 0x3, pr_skip_hidden = 0x4 } prdirflags; the memory associated with the re
turned prdirentry structure is managed by nspr. the caller must not free the prdirentry structure. moreover, the prdirentry structure re
turned by each pr_readdir call is valid only until the next pr_readdir or pr_closedir call on the same prdir object. if the end of the directory is reached, pr_readdir re
turns null, and pr_geterror re
turns pr_no_more_files_error. see also pr_opendir ...
PR_SetThreadPrivate
if the index is invalid, pr_failure. ...
... if the index is invalid, pr_failure. ...
...index is invalid, pr_failure. description if the thread already has non-null private data associated with it, and if the destructor function for the index is known (not null), nspr calls the destructor function associated with the index before setting the new data value. the pointer at the index is swapped with null. if the swapped out value is not null, the destructor function is called. on re
turn, the private data associated with the index is reassigned the new private data's value, even if it is null. the runtime provides no protection for the private data. the destructor is called with the runtime holding no locks. synchronization is the client's responsibility. the only way to eliminate thread private data at an index prior to the thread's termination is to call pr_setthreadprivate wi...
PR_dtoa
an indication that the conversion was of a negative value. *rve if not null this location is set to the address of the end of the result. buf the address of the buffer in which to store the result. bufsz the size of the buffer provided to hold the result. results the principle output is the null-terminated string stored in buf. if rve is not null, *rve is set to point to the end of the re
turned value. description this function converts the specified floating point number to a string, using the method specified by mode. possible modes are: 0 shortest string that yields d when read in and rounded to nearest. 1 like 0, but with steele & white stopping rule. for example, with ieee 754 arithmetic, mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 max(1, ndigits) sign...
...nction converts the specified floating point number to a string, using the method specified by mode. possible modes are: 0 shortest string that yields d when read in and rounded to nearest. 1 like 0, but with steele & white stopping rule. for example, with ieee 754 arithmetic, mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 max(1, ndigits) significant digits. this gives a re
turn value similar to that of ecvt, except that trailing zeros are suppressed. 3 through ndigits past the decimal point. this gives a re
turn value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4,5,8,9 same as modes 2 and 3, but usingleft to right digit generation. 6-9 same as modes 2 and 3, but do not try fast floating-point estimate (if appli...
...ing zeros are suppressed. 3 through ndigits past the decimal point. this gives a re
turn value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4,5,8,9 same as modes 2 and 3, but usingleft to right digit generation. 6-9 same as modes 2 and 3, but do not try fast floating-point estimate (if applicable). all others treated as mode 2. upon re
turn, the buffer specified by buf and bufsz contains the converted string. trailing zeros are suppressed. sufficient space is allocated to the re
turn value to hold the suppressed trailing zeros. if the input parameter d is+infinity,-infinity ornan, *decpt is set to 9999. ...
Function_Name
one-line description of what the function does (more than just what it re
turns). syntax #include <headers.h> re
turntype function_name( paramtype paramname, paramtype paramname, ); parameters paramname sample: in pointer to a certcertdbhandle representing the certificate database to look in paramname sample: in pointer to an secitem whose type must be sidercertbuffer and whose data contains a der-encoded certificate description long description of this function, what it does, and why you would use it. describe all side-effects on "out" parameters. avoid describing the re
turn until the next section, for example: this function looks in the nsscryptocontext and the nsstrustdomain to find the certificate that matches the der-encoded certificate. a ...
...the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. ...
...the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. ...
NSS 3.21 release notes
d signature and hash algorithms ssl_signaturemaxcount - obtains the maximum number signature algorithms that can be configured with ssl_signatureprefset in utilpars.h nssutil_argparsemodulespecex - takes a module spec and breaks it into shared library string, module name string, module parameters string, nss specific parameters string, and nss configuration parameter strings. the re
turned strings must be freed by the caller. the difference with nss_argparsemodulespec is the new function handles nss configuration parameter strings. nssutil_mkmodulespecex - take a shared library string, module name string, module parameters string, nss specific parameters string, and nss configuration parameter string and re
turns a module string which the caller must free when it is done. the d...
...:f0:36:9b:46 cn = utn - datacorp sgc sha-1 fingerprint: 58:11:9f:0e:12:82:87:ea:50:fd:d9:87:45:6f:4f:78:dc:fa:d6:d4 o = tÜrktrust bilgi İletişim ve bilişim güvenliği hizmetleri a.Ş. ...
... compatibility nss 3.21 shared libraries are backward compatible with all ...
NSS 3.31 release notes
11uri.h pk11uri_createuri - create a new pk11uri object from a set of attributes. pk11uri_destroyuri - destroy a pk11uri object. pk11uri_formaturi - format a pk11uri object to a string. pk11uri_getpathattribute - retrieve a path attribute with the given name. pk11uri_getqueryattribute - retrieve a query attribute with the given name. pk11uri_parseuri - parse pkcs#11 uri and re
turn a new pk11uri object. new macros in pkcs11uri.h several new macros that start with pk11uri_pattr_ for path attributes defined in rfc7512. several new macros that start with pk11uri_qattr_ for query attributes defined in rfc7512. notable changes in nss 3.31 the apis that set a tls version range have been changed to trim the requested range to the overlap with a system...
...7512. notable changes in nss 3.31 the apis that set a tls version range have been changed to trim the requested range to the overlap with a systemwide crypto policy, if configured. ssl_versionrangegetsupported can be used to query the overlap between the library's supported range of tls versions and the systemwide policy. previously, ssl_versionrangeset and ssl_versionrangesetdefault re
turned a failure if the requested version range wasn't fully allowed by the systemwide crypto policy. they have been changed to re
turn success, if at least one tls version overlaps between the requested range and the systemwide policy. an application may call ssl_versionrangeget and ssl_versionrangegetdefault to query the tls version range that was effectively activated. corrected the encoding of dom...
...he tls version range that was effectively activated. corrected the encoding of domain name constraints extensions created by certutil nss supports a clean seeding mechanism for *nix systems now using only /dev/urandom. this is used only when seed_only_dev_urandom is set at compile time. cert_asciitoname can handle oids in dotted decimal form now. bugs fixed in nss 3.31 this bugzilla query re
turns all the bugs fixed in nss 3.31: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.31 compatibility nss 3.31 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.31 shared libraries without recompiling or r...
NSS 3.35 release notes
:60:25:db:ea:10:41:6d:7e:b6:83:1f:8c:40 subject cn = verisign class 3 secure server ca - g2 sha-256 fingerprint: 0a:41:51:d5:e5:8b:84:b8:ac:e5:3a:5c:12:12:2a:c9:59:cd:69:91:fb:b3:8e:99:b5:76:c0:ab:da:c3:58:14 this intermediate cert had been directly included to help with transition from 1024-bit roots per bug #1045189. ...
...nctionality and the apis listed in this section are experimental. any of these apis may be removed from future nss versions. applications must not rely on these apis to be present. if an application is linked at runtime to a later version of nss, which no longer provides any of these apis, the application must handle the scenario gracefully. in order to ease transitions, experimental functions re
turn secfailure and set the ssl_error_unsupported_experimental_api code if the selected api is not available. experimental functions will always re
turn this result if they are disabled or removed from a later nss release. if these experimental functions are made permanent in a later nss release, no change to code is necessary. (only apis exported in *.def files are stable apis.) new experimental fun...
... (tls 1.3 server only). experimental: ssl_sendsessionticket - send a session ticket (tls 1.3 server only). removed experimental apis note that experimental apis might get removed from nss without announcing removals in the release notes. this section might be incomplete. the experimental api ssl_usealtserverhellotype has been disabled. bugs fixed in nss 3.35 this bugzilla query re
turns all the bugs fixed in nss 3.35: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.35 compatibility nss 3.35 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.35 shared libraries, without recompiling, or...
NSS 3.45 release notes
vailable on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_45_rtm/src/ other releases are available in nss releases. new in nss 3.45 new functionality new functions in pk11pub.h: pk11_findrawcertswithsubject - finds all certificates on the given slot with the given subject distinguished name and re
turns them as der bytes. if no such certificates can be found, re
turns secsuccess and sets *results to null. if a failure is encountered while fetching any of the matching certificates, secfailure is re
turned and *results will be null. notable changes in nss 3.45 bug 1540403 - implement delegated credentials (draft-ietf-tls-subcerts) this adds a new experimental function: ssl_delegate...
...ween mp_set_long and mp_set_ulong bug 1515011 - fix a mistake with chacha20-poly1305 test code where tags could be faked. ...
...on ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequestcallback re
turn code for rejecting 0-rtt bug 1556591 - eliminate races in uses of pk11_setwrapkey bug 1558681 - stop using a global for anti-replay of tls 1.3 early data bug 1561510 - fix a bug where removing -arch xxx args from cc didn't work bug 1561523 - add a string for the new-ish error ssl_error_missing_post_handshake_auth_extension this bugzilla query re
turns all the bugs fixed in nss 3.45: https:/...
NSS 3.46 release notes
ug 1574220 - improve controls after errors in tstcln, selfserv and vfyserv cmds bug 1550636 - upgrade sqlite in nss to a 2019 version bug 1572593 - reset advertised extensions in ssl_constructextensions bug 1415118 - nss build with ./build.sh --enable-libpkix fails bug 1539788 - add length checks for cryptographic primitives (cve-2019-17006) bug 1542077 - mp_set_ulong and mp_set_int should re
turn errors on bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to ...
...hangs on windows x64 when building nss since changeset 9162c654d06915f0f15948fbf67d4103a229226f bug 1564875 - improve rebuilding with build.sh bug 1565243 - support tc_owner without email address in nss taskgraph bug 1563778 - increase maxruntime on mac taskcluster tools, ssl tests bug 1561...
...a program linked with older nss 3.x shared libraries will work with nss 3.46 shared libraries without recompiling or r...
Notes on TLS - SSL 3.0 Intolerant Servers
n.b. there might be servers other than those listed above which exhibit this problem. if you find such a server, feel free to add it to this page. for up-to-date information, you can read this bug 59321 which keeps a list of tls/ssl 3.0 intolerant servers. users: how to avoid this problem? netscape 6.1 preview release 1, or mozilla 0.9.1 and earlier these versions shipped with the tls option
turned on as the default but with no way to deal with the problem servers. if you are using these old versions, please update to the latest netscape or mozilla versions. you can also avoid such a problem by editing an existing profile -- check the preference option setting at: edit | preferences | privacy and security | ssl | enable tls, and
turn it off if it is on for these earlier browsers. netscap...
...ther network clients which implement tls/ssl 3.0 specification correctly and have a problem with your site. let's not perpetuate the problem servers. contact the manufacturer and inquire if there is a new version available which fixes this problem. post a note on your site instructing users of old versions of browsers like netscape 6.0/6.01/6.1 preview release 1 and mozilla 0.9.1 and earlier to
turn off the tls option at: edit | preferences | privacy and security | ssl | enable tls. however, this is a temporary workaround at best. we recommend strongly that you urge users to upgrade to the latest netscape version (or at least netscape 6.1) since the newer versions have the graceful rollback implemented in the code. if you have questions concerning netscape browsers and problem servers, plea...
...y also run this test with versions later than the older versions of netscape 6.x or mozilla -- just in case code changes in netscape 6.1/mozilla 0.9.2 or later may not catch all problem servers. when you find a secure site which simply does not display any page content or drops the connection, check to see if the preference option edit | preferences | privacy and security | ssl | enable tls is
turned on. if so,
turn it off. now re-visit the problem site. if the content displays this time, you are most likely witnessing a tls/ssl 3.0 intolerant server. report such a problem to the server's administrator. how to report an intolerant server optional:get the name of the ssl server software used by the website. to do so, add http://toolbar.netcraft.com/site_report?url= to the beginning of...
PKCS11 FAQ
ect to implement all the pkcs #11 functions that make sense for your token. nss continues to evolve, and periodically enhances it's functionality by using a more complete list of pkcs #11 functions. you should have implementations for all the functions specified in the version of the pkcs #11 spec your token implements. if you do not actually do the operation specified by that function, you can re
turn ckr_function_not_supported. will nss get the user's ca certificate via pkcs #11 and push it into the ca certificate database or is the ca certificate database expected to obtain the ca certificate by some other means? pkcs #11 certificates that have private keys associated with them are are loaded into the temporary database (in memory) and marked as user certificates. all other certificates in...
...using that same token (so keys don't get moved around). symmetric operations supported by nss include the following: ckm_aes_xxx, ckm_des3_xxx, ckm_des_xxx, ckm_rc2_xxx, and ckm_rc4_xxx. nss knows about all the mechanisms defined in pkcs #11 version 2.01, but will not perform those that aren't defined by nss's policy mechanism. when do nss applications spawn threads off the main thread, which in
turn opens up a new pkcs #11 session? this depends on the application. pkcs #11 sessions are cryptographic session states, independent of threads. in nss based servers, multiple threads may call the same session, but two threads will not call the same session at the same time. questions about keys and tokens is the pkcs #11 token treated in a read-only manner? that is, no token init, no key gens, n...
...opyobject. if your module does not support this semantic, it will not work with nss. questions about pins will a password change ever be done on the token? yes, nss attempts to change the password in user mode only. (it goes to sso mode only if your token identifies itself as ckf_login_required, but not ckf_user_initialized). it's perfectly valid to reject the password change request with a re
turn value such as ckr_function_not_supported. if you do this, nss applications display an appropriate error message for the user. if i have my smart card which has initial pin set at '9999', i insert it into my reader and download with my certificate (keygen completed), can i issue 'change password' from the firefox to set a new pin to the smart card? any scenario that you can give me similar to thi...
PKCS11 Implement
initialize the nss calls c_initialize on startup or when it loads a new module. the nss always passes null, as required by the pkcs #11 specification, in the single c_initialize parameter preserved. c_finalize the nss calls c_finalize on shutdown and whenever it unloads a module. c_getfunctionlist the nss calls c_getfunctionlist on startup or when it loads a new module. the function list re
turned should include all the pkcs 2.0 function calls. if you don't implement a function, you should still provide a stub that re
turns ckr_function_not_supported. c_getinfo the nss calls c_getinfo on startup or when it loads a new module. the version numbers, manufacturer ids, and so on are displayed when the user views the information. the supplied library names are used as the default library nam...
...on). if it runs out of sessions, it uses the initial session for saves and restores. c_closesession the nss calls c_closesession to close sessions created for bulk encryption. c_closeallsessions the nss may call c_closeallsessions when it closes down a slot. c_getsessioninfo the nss calls c_getsessioninfo frequently. if a token has been removed during a session, c_getsessioninfo should re
turn either ckr_session_closed or ckr_session_handle_invalid. if a token has been removed and then the same or another token is inserted, c_getsessioninfo should re
turn ckr_session_handle_invalid. c_login the nss calls c_login on a token's initial session whenever ckf_login_required is true and the user state indicates that the user isn't logged in. c_logout the nss calls c_logout on a token's i...
...typically, nss uses c_createobject for creating a new private key if pkcs #12 is operating or if your writable token doesn't support c_generatekeypair. ...
FC_DigestFinal
operation. syntax ck_rv fc_digestfinal( ck_session_handle hsession, ck_byte_ptr pdigest, ck_ulong_ptr puldigestlen ); parameters hsession [in] session handle. pdigest [out] pointer to the buffer which will receive the digest or null. puldigestlen [in, out] pointer to location containing the maximum buffer size. ...
...uldigestlen ); parameters hsession [in] session handle. pdigest [out] pointer to the buffer which will receive the digest or null. puldigestlen [in, out] pointer to location containing the maximum buffer size. description fc_digestfinal finishes a multi-part digest operation by re
turning the complete digest and clearing the operation context. ...
...ing the maximum buffer size. description fc_digestfinal finishes a multi-part digest operation by re
turning the complete digest and clearing the operation context. if pdigest is null the length of the digest is re
turned and fc_digestfinal may be called again with pdigest set to retrieve the digest. a user may call fc_digestfinal without logging into the token (to assume the nss user role). ...
FC_FindObjects
ts syntax ck_rv fc_findobjects( ck_session_handle hsession, ck_object_handle_ptr phobject, ck_ulong usmaxobjectcount, ck_ulong_ptr pusobjectcount ); parameters hsession [in] session handle. ptemplate [out] pointer to location to receive the object handles. usmaxobjectcount [in] maximum number of handles to retrieve. ...
...handle hsession, ck_object_handle_ptr phobject, ck_ulong usmaxobjectcount, ck_ulong_ptr pusobjectcount ); parameters hsession [in] session handle. ptemplate [out] pointer to location to receive the object handles. usmaxobjectcount [in] maximum number of handles to retrieve. ...
... receive the object handles. usmaxobjectcount [in] maximum number of handles to retrieve. pusobjectcount [out] pointer to location to receive the number of re
turned handles. ...
FC_GetFunctionStatus
examples see also nsc_getfunctionstatus ...
... examples see also nsc_getfunctionstatus ...
... examples see also nsc_getfunctionstatus ...
FC_SignFinal
n. syntax ck_rv fc_signfinal( ck_session_handle hsession, ck_byte_ptr psignature, ck_ulong_ptr pussignaturelen ); parameters hsession [in] session handle. psignature [out] pointer to the buffer which will receive the digest or null. pussignaturelen [in, out] pointer to location containing the maximum buffer size. ...
... parameters hsession [in] session handle. psignature [out] pointer to the buffer which will receive the digest or null. pussignaturelen [in, out] pointer to location containing the maximum buffer size. description fc_signfinal finishes a multi-part signing operation by re
turning the complete signature and clearing the operation context. ...
...aximum buffer size. description fc_signfinal finishes a multi-part signing operation by re
turning the complete signature and clearing the operation context. if psignature is null the length of the signature is re
turned and fc_signfinal may be called again with psignature set to retrieve the signature. a user must log into the token (to assume the nss user role) before calling fc_signfinal. ...
NSS tools : pk12util
cates and other meta-data. -n certname specify the nickname of the cert and private key to export. -p prefix specify the prefix used on the certificate and key databases. this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -r dumps all of the data in raw (binary) form. this must be saved as a der file. ...
...raw (binary) form. this must be saved as a der file. the default is to re
turn information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...cryption with md5 and des cbc o pkcs #5 password based encryption with sha1 and des cbc with pkcs#12, the crypto provider may be the soft token module or an external hardware module. if the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default). if no suitable replacement for the desired algorithm can be found, the tool re
turns the error no security module can perform the requested operation. nss database types nss originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it from being easily used by m...
NSS tools : pk12util
specify the desired length of the symmetric key to be used to encrypt the private key. -n | --cert-key-len certkeylength specify the desired length of the symmetric key to be used to encrypt the certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. ...
...the desired length of the symmetric key to be used to encrypt the certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to re
turn information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
... cbc o pkcs #5 password based encryption with sha1 and des cbc with pkcs#12, the crypto provider may be the soft token module or an external hardware module. if the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default). if no suitable replacement for the desired algorithm can be found, the tool re
turns the error no security module can perform the requested operation. nss database types nss originally used berkeleydb databases to store security information. the last versions of these legacy databases are: o cert8.db for certificates o key3.db for keys o secmod.db for pkcs #11 module information berkeleydb has performance limitations, though, which prevent it fro...
Rhino serialization
has some significant limitations. serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. simple serialization example the rhino shell has two new top-level functions, serialize and deserialize. they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { re
turn 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { re
turn 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a new instance of rhino and called. rhino serialization apis two new classes, scriptableoutputstream and scriptableinputstream, were introduced to han...
...ization. exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputstream or scriptableinputstream. rhino serialization in compilation mode serialization works well with objects and with functions and scripts in interpretive mode. however, you can run into problems with serialization of compiled functions and scripts: $ cat test.jsfunction f() { re
turn 3; } serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java org.mozilla.javascript.tools.shell.main -opt -1test.js 3 $ java org.mozilla.javascript.tools.shell.main test.js js: uncaught javascript exception: java.lang.classnotfoundexception:c1 the problem is that java serialization has no built-in way to serialize java classes themselves. (it might be possible to save the java byteco...
...ng.classnotfoundexception:c1 the problem is that java serialization has no built-in way to serialize java classes themselves. (it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function f() { re
turn 3; } $ java -classpath js.jarorg.mozilla.javascript.tools.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java -classpath 'js.jar;.'org.mozilla.javascript.tools.shell.main test2.js 3 now the function f is compiled to a java class, but that class is then made available in the classpath so serialization works. this isn't that interesting a...
SpiderMonkey Internals
1.) error handling spidermonkey has two interdependent error-handling systems: javascript exceptions (which are not implemented with, or even compatible with, any kind of native c/c++ exception handling) and error reporting. in general, both functions inside spidermonkey and jsapi callback functions signal errors by calling js_reporterror or one of its variants, or js_setpendingexception, and re
turning js_false or null. public apis the public c/c++ interface, called the jsapi, is in most places a thin (but source-compatible across versions) layer over the implementation. see the jsapi user guide. there is an additional public api for javascript debuggers, jsdbgapi, but js/jsd/jsdebug.h might be a better api for debuggers. another api, jsxdrapi, provides serialization for javascript scripts...
... cleared. watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set. line number to pc and back mapping functions. the line-to-pc direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may re
turn the pc of a for-loop update part, if given the line number of the loop body's closing brace. any line after the last one in a script or function maps to a pc one byte beyond the last bytecode in the script. an example, from perfect.js: function perfect(n) { print("the perfect numbers up to " + n + " are:"); // we build sumofdivisors[i] to hold a string expression for // the sum of the divi...
...finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them. the details of a native object's map (scope) are mostly hidden in jsscope.[ch]. jsatom.cpp, jsatom.h the atom manager. contains well-known string constants, their atoms, the global atom hash table and related state, the js_atomize() function that
turns a counted string of bytes into an atom, and literal pool (jsatommap) methods. jsarena.cpp, jsarena.h last-in-first-out allocation macros that amortize malloc costs and allow for en-masse freeing. see the paper mentioned in jsarena.h's major comment. jsgc.cpp, jsgc.h the garbage collector and tracing routines. jsinterp.*, jscntxt.*, jsinvoke.cpp the bytecode interpreter, and related functio...
JIT Optimization Outcomes
the typed object. inconsistentfieldtype the type of an unboxed field is not consistent across all the different types of objects it could be accessed from. inconsistentfieldoffset the offset of an unboxed field is not consistent across all the different types of objects it could be accessed from. needstypebarrier optimization failed because somehow the property was accessed in a way that re
turned a different type than the expected constant. this is an unlikely failure mode, and should not occur. indictionarymode the object whose property is being accessed is in dictionary mode. objects which are used in ways that suggest they are hashtables are
turned into dictionary objects and their types marked as such. noprotofound a prototype object was not found for all the object used by this...
...ith too many arguments. these thresholds are subject to change. cantinlinerecursive unable to inline function call. the interpreted callee function recurs for more than one level. the first level of recursion is inlinable. cantinlineheavyweight unable to inline function call. the interpreted callee function contains variables bindings that are closed over. for example, function f() { var x; re
turn function () { x++; } } closes over x in f. cantinlineneedsargsobj unable to inline function call. the interpreted callee function requires an arguments object to be created. cantinlinedebuggee unable to inline function call. the interpreted callee function is being debugged by the debugger api. cantinlineunknownprops unable to inline function call. the engine knows nothing definite about th...
...ction call. the interpreted callee function is being debugged by the debugger api. cantinlineunknownprops unable to inline function call. the engine knows nothing definite about the type of the callee function object. cantinlineunreachable unable to inline function call. the call site has not been observed to have ever been executed. it lacks observed type information for its arguments, its re
turn value, or both. cantinlinebound unable to inline function call. the interpreted callee is a bound function generated from function.prototype.bind that failed some sub-checks. (expand) cantinlinenativenospecialization unable to inline function call. ion does not have built-in specialization for the native (implemented in c++) callee function. cantinlinenativebadform unable to inline function...
JS::DeflateStringToUTF8Buffer
to hold the number of bytes written to the buffer. if numcharsp is provided, it will be updated to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. ...
... to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. ...
...e string is fully encoded. ...
JSNative
avascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). argc unsigned the number of arguments supplied to the function by the caller (as opposed to, say, the number of arguments the function is specified to take in its jsfunctionspec). vp js::value * the arguments, the this argument, the re
turn-value slot, and the callee function object are accessible through this pointer using macros described below. description jsnative is the type of native implementations of javascript functions. full documentation of how to define a jsnative (or a jsfastnative, the equivalent typedef which preceded it) is available in the api header "js/callargs.h" added in spidermonkey 24. this header is...
... defined there; the macros providing equivalent functionality are deprecated. the behavior of a jsnative is implemented using a js::callargs structure added in spidermonkey 17. ...
...mplemented using a js::callargs structure added in spidermonkey 17. (this structure is now provided in "js/callargs.h" added in spidermonkey 24 as well as through "jsapi.h".) this structure encapsulates access to the callee function, this, the function call's arguments, and the eventual re
turn value. on success, the callback must set js::callargs::rval() or call js_set_rval (at least once) and re
turn true. otherwise it should either report an error (using e.g. js_reporterror or js_reportoutofmemory) or raise an exception (using js_setpendingexception), and the callback must re
turn false. (re
turning false without reporting an error or raising an exception terminates the script with an uncatchable error. this has limited use cases; it's used to implement firefox's "slow script" dialog, for exam...
JSNewEnumerateOp
ermonkey, noting the jsclass_new_enumerate flag, will cast that function pointer back to type jsnewenumerateop before calling it.) the behavior depends on the value of enum_op: jsenumerate_init a new, opaque iterator state should be allocated and stored in *statep. (you can use private_to_jsval to tag the pointer to be stored). the number of properties that will be enumerated should be re
turned as an integer jsval in *idp, if idp is non-null, and provided the number of enumerable properties is known. if idp is non-null and the number of enumerable properties can't be computed in advance, *idp should be set to jsval_zero. jsenumerate_init_all used identically to jsenumerate_init, but exposes all properties of the object regardless of enumerability. jsenumerate_next a previously...
...ided the number of enumerable properties is known. if idp is non-null and the number of enumerable properties can't be computed in advance, *idp should be set to jsval_zero. jsenumerate_init_all used identically to jsenumerate_init, but exposes all properties of the object regardless of enumerability. jsenumerate_next a previously allocated opaque iterator state is passed in via statep. ...
... passed in via statep. re
turn the next jsid in the iteration using *idp. the opaque iterator state pointed at by statep is destroyed and *statep is set to jsval_null if there are no properties left to enumerate. jsenumerate_destroy destroy the opaque iterator state previously allocated in *statep by a call to this function when enum_op was jsenumerate_init or jsenumerate_init_all. the re
turn value is used to indicate success, with a value of false indicating failure. see also mxr id search for jsnewenumerateop jsenumerateop bug 1097267 ...
JS_GetGlobalForScopeChain
obsolete since jsapi 25this 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. this article covers features introduced in spidermonkey 1.8.5 re
turns the global object for the active function on the context. renamed to js::currentglobalornull. ...
...uraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 re
turns the global object for the active function on the context. renamed to js::currentglobalornull. syntax jsobject * js_getglobalforscopechain(jscontext *cx); name type description cx jscontext * the context for which to re
turn the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getglobalforscopechain() re
turns the global object for whatever function is currently running on the context. ...
...obalforscopechain(jscontext *cx); name type description cx jscontext * the context for which to re
turn the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getglobalforscopechain() re
turns the global object for whatever function is currently running on the context. in other words, it re
turns the global object on the current scope chain. if there is no javascript running on the context, this re
turns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming obsolete. see also js_getglobalforobject js::currentglobalornull bug 899245 ...
JS_GetProperty
description js_getproperty examines a specified js object obj and its prototype chain for a property with the specified name. it behaves like the javascript expression obj[name]. js_getucproperty is the unicode version of the function. js_getpropertybyid is the same but takes a js::handleid for the property name. in the simplest case, js_getproperty stores the value of the property in *vp and re
turns true. however, several different hooks can affect property gets. the full algorithm is described below. details first, a property lookup is performed. if the lookup proceeds without error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined. then the jsclass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp). for...
...etails first, a property lookup is performed. if the lookup proceeds without error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined. then the jsclass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp). for many objects, including objects of standard classes such as object and array, this hook does nothing and re
turns true, so the property get succeeds and undefined is left in *vp. if the property is found on a non-native object, get handler of proxy (only if the object is a proxy) or its jsobjectops.getproperty method is called. otherwise the property is found on a native object. if the property has a javascript getter, it is called. otherwise *vp is set to the property's stored value, or undefined if the ...
... or its jsobjectops.getproperty method is called. otherwise the property is found on a native object. if the property has a javascript getter, it is called. otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp). for many properties, the getter does nothing and re
turns true, so the property get succeeds and the property's stored value is left in *vp. internally, property retrieval, including all the behavior described above, is implemented by obj's jsobjectops.getproperty callback. on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and re
turn true. on an error or exception, these functions ret...
JS_InstanceOf
optional argument vector. if non-null, report an error if obj is not of type clasp. argv must be the argv argument passed from the engine to a jsnative callback, js_argv(cx, rv) in a jsfastnative callback, or null. obsolete since jsapi 32 description js_instanceof can be used to check whether an object obj is of a particular jsclass. to use it this way, pass null for argv. js_instanceof re
turns true if obj is of the given class and false otherwise. that is, it re
turns js_getclass(obj) == clasp. js_instanceof can also be used in native functions to check the class of an argument when a particular class is required. to use it this way, pass the arguments provided by the engine for args with js::callargsfromvp(argc, vp). when args is non-null, js_instanceof behaves as follows. if obj is ...
... note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain. js_hasinstance is similar to instanceof. ...
... note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain. js_hasinstance is similar to instanceof. ...
JS_IsConstructing
ructing(jscontext *cx, jsval *vp); name type description cx jscontext * the cx parameter passed to the jsnative. vp jsval * the vp parameter passed to the jsnative. description js_isconstructing must be called only from a jsnative called from the engine. cx and vp must be the arguments that the engine passed to that jsnative. ...
...many constructors do not need to call it either. ...
...many constructors do not need to call it either. in the common case where a constructor should have the same behavior (creating a new object) whether it is called with the new keyword or not, it does not need to call js_isconstructing. ...
JS_IsExceptionPending
determine whether an exception is pending in the js engine. syntax bool js_isexceptionpending(jscontext *cx); name type description cx jscontext * pointer to a js context to check for pending exceptions. description js_isexceptionpending re
turns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. ...
... whether an exception is pending in the js engine. syntax bool js_isexceptionpending(jscontext *cx); name type description cx jscontext * pointer to a js context to check for pending exceptions. description js_isexceptionpending re
turns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. otherwise, it re
turns false this can be used from jsnative functions which call js code to determine if the called js code threw an exception or not. ...
...code that might throw js exception ... */ if (js_isexceptionpending(cx)) { /* ... react to exception thrown in this block ... */ js_clearpendingexception(cx); } /* restore the original exception. ...
JS_NewScriptObject
obsolete since jsapi 8this 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. re
turn the javascript script object that wraps a compiled script. the compiled script and its parts live until the script object is garbage collected. syntax jsobject * js_newscriptobject(jscontext *cx, jsscript *script); name type description cx jscontext * the context in which to create the new script object. requires request. ...
...scriptobject(jscontext *cx, jsscript *script); name type description cx jscontext * the context in which to create the new script object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. script jsscript * the compiled script for which to create a new script object. description js_newscriptobject re
turns the script object associated with the given jsscript. every jsscript object has an associated jsobject script object. as long as the script object is reachable, the jsscript and its components are protected from garbage collection; when the script object is collected, the jsscript and its contents are freed. once you have created a script, you should immediately ensure that its script object is...
...ents are freed. once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope). a script object has no properties, and its prototype is object.prototype. so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it. on success, js_newscriptobject re
turns a pointer to the script's object. otherwise it re
turns null. (the name "js_newscriptobject" suggests that the script object is freshly allocated; this was the case in older versions of the api, but now the script object is allocated along with the jsscript itself.) (some temporary scripts used internally by spidermonkey do not have script objects allocated for them; such scripts are not access...
JS_SetGCCallback
cating the stage of gc. description js_setgccallback sets a callback function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the new callback function to use. callback related to finalization is separated to js_setfinalizecallback in jsapi 13. obsolete since jsapi 13 js_setgccallback re
turns a pointer to the previously used callback function upon completion. the application may store this re
turn value in order to restore the original callback when the new callback is no longer needed. to restore the original callback, call js_setgccallback a second time, and pass the old callback in as the cb argument. during each complete garbage collection cycle, the current gc callback is called...
... jsgc_mark_end obsolete since jsapi 13 end of marking. the callback may use js_isabouttobefinalized to clean up weak references to js objects (that is, pointers that are not traced by the gc). ...
...he original callback when the new callback is no longer needed. to restore the original callback, call js_setgccallback a second time, and pass the old callback in as the cb argument. during each complete garbage collection cycle, the current gc callback is called four times: jsgc_begin start of gc. the callback may prevent gc from starting by re
turning false. but even if the callback re
turns true, the garbage collector may determine that gc is not necessary, in which case the other three callbacks are skipped. jsgc_mark_end obsolete since jsapi 13 end of marking. the callback may use js_isabouttobefinalized to clean up weak references to js objects (that is, pointers that are not traced by the gc). jsgc_finalize_end obsolete since jsapi 13 end of finalization. js...
extISessionStorage
s an extension to store data for the life time of the application (e.g. browser). extisessionstorage is defined in toolkit/components/exthelper/extiapplication.idl. implemented via xpcom service for extiapplication: see the instructions on the fuel (firefox), steel (thunderbird) and smile (seamonkey) pages. method overview these methods are usually accessed via application.storage. ...
...) nsivariant get(in astring aname, in nsivariant adefaultvalue) attributes attribute type description events readonly attribute extievents the events object for the storage supports: "change" methods has() determines if a storage item exists with the given name. boolean has(in astring aname) parameters aname the name of an item re
turn value true if an item exists with the given name, false otherwise. set() sets the value of a storage item with the given name. void set(in astring aname, in nsivariant avalue) parameters aname the name of an item re
turn value get() gets the value of a storage item with the given name. re
turns a default value if the item does not exist. nsivariant get(in astring aname, in nsivaria...
...se. set() sets the value of a storage item with the given name. void set(in astring aname, in nsivariant avalue) parameters aname the name of an item re
turn value get() gets the value of a storage item with the given name. re
turns a default value if the item does not exist. nsivariant get(in astring aname, in nsivariant adefaultvalue) parameters aname the name of an item re
turn value value of the item or the given default value if no item exists with the given name. see also fuel (firefox), steel (thunderbird) and smile (seamonkey) ...
Components.Constructor
.constructor() is a handy shortcut for creating instances of xpcom components. it eliminates the clutter of typing components.classes, components.interfaces, createinstance, and so on every time you wish to create an instance. it also gives creation of xpcom objects more javascript-like syntax. ...
...her important benefit is that it precomputes some of the computation it does, so using a function re
turned from components.constructor() to create xpcom objects is faster than creating the object from base principles, as demonstrated below. (this benefit is also partly a result of having to travel through the layer between the javascript engine and xpcom fewer times.) the behavior of functions re
turned by components.constructor() varies depending upon the arguments given to components.constructor() when called. if only one argument is given, that argument is the contract id of the xpcom component to create. the component is then re
turned immediately, with only the base interface nsisupports available on it; you must call nsisupports.queryinterface() on it to call methods on the object. for ex...
... initializer) { var ccargs = arguments; function ctor() { var instance = components.classes[contractid] .createinstance(components.interfaces.nsisupports); if (ccargs.length > 1) { instance.queryinterface(components.interfaces[interfacename]); if (ccargs.length > 2) instance[initializer].apply(instance, arguments); } re
turn instance; } re
turn ctor; } ...
Components.classes
classesbyid instead of components.classes to retrieve it. note also that it is possible that a given add-on component with a given contractid will be present on one machine but not have been installed on another machine. if the given element in the components.classes object is not registered on the machine then trying to access it will generate a javascript warning in strict mode and the value re
turned will be the javascript value undefined. you should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in components.classes)) // do something... the properties of the components.classes object can be enumerated using a for...in loop. usage in order to retrieve the object for a given contractid, you can query the components.classes array as...
... = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service. ...
... to access a service (a singleton component, only single instance of which exists at any time), you should use getservice instead of createinstance: var os = components.classes["@mozilla.org/observer-service;1"] ...
Components.utils.evalInWindow
this function is no longer available as of firefox 34. see bug 1042840 for details. this function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context. the result is structured cloned back to the original context, unless it is native (for example, if it re
turns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper already), so it's guaranteed to behave predictably. this is useful for privileged code, such as add-on code, to access variables and apis defined in web content. even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example,...
... have been redefined to do something unexpected). this function is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. syntax var result = components.utils.evalinwindow(script, window); parameters script : string the script to evaluate in the other window. window : object the window in which to evaluate the script. re
turns the result of evaluating the script. if this is just native (for example, a dom node), then the function relies on xraywrappers to wrap the re
turned content, otherwise the result is structured-cloned. this does impose some restrictions on the sorts of things that can be re
turned: in particular, the result can't contain any functions, because functions can't be structured-cloned. example suppose ...
...y the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop); // 42 but note that the add-on script must trust that the page script has not redefined the setter on somelocalvariable: unlike xraywrappers, evalinwindow() does not provide x-ray vision. if the re
turned object contains a function, calls to evalinwindow() will throw an error: // page-script.js function bar() { } var somelocalvariablecontainingafunction = {name: "selection1", foo : bar}; // add-on-script.js components.utils.evalinwindow("somelocalvariablecontainingafunction", contentwindow); // error, function can't be cloned ...
Components.utils
es. its interface is defined at js/xpconnect/idl/xpccomponents.idl. the object currently has the following members: editors! please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context. createarrayin() removed in gecko 31 re
turns an array created in specified compartment. createobjectin() creates a new object, created in the scope of the specified object's compartment. dispatch() dispatches a runnable to the current/main thread. if the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets called. evalinsandbox...
... forceshrinkinggc() forces a shrinking garbage collection cycle. getcomponentsforscope() this seemingly-paradoxical api allows privileged code to explicitly give unprivileged code a reference to its own components object (whereas it's normally hidden away on a scope chain visible only to xbl methods). see also specialpowers.getcomponents. getglobalforobject() re
turns the global object with which a given object is associated (through its prototype chain at birth, for example). getjstestingfunctions() getobjectprincipal() gets the nsiprincipal for the given javascript object. getweakreference() gets a weak reference for the object passed in. import() loads a js module into the current script, without sharing a...
.... lookupmethod() looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. makeobjectpropsnormal() ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. nondeterministicgetweakmapkeys() re
turn the keys in a weak map. this operation is non-deterministic because it is affected by the scheduling of the garbage collector and the cycle collector. this should only be used to write tests of the interaction of the gc and cc with weak maps. obsolete since gecko 45 the function was moved to threadsafechromeutils nukesandbox() recomputewrappers() to be called f...
nsDirectoryService
for instance, it can give you the path of the system's temporary directory, desktop directory, current working directory, and so on. class id f00152d0-b40b-11d3-8c9c-000064657374 contractid @mozilla.org/file/directory_service;1 supported interfaces nsiproperties nsidirectoryservice remarks this component is a singleton and should therefore be accessed via the xpcom service manager. ...
...ager. example code #include "nsxpcom.h" #include "nscomptr.h" #include "nsdirectoryservicedefs.h" #include "nsiservicemanager.h" #include "nsiproperties.h" /** * get the location of the system's "temp" directory. ...
...nscomptr<nsiservicemanager> svcmgr; rv = ns_getservicemanager(getter_addrefs(svcmgr)); if (ns_failed(rv)) re
turn rv; nscomptr<nsiproperties> directory; rv = svcmgr->getservicebycontractid("@mozilla.org/file/directory_service;1", ns_get_iid(nsiproperties), getter_addrefs(directory)); if (ns_failed(rv)) re
turn rv; rv = directory->get(ns_os_temp_dir, ns_get_iid(nsifile), aresult); re
turn rv; } note that ns_os_temp_dir is defined in nsdirectoryservicedefs.h along with a number of other directory service keys. see also using nsidirectoryservice nsiproperties.get() nsidirectoryserviceprovider ...
nsresult
« xpcom api reference the nsresult data type is a strongly-typed enum used to represent a value re
turned by an xpcom function; these are typically error or status codes. for a list of defined result values, see error codes re
turned by mozilla apis. note: on compilers that do not support strongly-typed enums (that is, compilers that don't support this feature of c++11), it falls back to being an unsigned 32-bit integer, as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as re
turning an nsresult value from a function whose signature indicates it re
turns a boolean. because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ... ...
...integer, as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as re
turning an nsresult value from a function whose signature indicates it re
turns a boolean. ...
...ko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as re
turning an nsresult value from a function whose signature indicates it re
turns a boolean. because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ... ...
operator=
« xpcom api reference summary this operator is a shortcut for the inherited nsacstring::assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedcstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsacstring to append to this string. ...
...:assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedcstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsacstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters ...
... object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also nsacstring::assign ...
operator=
« xpcom api reference summary this operator is a shortcut for the inherited nsastring::assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsastring to append to this string. ...
...g::assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsembedstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const abstract_string_type& astring ); parameters astring [in] a nsastring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters ...
... object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also nsastring::assign ...
IAccessibleApplication
ion interface via queryservice from any object so that ats can easily determine specific information about the application such as its name or version. ...
...ion such as its name or version. method overview [propget] hresult appname([out] bstr name ); [propget] hresult appversion([out] bstr version ); [propget] hresult toolkitname([out] bstr name ); [propget] hresult toolkitversion([out] bstr version ); methods appname() re
turns the application name. [propget] hresult appname( [out] bstr name ); parameters name the application name. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. appversion() re
turns the application version. [propget] hresult appversion( [out] bstr version ); parameters version the application version. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. toolkitname() re
turns the toolkit/bridge name. [propget] hresult toolkitname( [out] bstr name ); p...
..., [out] value is null. s_ok. appversion() re
turns the application version. [propget] hresult appversion( [out] bstr version ); parameters version the application version. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. toolkitname() re
turns the toolkit/bridge name. [propget] hresult toolkitname( [out] bstr name ); parameters name the toolkit/bridge name. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. toolkitversion() re
turns the toolkit/bridge version. [propget] hresult toolkitversion( [out] bstr version ); parameters version the toolkit/bridge version. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. ...
imgIRequest
: 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 re
turned request will have aobserver as the observer. aobserver will be notified synchronously (before the clone call re
turns) with all the notifications that have already been dispatched for this image load. imgirequest clone( in imgidecoderobserver aobserver ); parameters aobserver re
turn value decrementanimationconsumers() tell the image it can forget about a request that the image animate. vo...
...void incrementanimationconsumers(); parameters none. lockimage() locks an image. ...
...void incrementanimationconsumers(); parameters none. lockimage() locks an image. if the image does not exist yet, locks it once it becomes available. the lock persists for the lifetime of the imgirequest (until unlockimage() is called) even if the underlying image changes. ...
mozISpellCheckingEngine
uggestions, out pruint32 count); attributes attribute type description copyright wstring a string indicating the copyright of the engine. not currently used. read only. dictionary wstring the name of the current dictionary used by check() and suggest(). this will be either element from the array re
turned by getdictionarylist() or an empty string if no dictionary is selected. note: setting this value to a value that doesn't match an existing dictionary throws a ns_error_file_not_found exception. when this attribute's value is changed, a "spellcheck-dictionary-update" notification is sent. if the dictionary was set to "no dictionary" (that is, by specifying an empty str...
...ary is selected. note: setting this value to a value that doesn't match an existing dictionary throws a ns_error_file_not_found exception. when this attribute's value is changed, a "spellcheck-dictionary-update" notification is sent. if the dictionary was set to "no dictionary" (that is, by specifying an empty string), the observer may select another dictionary before re
turning. language wstring the language this spell checker is using when checking. this is the language of dictionary. read only. when this changes, the spell checker sends a "spellcheck-dictionary-update" notification. name wstring the name of the engine. not currently used. read only. personaldictio...
... adddirectory( nsifile dir ); parameters dir an nsifile object indicating the directory from which to add dictionaries. check() checks a word to determine if it's spelled correctly. when this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check( in wstring word ); parameters word a word to check for correct spelling. re
turn value re
turns true if word is spelled correctly according to the dictionary attribute, and re
turns false if word is misspelled. getdictionarylist() gets the list of dictionaries. void getdictionarylist( [array, size_is(count)] out wstring dictionaries, out pruint32 count ); parameters dictionaries a list of dictionaries supported by this spell checker. the dictionary attribute...
mozIStorageRow
. storage/public/mozistoragerow.idlscriptable please add a summary to this article. ...
...iant getresultbyindex(in unsigned long aindex); nsivariant getresultbyname(in autf8string aname); methods getresultbyindex() re
turns the value from a specific column in the row, using a zero-based index to identify the column. nsivariant getresultbyindex( in unsigned long aindex ); parameters aindex the zero-based index of the column number whose value is to be re
turned. re
turn value an nsivariant object containing the value of the specified column. getresultbyname() re
turns the value from a specific column in the row, identifying the column by name. ...
...meters aindex the zero-based index of the column number whose value is to be re
turned. re
turn value an nsivariant object containing the value of the specified column. getresultbyname() re
turns the value from a specific column in the row, identifying the column by name. nsivariant getresultbyname( in autf8string aname ); parameters aname the name of the column whose value is to be re
turned. re
turn value an nsivariant object containing the value of the specified column. see also storage mozistorageresultset mozistorageconnection mozistoragestatement ...
nsIAbCard
llist boolean maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mailing list. allowremotecontent boolean allow remote content to be displayed in html mail received from this contact methods getcardvalue() astring getcardvalue(in string name) parameters name the attribute you want the value for. re
turn value the value of the attribute asked for. setcardvalue() void setcardvalue(in string attrname, in astring value) parameters attrname the attribute you want to set. value the value to set the attribute to. copy() this function will copy all values from one card to another. void copy(in nsiabcard srccard) parameters srccard the source card to copy values from. equals() ...
... attrname, in astring value) parameters attrname the attribute you want to set. value the value to set the attribute to. copy() this function will copy all values from one card to another. void copy(in nsiabcard srccard) parameters srccard the source card to copy values from. equals() boolean equals(in nsiabcard card) parameters card the card you are comparing with. re
turn value true if the cards are the same. converttobase64encodedxml() string converttobase64encodedxml() re
turn value converttoxmlprintdata() astring converttoxmlprintdata() re
turn value converttoescapedvcard() string converttoescapedvcard() re
turn value generatename() generate a name from the card for display purposes. using the firstname, lastname and the displayname. we all...
...book.properties. 2 firstlast, formatted following firstlastformat property in addressbook.properties. abundle an optional parameter that is a pointer to a string bundle that holds: addressbook.properties. if this bundle is not supplied, then the function will obtain the bundle itself. if cached by the caller and supplied to this function, then performance will be improved over many calls. re
turn value a string containing the generated name. generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values. astring generatephoneticname(in boolean alastnamefirst) parameters alastnamefirst set to true to put the last name before the first. re
turn value a string containing the generated phonetic name. ...
nsIAccessNode
a unique id calculated for this dom node, for the purposes of caching and referencing this object. read only. native code only! methods getchildnodeat() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) get the nth child of this node. nsiaccessnode getchildnodeat( in long childnum ); parameters childnum zero-based child index. re
turn value the nth nsiaccessnode child. exceptions thrown ns_error_failure indicates that the access node is unattached from the accessible tree. getcomputedstylecssvalue() retrieve the computed style value as nsidomcssprimitivevalue for the dom node this access node is associated with. note: the meanings of width, height and other size measurements depend on the version of css being used. t...
...fore, for bounds information, it is better to use nsiaccessible.getbounds(). nsidomcssprimitivevalue getcomputedstylecssvalue( in domstring pseudoelt, in domstring propertyname ); parameters pseudoelt the pseudo element to retrieve style for, or empty string for general computed style information for the node. propertyname retrieve the computed style value for this property name. re
turn value the nsidomcssprimitivevalue computed style value. exceptions thrown ns_error_failure indicates that the access node is unattached from the accessible tree. getcomputedstylevalue() retrieve the computed style value for this dom node, if it is a dom element. note: the meanings of width, height and other size measurements depend on the version of css being used. therefore, for bounds...
... for bounds information, it is better to use nsiaccessible.getbounds(). domstring getcomputedstylevalue( in domstring pseudoelt, in domstring propertyname ); parameters pseudoelt the pseudo element to retrieve style for, or null for general computed style information for this node. propertyname retrieve the computed style value for this property name, for example "border-bottom". re
turn value the computed style value. exceptions thrown ns_error_failure indicates that the access node is unattached from the accessible tree. scrollto() makes an object visible on screen. void scrollto( in unsigned long ascrolltype ); parameters ascrolltype defines where the object should be placed on the screen (see nsiaccessiblescrolltype.constants for available constants). exce...
GetRelation
exception thrown ns_error_invalid_arg indicates that the given index is invalid. remark currently we do not support multiple relations so the zero index may be valid only. refer to relations documentation for more info. ...
...exception thrown ns_error_invalid_arg indicates that the given index is invalid. remark currently we do not support multiple relations so the zero index may be valid only. refer to relations documentation for more info. ...
...exception thrown ns_error_invalid_arg indicates that the given index is invalid. remark currently we do not support multiple relations so the zero index may be valid only. refer to relations documentation for more info. ...
nsIAccessibleHyperText
long the number of links contained within this hypertext object. read only. note: renamed from links in gecko 1.9 methods getlink() retrieves the nsiaccessiblehyperlink object at the given link index. nsiaccessiblehyperlink getlink( in long linkindex ); parameters linkindex 0-based index of the link that is to be retrieved. this can be retrieved via getlinkindex(). ...
...linkindex(). re
turn value an nsiaccessiblehyperlink object. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg the link index is invalid. getlinkindex() the link index at the given offset (character index). long getlinkindex( in long charindex ); parameters charindex the 0-based character index. re
turn value the index of the link if it's presented on the given character index, otherwise -1. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getselectedlinkindex() obsolete since gecko 1.9 (firefox 3) long getselectedlinkindex(); parameters none. ...
...eters charindex the 0-based character index. re
turn value the index of the link if it's presented on the given character index, otherwise -1. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getselectedlinkindex() obsolete since gecko 1.9 (firefox 3) long getselectedlinkindex(); parameters none. re
turn value missing description exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. see also nsiaccessiblehyperlink ...
nsIAccessibleRelation
changed in gecko 1.9 (firefox 3) note: be carefull, do not change constants until atk has a structure to map gecko constants into atk constants. method overview nsiaccessible gettarget(in unsigned long index); nsiarray gettargets(); attributes attribute type description relationtype unsigned long re
turns the type of the relation. read only. targetscount unsigned long re
turns the number of targets for this relation. read only. constants constant value description relation_nul 0x00 relation_controlled_by 0x01 some attribute of this object is affected by a target object. ...
...cription can occur both on their own, and in the name or description fields of an nsiaccessible. relation_description_for 0x0f this object is describes the target object. relation_default_button 0x4000 part of a form/dialog with a related default button. it is used for msaa only, no for ia2 nor atk/at-spi. methods gettarget() re
turns accessible relation target at the given index. nsiaccessible gettarget( in unsigned long index ); parameters index zero-based index of relation target. re
turn value re
turns an nsiaccessible object. exceptions thrown ns_error_invalid_arg indicates the given index is out of range. gettargets() re
turns an array of accessible relation targets. nsiarray ge...
... given index. nsiaccessible gettarget( in unsigned long index ); parameters index zero-based index of relation target. re
turn value re
turns an nsiaccessible object. exceptions thrown ns_error_invalid_arg indicates the given index is out of range. gettargets() re
turns an array of accessible relation targets. nsiarray gettargets(); parameters none. re
turn value an nsiarray object, each item in the array implements an nsiaccessible. ...
nsIApplicationCache
cation cache. void addnamespaces( in nsiarray namespaces ); parameters namespaces an nsiarray of nsiapplicationcachenamespace objects describing the namespaces to add to the cache. discard() discards this application cache. this removes all resources it has cached. if this is the active application cache for the group, the group is removed. void discard(); parameters none. gatherentries() re
turns a list of entries in the cache whose type matches one or more of the specified types. void gatherentries( in pruint32 typebits, out unsigned long count, [array, size_is(count)] out string keys ); parameters typebits a bit field indicating the types against which to match. see constants for a list of types. count on re
turn, indicates how many matching entries were found. keys an array of ...
... gatherentries( in pruint32 typebits, out unsigned long count, [array, size_is(count)] out string keys ); parameters typebits a bit field indicating the types against which to match. see constants for a list of types. count on re
turn, indicates how many matching entries were found. keys an array of the keys matching one or more of the types indicated by typebits. getmatchingnamespace() re
turns the most specific namespace matching a given key. nsiapplicationcachenamespace getmatchingnamespace( in acstring key ); parameters key the key for the cache entry whose most specific namespace is to be re
turned. re
turn value an nsiapplicationcachenamespace object describing the most specific namespace matching the given key. gettypes() gets the types for a given entry in the cache. unsigned...
...see constants for a list of types. initashandle() init this application cache instance to just hold the group id and the client id to work just as a handle to the real cache. used on content process to simplify the application cache code. ...
nsIApplicationCacheService
ally( in nsiapplicationcache cache, in acstring key ); parameters cache the cache in which the entry is currently cached. key the cache entry's key. chooseapplicationcache() tries to find the best application cache to serve a specified resource. nsiapplicationcache chooseapplicationcache( in acstring key ); parameters key the cache entry key for which to select an application cache. re
turn value the nsiapplicationcache best able to serve the resource indicated by the key parameter. createapplicationcache() creates a new, empty application cache for the specified cache group. nsiapplicationcache createapplicationcache( in acstring group ); parameters group the cache group for which to create an application cache. re
turn value the newly-created nsiapplicationcache. deactivategro...
...icationcache createapplicationcache( in acstring group ); parameters group the cache group for which to create an application cache. re
turn value the newly-created nsiapplicationcache. deactivategroup() deactivates the currently active cache object for the specified cache group. void deactivategroup( in acstring group ); parameters group the cache group to deactivate. getactivecache() re
turns the currently active cache object for a cache group. nsiapplicationcache getactivecache( in acstring group ); parameters group the cache group for which to re
turn an application cache. re
turn value the currently active cache object for the cache group. getapplicationcache() re
turns the nsiapplicationcache object for the specified client id. nsiapplicationcache getapplicationcache( in acst...
...ncache getactivecache( in acstring group ); parameters group the cache group for which to re
turn an application cache. re
turn value the currently active cache object for the cache group. getapplicationcache() re
turns the nsiapplicationcache object for the specified client id. nsiapplicationcache getapplicationcache( in acstring clientid ); parameters clientid the client id for which to re
turn the application cache object. re
turn value the application cache object for the specified client id. getgroups() re
turns the list of application cache groups. void getgroups( out unsigned long count, optional [array, size_is(count), retval] out string groupids ); parameters count optional the count of the application cache groups. groupids the list of application cache groups. see also o...
nsIArray
ention is that the elements of the array should not be modified. documentation within a specific interface should describe variations from this convention. it is also convention that if an interface provides access to an nsiarray, that the array should not be queryinterfaced to an nsimutablearray for modification. if the interface in question had intended the array to be modified, it would have re
turned an nsimutablearray! null is a valid entry in the array, and as such any nsisupports parameters may be null, except where noted. method overview nsisimpleenumerator enumerate(); unsigned long indexof(in unsigned long startindex, in nsisupports element); void queryelementat(in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result); attributes attribute t...
... unsigned long indexof(in unsigned long startindex, in nsisupports element); void queryelementat(in unsigned long index, in nsiidref uuid, [iid_is(uuid), retval] out nsqiresult result); attributes attribute type description length unsigned long the number of elements in the array. read only. methods enumerate() enumerate the array. nsisimpleenumerator enumerate(); parameters none. re
turn value a new enumerator positioned at the start of the array. exceptions thrown ns_error_failure if the array is empty (to make it easy to detect errors). ns_error_out_of_memory if there is not enough memory to complete the operation. indexof() get the position of a specific element. note that since null is a valid input, exceptions are used to indicate that an element is not found. unsigned lon...
.... indexof() get the position of a specific element. note that since null is a valid input, exceptions are used to indicate that an element is not found. unsigned long indexof( in unsigned long startindex, in nsisupports element ); parameters startindex the initial element to search in the array. to start at the beginning, use 0 as the startindex. element the element you are looking for. re
turn value a number >= startindex which is the position of the element in the array. exceptions thrown ns_error_failure if the element was not in the array. queryelementat() retrieve a specific element of the array, and queryinterface it to the specified interface. null is a valid result for this method, but exceptions are thrown in other circumstances. void queryelementat( in unsigned long index,...
nsIAuthInformation
ring the authentication scheme used for this request, if applicable. if the protocol for this authentication does not support schemes, this will be the empty string. otherwise, this will be a string such as "basic" or "digest". this string will always be in lowercase. read only. domain astring the initial value should be used to prefill the dialog or be shown in some other way to the user. on re
turn, this parameter should contain the domain entered by the user. this attribute is only used if flags include #need_domain. flags unsigned long flags describing this dialog. a bitwise or of the constants. it is possible that neither #auth_host nor #auth_proxy are set. auth prompts should ignore flags they do not understand; especially, they should not throw an exception because of an unsupported...
...se or of the constants. it is possible that neither #auth_host nor #auth_proxy are set. auth prompts should ignore flags they do not understand; especially, they should not throw an exception because of an unsupported flag. read only. password astring the initial value should be used to prefill the dialog or be shown in some other way to the user. the password should not be shown in clear. on re
turn, this parameter should contain the password entered by the user. realm astring the server-supplied realm of the authentication as defined in rfc 2617. can be the empty string if the protocol does not support realms. otherwise, this is a human-readable string like "secret files". read only. username astring the initial value should be used to prefill the dialog or be shown in some other way to...
... should contain the password entered by the user. realm astring the server-supplied realm of the authentication as defined in rfc 2617. can be the empty string if the protocol does not support realms. otherwise, this is a human-readable string like "secret files". read only. username astring the initial value should be used to prefill the dialog or be shown in some other way to the user. on re
turn, this parameter should contain the username entered by the user. this field can only be changed if the #only_password flag is not set. constants constant value description auth_host 1 this dialog belongs to a network host. auth_proxy 2 this dialog belongs to a proxy. need_domain 4 this dialog needs domain information. the user interface should show a domain field, prefilled with the d...
nsIAuthPrompt
wstring result ); parameters dialogtitle the title of the dialog. text the text of the prompt message dialog box. passwordrealm the password realm. for example, ldap://localhost/dc=test. savepassword saving password option. one of the save_password_* constants defaulttext the default text for the text input dialog box. result the result of the dialog box, ok or cancel buttons. re
turn value true for ok, false for cancel. promptpassword() this method puts up a password dialog with ok and cancel buttons. note: if a username is specified, the username should be escaped. boolean promptpassword( in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, inout wstring pwd ); parameters dialogtitle the title of the dialog. text ...
...alm the password realm. for example, ldap://localhost/dc=test. if a username is specified (http://user@site.com) it will be used when matching existing logins or saving new ones. if no username is specified, only password-only logins will be matched or saved. savepassword saving password option. one of the save_password_* constants pwd the password entered by the user if ok was selected. re
turn value true for ok, false for cancel. promptusernameandpassword() this method puts up a username/password dialog with ok and cancel buttons. boolean promptusernameandpassword( in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, inout wstring user, inout wstring pwd ); parameters dialogtitle the title of the dialog. text the text of t...
... ...
nsIBlocklistService
the addon object whose blocklist state is to be determined. appversion optional the version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. toolkitversion optional the version of the toolkit we are checking in the blocklist. if this parameter is null, the version of the running toolkit is used. re
turn value the blocklist state of the add-on, one of the constants. getpluginblockliststate() determine the blocklist state of a plugin. unsigned long getpluginblockliststate( in nsiplugintag plugin, in astring appversion, optional in astring toolkitversion optional ); parameters plugin the plugin to get the state for. appversion optional the version of the application we are c...
... ); parameters plugin the plugin to get the state for. appversion optional the version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. toolkitversion optional the version of the toolkit we are checking in the blocklist. if this parameter is null, the version of the running toolkit is used. re
turn value the blocklist state of the plugin, one of the constants. isaddonblocklisted() determine if an item is blocklisted. boolean isaddonblocklisted( in jsval addon, in astring appversion, optional from gecko 1.9.1 in astring toolkitversion optional from gecko 1.9.1 ); parameters addon the addon object to be checked. appversion optional from gecko 1.9.1 the version of the a...
...he addon object to be checked. appversion optional from gecko 1.9.1 the version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. toolkitversion optional from gecko 1.9.1 the version of the toolkit we are checking in the blocklist. if this parameter is null, the version of the running toolkit is used. re
turn value true if the item is blocklisted, otherwise false. ...
nsIBoxObject
evice pixels. read only. width long the width of the box, in css pixels. read only. x long the x coordinate of the box, in css pixels. read only. y long the y coordinate of the box, in css pixels. read only. ...
...inate of the box, in css pixels. read only. y long the y coordinate of the box, in css pixels. read only. ...
...tlookandfeelmetric() obsolete since gecko 1.9 (firefox 3) wstring getlookandfeelmetric( in wstring propertyname ); parameters propertyname re
turn value getproperty() wstring getproperty( in wstring propertyname ); parameters propertyname re
turn value getpropertyassupports() nsisupports getpropertyassupports( in wstring propertyname ); parameters propertyname re
turn value removeproperty() void removeproperty( in wstring propertyname ); parameters propertyname setproperty() void setproperty( in wstring propertyname, in wstring propertyvalue ); parameters propertyname propertyvalue setpropertyassupports() void setpropertyassupports( in wstring propertyname, in nsisupports value ); parameters propertyname value ...
nsICRLManager
void importcrl( [array, size_is(length)] in octet data, in unsigned long length, in nsiuri uri, in unsigned long type, in boolea...
... methods computenextautoupdatetime() wstring computenextautoupdatetime( in nsicrlinfo info, in unsigned long autoupdatetype, in double noofdays ); parameters info autoupdatetype noofdays re
turn value deletecrl() delete the crl. void deletecrl( in unsigned long crlindex ); parameters crlindex getcrls() get a list of crl entries in the db. nsiarray getcrls(); parameters none. re
turn value importcrl() import a crl into the certificate database. void importcrl( [array, size_is(length)] in octet data, in unsigned long length, in nsiuri uri, in unsigned long type, in boolean dosilentdownload, in wstring crlkey ); parameters data length uri type dosilentdownload crlkey reschedulecrlautoupdate() this would reschedule the autoupdate of crls with auto update en...
...ta length uri type dosilentdownload crlkey reschedulecrlautoupdate() this would reschedule the autoupdate of crls with auto update enable. void reschedulecrlautoupdate(); parameters none. updatecrlfromurl() update an existing crl from the last fetched url. needed for the update button in crl manager. boolean updatecrlfromurl( in wstring url, in wstring key ); parameters url key re
turn value ...
nsICacheMetaDataVisitor
see also nsicache nsicacheentrydescriptor ...
...see also nsicache nsicacheentrydescriptor ...
...methods visitmetadataelement() this method is called for each key/value pair in the meta data for a cache entry. boolean visitmetadataelement( in string key, in string value ); parameters key the key for visiting the meta data for a cache entry. value the value for visiting the meta data for a cache entry. re
turn value re
turns true if the provided key/value finds a cache entry, otherwise re
turns false. see also nsicache nsicacheentrydescriptor ...
nsIChannel
d reason. load_classify_uri 22 this flag tells the channel to use uri classifier service to check the uri when opening the channel. methods asyncopen() asynchronously open this channel. data is fed to the specified stream listener as it becomes available. the stream listener's methods are called on the thread that calls asyncopen and are not called until after asyncopen re
turns. if asyncopen re
turns successfully, the channel promises to call at least onstartrequest and onstoprequest. if the nsirequest object passed to the stream listener's methods is not this channel, an appropriate onchannelredirect notification needs to be sent to the notification callbacks before onstartrequest is called. once onstartrequest is called, all following method calls on alistener will g...
...sent to the notification callbacks before onstartrequest is called. once onstartrequest is called, all following method calls on alistener will get the request that was passed to onstartrequest. if the channel's and loadgroup's notification callbacks do not provide an nsichanneleventsink when onchannelredirect would be called, that's equivalent to having called onchannelredirect. if asyncopen re
turns successfully, the channel is responsible for keeping itself alive until it has called onstoprequest on alistener or called onchannelredirect. implementations are allowed to synchronously add themselves to the associated load group (if any). void asyncopen( in nsistreamlistener alistener, in nsisupports acontext ); parameters alistener the nsistreamlistener implementation. acontext ...
...st is redirected, rather than redirecting transparentlynote: nsichannel implementations are not required to implement this method. moreover, since this method may block the calling thread, it should not be called on a thread that processes ui events. like any other nsichannel method it must not be called on any thread other than the xpcom main thread. nsiinputstream open(); parameters none. re
turn value blocking input stream to the channel's data. exceptions thrown ns_error_in_progress if the channel is reopened. see also nsichanneleventsink for onchannelredirect ...
nsIChromeRegistry
td for a "locale" package. void canonify( in nsiuri achromeurl ); parameters achromeurl the url that is to be canonified. checkfornewchrome() refreshes the chrome list at runtime, looking for new packages and so forth. void checkfornewchrome(); parameters none. convertchromeurl() resolves a chrome url to an loadable uri using the information in the registry. a new nsiuri is re
turned; the original is left unmodified. this lets you take a non-canonical chrome uri, such as chrome://package/provider/file, and convert it into a canonical one. this is useful because chrome urls are allowed to be specified in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "c...
...o be specified in "shorthand", leaving the "file" portion off. in that case, the url is expanded to chrome://package/provider/package.ext. the extension, ext, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. nsiuri convertchromeurl( in nsiuri achromeurl ); parameters achromeurl the url that is to be converted. ...
...t, is one of: xul for a "content" package. css for a "skin" package. dtd for a "locale" package. nsiuri convertchromeurl( in nsiuri achromeurl ); parameters achromeurl the url that is to be converted. re
turn value a new nsiuri object containing the loadable uri for the specified chrome url. violates the xpcom interface guidelines wrappersenabled() re
turns whether xpcnativewrappers are enabled for the specified uri. boolean wrappersenabled( in nsiuri auri ); parameters auri the uri for which to determine if xpcnativewrappers are enabled. re
turn value true if xpcnativewrappers are enabled for the specified uri; otherwise false. see also chrome registration ...
nsIClipboard
k if there is data on the clipboard matching any of the flavors in the given list. boolean hasdatamatchingflavors( [array, size_is(alength)] in string aflavorlist, in unsigned long alength, in long awhichclipboard ); parameters aflavorlist an array of ascii strings. alength the length of the aflavorlist. awhichclipboard specifies the clipboard to which this operation applies. re
turn value re
turns true, if data is present and it matches the specified flavor. otherwise it re
turns false. setdata() this method sets the data from a transferable on the native clipboard. void setdata( in nsitransferable atransferable, in nsiclipboardowner anowner, in long awhichclipboard ); parameters atransferable the transferable containing the data to put on the clipboard. anown...
...able the transferable containing the data to put on the clipboard. anowner the owner of the transferable. awhichclipboard specifies the clipboard to which this operation applies. supportsselectionclipboard() this method allows clients to determine if the implementation supports the concept of a separate clipboard for selection. boolean supportsselectionclipboard(); parameters none. re
turn value re
turns true if kselectionclipboard is available. otherwise it re
turns false. supportsfindclipboard() this method allows clients to determine if the implementation supports the concept of a separate clipboard for find search strings. boolean supportsfindclipboard(); parameters none. re
turn value re
turns true if the separate clipboard for find search strings is supported. otherwise ...
...e re
turns true if kselectionclipboard is available. otherwise it re
turns false. supportsfindclipboard() this method allows clients to determine if the implementation supports the concept of a separate clipboard for find search strings. boolean supportsfindclipboard(); parameters none. re
turn value re
turns true if the separate clipboard for find search strings is supported. otherwise it re
turns false. see also nsiclipboardowner nsitransferable nsiarray using the clipboard ...
nsIClipboardCommands
lean cancopyimagecontents(); boolean cancopyimagelocation(); boolean cancopylinklocation(); boolean cancopyselection(); boolean cancutselection(); boolean canpaste(); void copyimagecontents(); void copyimagelocation(); void copylinklocation(); void copyselection(); void cutselection(); void paste(); void selectall(); void selectnone(); methods cancopyimagecontents() re
turns whether we can copy an image's contents. boolean cancopyimagecontents(); parameters none. re
turn value true if an image is selected, false otherwise. cancopyimagelocation() re
turns whether we can copy an image location. boolean cancopyimagelocation(); parameters none. re
turn value true if an image is selected, false otherwise. cancopylinklocation() re
turns whether we can copy a link location. ...
...cancopyimagecontents(); parameters none. re
turn value true if an image is selected, false otherwise. cancopyimagelocation() re
turns whether we can copy an image location. boolean cancopyimagelocation(); parameters none. re
turn value true if an image is selected, false otherwise. cancopylinklocation() re
turns whether we can copy a link location. boolean cancopylinklocation(); parameters none. re
turn value true if a link is selected, false otherwise. cancopyselection() re
turns whether there is a selection and it is copyable. boolean cancopyselection(); parameters none. re
turn value true if there is a selection, false otherwise. cancutselection() re
turns whether there is a selection and it is not read-only. ...
...inklocation(); parameters none. re
turn value true if a link is selected, false otherwise. cancopyselection() re
turns whether there is a selection and it is copyable. boolean cancopyselection(); parameters none. re
turn value true if there is a selection, false otherwise. cancutselection() re
turns whether there is a selection and it is not read-only. boolean cancutselection(); parameters none. re
turn value true if the current selection can be cut, false otherwise. canpaste() re
turns whether the current contents of the clipboard can be pasted and if the current selection is not read-only. boolean canpaste(); parameters none. re
turn value true if there is data to paste on the clipboard and the current selection is not read-only, false otherwise. copyimagecontents() copy the contents of the sel...
nsICollection
result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection. void appendelement( in nsisupports item ) parameters item nsisupports item to be appended to the list. clear() removes all items from the collection. void clear(); parameters none. count() re
turns the number of items in the collection. pruint32 count(); parameters none. re
turn value number of items in the list. enumerate() re
turns an nsienumerator that lets you iterate over the items in the collection. nsienumerator enumerate(); parameters none. re
turn value an nsienumerator. getelementat() re
turns the element at the specified index into the collection. nsisupports getelementat( in pr...
...queryelementat() performs a queryinterface on the item at the specified index into the collection. void queryelementat( in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters index position of the item to be queried. ...
...queryelementat() performs a queryinterface on the item at the specified index into the collection. void queryelementat( in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ); parameters index position of the item to be queried. uuid nsiidref of the item. ...
nsIContentSecurityPolicy
load-blocking and fail-closed are disabled: content security policy will only send reports, and not modify behavior. methods permitsancestry() verifies ancestry as permitted by the policy. calls to this may trigger violation reports when queried, so this value should not be cached. boolean permitsancestry( in nsidocshell docshell ); parameters docshell containing the protected resource. re
turn value true if the frame's ancestors are all permitted by policy. refinepolicy() updates the policy currently stored in the content security policy to be "refined" or tightened by the one specified in the string policystring. void refinepolicy( in astring policystring, in nsiuri selfuri ); parameters policystring selfuri scanrequestdata() called after the content security policy object is...
... is satisfied. calls to this may trigger violation reports when queried, so this value should not be cached. short shouldload( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetypeguess, in nsisupports aextra ); parameters acontenttype acontentlocation arequestorigin acontext amimetypeguess aextra re
turn value shouldprocess() delegate method called by the service when sub-elements of the protected document are being processed. given a bit of information about the request, decides whether or not the policy is satisfied. short shouldprocess( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetype, in nsisupport...
... are being processed. ...
nsICookiePermission
tests whether or not the given uri/channel may access the cookie database, either to set or get cookies. nscookieaccess canaccess( in nsiuri auri, in nsiuri afirsturi, obsolete since gecko 1.9 in nsichannel achannel ); parameters auri the uri trying to access cookies. afirsturi the uri initiated by the user that resulted in auri being loaded. achannel the channel corresponding to auri. re
turn value one of the nscookieaccess values: access_default, access_allow, or access_deny. cansetcookie() tests whether or not the given uri/channel may set a specific cookie. this method is always preceded by a call to canaccess(). it may modify the issession and expiry attributes of the cookie via the aissession and aexpiry parameters, in order to limit or extend the lifetime of the cookie. this is ...
... cookie being added to the cookie database. aissession when cansetcookie is invoked, this is the current issession attribute of the cookie. cansetcookie may leave this value unchanged to preserve this attribute of the cookie. aexpiry when cansetcookie is invoked, this is the current expiry time of the cookie. cansetcookie may leave this value unchanged to preserve this attribute of the cookie. re
turn value true if the cookie can be set. getoriginatinguri() determines the originating uri for a load given a channel, for third-party cookie blocking. this is done by leveraging the loadgroup of the channel to find the root content docshell, and the uri associated with its principal. if the root content docshell or its principal's uri cannot be obtained, this method will throw. nsiuri getoriginatin...
...l, for third-party cookie blocking. this is done by leveraging the loadgroup of the channel to find the root content docshell, and the uri associated with its principal. if the root content docshell or its principal's uri cannot be obtained, this method will throw. nsiuri getoriginatinguri( in nsichannel achannel ); parameters achannel the channel for the load trying to get or set cookies. re
turn value the originating uri. setaccess() sets cookie access permissions for the given uri. this may result in other uris being blocked as well, such as uris that share the same host name. void setaccess( in nsiuri auri, in nscookieaccess aaccess ); parameters auri the uri to block. aaccess the new cookie access permissions for the uri. see also nsicookie nsicookie2 nsicookiemanager nsicooki...
nsIDNSRecord
inherits from: nsisupports last changed in gecko 1.7 method overview prnetaddr getnextaddr(in pruint16 aport); native code only! acstring getnextaddrasstring(); boolean hasmore(); void rewind(); attributes attribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org. read only. ...
...ribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org. read only. methods native code only!getnextaddr this function copies the value of the next ip address into the given prnetaddr struct and increments the internal address iterator. prnetaddr getnextaddr( in pruint16 aport ); parameters aport a port number to initialize the prnetaddr with. ...
...heet.mozilla.org. read only. methods native code only!getnextaddr this function copies the value of the next ip address into the given prnetaddr struct and increments the internal address iterator. prnetaddr getnextaddr( in pruint16 aport ); parameters aport a port number to initialize the prnetaddr with. re
turn value the value of the next ip address. getnextaddrasstring() this function re
turns the value of the next ip address as a string and increments the internal address iterator. acstring getnextaddrasstring(); parameters none. re
turn value the value of the next ip address as a string. hasmore() this method checks if there is another address in the record. boolean hasmore(); parameters none. re
turn value true if there is another address in the record. rewind() this function reset...
nsIDOMStorage
mstring key); domstring key(in unsigned long index); void removeitem(in domstring key); void setitem(in domstring key, in domstring data); attributes attribute type description length unsigned long the number of keys stored in the session store. read only. methods clear() clear the content of this storage bound to a domain or an origin. void clear(); parameters none. getitem() re
turns from session storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be re
turned. re
turn value an nsidomstorageitem object describing the data corresponding to the specified key, or null if no data exists for the given key. key() re
turns the key for the item stored at the specified index in the data store. doms...
...exceptions thrown index_size_err there is no key at the specified index. removeitem() given a key, removes the corresponding entry from the session store. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. ...
...exceptions thrown index_size_err there is no key at the specified index. removeitem() given a key, removes the corresponding entry from the session store. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. ...
nsIDOMStorage2
ring key(in unsigned long index); void removeitem(in domstring key); void setitem(in domstring key, in domstring data); attributes attribute type description length unsigned long the number of keys stored in local storage. methods clear() clears the contents of this storage context; this removes all values bound to the domain or origin. void clear(); parameters none. getitem() re
turns from local storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be re
turned. re
turn value a string containing the data corresponding to the specified key, or null if no data exists for the given key. key() re
turns the key for the item stored at the specified index in the data store. domstring key( in unsign...
...exceptions thrown index_size_errthere is no key at the specified index. removeitem() given a key, removes the corresponding entry from local storage. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. ...
...exceptions thrown index_size_errthere is no key at the specified index. removeitem() given a key, removes the corresponding entry from local storage. void removeitem( in domstring key ); parameters key the key for which data should be removed from storage. ...
nsIDOMStorageManager
earofflineapps(); nsidomstorage getlocalstorageforprincipal(in nsiprincipal aprincipal, in domstring adocumenturi); long getusage(in astring aownerdomain); methods clearofflineapps() clears keys owned by offline applications. all data owned by a domain with the "offline-app" permission is removed from the database. void clearofflineapps(); parameters none. ...
...emoved from the database. void clearofflineapps(); parameters none. getlocalstorageforprincipal() re
turns the instance of the localstorage object for auri's origin. this is used to ensure that only one local storage area exists for a given origin. nsidomstorage getlocalstorageforprincipal( nsiprincipal aprincipal, domstring adocumenturi ); parameters aprincipal the principal for which to re
turn the local storage object. adocumenturi the document's uri. re
turn value the local storage object for the specified principal. getusage() re
turns the amount of disk space used by a domain. usage is checked against the domain of the page that set the key (the owner domain), not the domain of the storage object. long getusage( astring aownerdomain ); parameters aownerdomain the domain to check...
...local storage object. adocumenturi the document's uri. re
turn value the local storage object for the specified principal. getusage() re
turns the amount of disk space used by a domain. usage is checked against the domain of the page that set the key (the owner domain), not the domain of the storage object. long getusage( astring aownerdomain ); parameters aownerdomain the domain to check. ...
nsIDOMXPathEvaluator
sidomxpathexpression createexpression( in domstring expression, in nsidomxpathnsresolver resolver ); parameters expression a string representing the xpath to be created. resolver a name space resolver created by creatensresolver(), or a user defined name space resolver. read more on implementing a user defined namespace resolver if you wish to take the latter approach. re
turn value an xpath expression, as an nsidomxpathexpression object. creatensresolver() creates an nsidomxpathexpression which resolves name spaces with respect to the definitions in scope for a specified node. it is used to resolve prefixes within the xpath itself, so that they can be matched with the document. null is common for html documents or when no name space prefixes are used. nsidomxpathnsres...
...ct to the definitions in scope for a specified node. it is used to resolve prefixes within the xpath itself, so that they can be matched with the document. null is common for html documents or when no name space prefixes are used. nsidomxpathnsresolver creatensresolver( in nsidomnode noderesolver ); parameters noderesolver the node to be used as a context for name space resolution. re
turn value a name space resolver. evaluate() evaluate the specified xpath expression. nsisupports evaluate( in domstring expression, in nsidomnode contextnode, in nsidomxpathnsresolver resolver, in unsigned short type, in nsisupports result ); parameters expression a string representing the xpath to be evaluated. contextnode a dom node to evaluate the xpath expression again...
...er a name space resolver created by creatensresolver(), or a user defined name space resolver. read more on implementing a user defined namespace resolver if you wish to take the latter approach. type a number that corresponds to one of the type constants of nsixpathresult. result an existing nsixpathresult to use for the result. using null will create a new nsixpathresult. re
turn value an xpath result. see also introduction to using xpath in javascript document.evaluate dom level 3 xpath specification xml path language (xpath)rec nsidomxpathresult nsidomxpathexception ...
nsIDOMXPathResult
read only. invaliditeratorstate boolean true if the iterator state has become invalid. for example, modifying a node invalidates the iterator. read only. ...
... unsigned long if resulttype is unordered_node_snapshot_type or ordered_node_snapshot_type, the length of the snapshort array. read only. stringvalue domstring if resulttype is string_type, the boolean value. read only. constants type constants constant value description any_type 0 used when evaluating an xpath expression; the evaluator will re
turn the most appropriate type. number_type 1 type is a single number. string_type 2 type is a single string. boolean_type 3 type is a single boolean value. unordered_node_iterator_type 4 type is a reference to all the nodes matching the expression used in the evaluator. the nodes may not necessarily be in the same order that they appear in t...
...ly the first node in the document that matches the expression used in the evaluator. first_ordered_node_type 9 type is the first node in the document that matches the expression used in the evaluator. methods iteratenext() iterates through the available nodes of an unordered_node_iterator_type or ordered_node_iterator_type result. nsidomnode iteratenext(); parameters none. re
turn value a dom node. snapshotitem() re
turns the specified node from what is essentially an array of resulting dom nodes. is only available if the result type is unordered_node_snapshot_type or ordered_node_snapshot_type. nsidomnode snapshotitem( in unsigned long index ); parameters index the index of the dom node to re
turn. re
turn value a dom node. see also introduction to using xpath...
nsIDOMXULSelectControlElement
ring value); nsidomxulselectcontrolitemelement removeitemat(in long index); attributes attribute type description itemcount unsigned long read only. ...
...on itemcount unsigned long read only. ...
...e domstring methods appenditem() nsidomxulselectcontrolitemelement appenditem( in domstring label, in domstring value ); parameters label value re
turn value getindexofitem() long getindexofitem( in nsidomxulselectcontrolitemelement item ); parameters item re
turn value getitematindex() nsidomxulselectcontrolitemelement getitematindex( in long index ); parameters index re
turn value insertitemat() nsidomxulselectcontrolitemelement insertitemat( in long index, in domstring label, in domstring value ); parameters index label value re
turn value removeitemat() nsidomxulselectcontrolitemelement removeitemat( in long index ); parameters index re
turn value ...
nsIDictionary
2 count, [retval, array, size_is(count)] out string keys); nsisupports getvalue(in string key); void setvalue(in string key, in nsisupports value); nsisupports deletevalue(in string key); void clear(); methods haskey() check if a given key is present in the dictionary. boolean haskey( in string key ); parameters key key to check for. ...
...alue(in string key); void clear(); methods haskey() check if a given key is present in the dictionary. boolean haskey( in string key ); parameters key key to check for. re
turn value true if present, false if absent. getkeys() retrieve all keys in the dictionary. void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); re
turn value array of all keys, unsorted. getvalue() find the value indicated by the key. nsisupports getvalue( in string key ); parameters key the lookup key indicating the value. re
turn value the value associated with the specified key. if the key doesn't exist, ns_error_failure is re
turned. setvalue() add the key-value pair to the dictionary. if the key is already present, the new...
...already present, the new value replaces the old one. void setvalue( in string key, in nsisupports value ); parameters key the key by which the value can be accessed. value the value to store. deletevalue() find the value indicated by the key. nsisupports deletevalue( in string key ); parameters key the key indicating the pair to be removed. re
turn value the removed value. if the key doesn't exist, ns_error_failure will be re
turned. clear() delete all key-value pairs from the dictionary. void clear(); parameters none. ...
nsIEventListenerInfo
content/events/public/nsieventlistenerservice.idlscriptable an instance of this interface describes how an event listener was added to an event target; these are re
turned by nsieventlistenerservice.getlistenerinfofor, which provides a list of all the listeners to a given event target. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview nsisupports getdebugobject(); astring tosource(); attributes attribute type description allowsuntrusted boolean indicates whether or not the event listener allows untrusted events. read only. capturing boolean indicates whether or not the event listener is in capture m...
... allows untrusted events. read only. capturing boolean indicates whether or not the event listener is in capture mode. read only. insystemeventgroup boolean indicates whether or not the event listener is in the system event group. read only. type astring the type of the event for which the listener was added. read only. methods getdebugobject() re
turns the debugger object if the debug service is active. nsisupports getdebugobject(); parameters none. re
turn value if jsdidebuggerservice is active and the listener is implemented in js, this re
turns the listener as a jsdivalue. otherwise null. this is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly sl...
...icantly slows down script execution. accordingly, this should probably only be used by real debuggers. this approach is necessary because event listeners added with addeventlistener won't necessarily be nsieventlisteners; the dom code will fix up ordinary javascript functions to act as listeners. tosource() tries to serialize the event listener to a string. astring tosource(); parameters none. re
turn value re
turns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in c++). remarks nsieventlistenerinfo was introduced with bug 448602. see also nsieventlistenerservice nsieventtarget ...
nsIFileView
toolkit/components/filepicker/public/nsifileview.idlscriptable this interface displays a list of files in a treebox. inherits from: nsisupports last changed in gecko 1.7 note: nsifileview is linux-only interface. it's not included in windows or mac builds. note: a quirk of the nsifileview is that it requires an appropriate treecols section in the tree tag, by default fileview will re
turn the file size in the column. if the treecol id is "filenamecolumn" fileview will re
turn the file name, if the id is "lastmodifiedcolumn" it will re
turn the date of last modification. currently no other file stats are implemented. the nsifileview provides a configuration interface to @mozilla.org/filepicker/fileview;1 , which also implements nsitreeview so that it can be passed as a tree view. imp...
...t sorttype, in boolean reversesort); attributes attribute type description reversesort boolean if true results will be sorted in ascending order. read only. selectedfiles nsiarray an nsiarray of selected files, which contains nsiarray instances. read only. showhiddenfiles boolean if true hidden files will be shown. showonlydirectories boolean if true only directory entries will be re
turned. sorttype short the current sort type in effect. read only. constants constant value description sortname 0 sort by file name. sortsize 1 sort by file size. sortdate 2 sort by the date of the last modification. methods setdirectory() set the directory to be browsed. void setdirectory( in nsifile directory ); parameters directory the directory to be browsed. setfilter() set...
... constant value description sortname 0 sort by file name. sortsize 1 sort by file size. sortdate 2 sort by the date of the last modification. methods setdirectory() set the directory to be browsed. void setdirectory( in nsifile directory ); parameters directory the directory to be browsed. setfilter() set the filter to be applied to the file list, for example "*.jpg" would only re
turn jpg files. void setfilter( in astring filterstring ); parameters filterstring the filter to be applied to the file list. sort() set the method used for sorting. void sort( in short sorttype, in boolean reversesort ); parameters sorttype one of the sort* constants. reversesort true, results will be sorted in ascending order. example <?xml version="1.0" ?> <?xml-stylesheet href="chrome:...
nsIHttpChannelInternal
read only. channelisfordownload boolean external handlers may set this to true to notify the channel that it is open on behalf of a download. documenturi nsiuri an http channel can own a reference to the document uri. forceallowthirdpartycookie boolean force relevant cookies to be sent with this load even if normally they would not be. ...
..._error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. methods getrequestversion() gets the request's major and minor version numbers. ...
...endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. methods getrequestversion() gets the request's major and minor version numbers. void getrequestversion( out unsigned long major, out unsigned long minor ); parameters major on re
turn, contains the request's major version number. minor on re
turn, contains the request's minor version number. getresponseversion() gets the response's major and minor version numbers. void getresponseversion( out unsigned long major, out unsigned long minor ); parameters major on re
turn, contains the response's major version number. minor on re
turn, contains the response's minor version number. httpupgrade() allows for the use of http to bootstrap ano...
nsILoginInfo
he password for the login. passwordfield astring the name attribute for the password input in a form. non-form logins should specify an empty string (""). username astring the username for the login. usernamefield astring the name attribute for the username input in a form. non-form logins should specify an empty string (""). ...
...tribute for the password input in a form. non-form logins should specify an empty string (""). username astring the username for the login. usernamefield astring the name attribute for the username input in a form. non-form logins should specify an empty string (""). methods clone() re
turns a clone of this login. nsilogininfo clone(); parameters none. re
turn value an nsilogininfo containing a clone of the login on which this method was invoked. equals() tests to determine whether this login is exactly equal to another nsilogininfo object. boolean equals( in nsilogininfo alogininfo ); parameters alogininfo the login to which to compare for equality. re
turn value true if the two logins are exactly equal or false if they're not. init() ...
...one login's formsubmiturl is an empty string (but not null), it will be treated as a wildcard. a blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsilogininfo alogininfo, in boolean ignorepassword ); parameters alogininfo the login to which to compare for equality. ignorepassword if true, do not examine the password value when matching. re
turn value true if the two logins are equivilant or false if they're not. see also nsiloginmanager using nsiloginmanager ...
nsILoginManagerCrypto
encrypt(in astring plaintext); attributes attribute type description isloggedin boolean current login state of the token used for encryption. if the user is not logged in, performing a crypto operation will result in a master password prompt. read only. uibusy boolean true when a master password prompt is being displayed. read only. ...
...note: the current implemention of this inferface simply uses nss/psm's "secret decoder ring" service. it is not recommended for general purpose encryption/decryption. ...
...fied string, re
turning the plain text value. can throw if the user cancels entry of their master password, or if the ciphertext value can not be successfully decrypted (for example, if it was encrypted with some other key). astring decrypt( in astring ciphertext ); parameters ciphertext the string to be decrypted. re
turn value the decrypted string. encrypt() encrypts the specified string, re
turning the ciphertext value. note: the current implemention of this inferface simply uses nss/psm's "secret decoder ring" service. it is not recommended for general purpose encryption/decryption. can throw if the user cancels entry of their master password. astring encrypt( in astring plaintext ); parameters plaintext the string to be encrypted. re
turn value the encrypted string. ...
nsIMemoryReporterManager
not covered by memory reporters. this reporter is special-cased because it is interesting, and is moderately difficult to compute in javascript. -1 means unknown. read only. resident print64 gets the resident size (that is rss, physical memory used). ...
... to compute in javascript. -1 means unknown. read only. resident print64 gets the resident size (that is rss, physical memory used). this reporter is special-cased because it is interesting, is available on all platforms, and re
turns a meaningful result on all common platforms. -1 means unknown. read only. methods enumeratemultireporters() re
turns an enumerator for looking at the installed memory multi-reporters. ...
...is rss, physical memory used). this reporter is special-cased because it is interesting, is available on all platforms, and re
turns a meaningful result on all common platforms. -1 means unknown. read only. methods enumeratemultireporters() re
turns an enumerator for looking at the installed memory multi-reporters. nsisimpleenumerator enumeratemultireporters(); parameters none. re
turn value an enumerator of nsimemorymultireporters that are currently registered. enumeratereporters() re
turns an enumerator for looking at the installed memory reporters. nsisimpleenumerator enumeratereporters(); parameters none. re
turn value an nsisimpleenumerator for enumerating installed memory reporters. init() initializes the memory reporter manager. void init(); parameters none. registermult...
nsIMicrosummaryGenerator
estriction being that the uri be globally unique. to ensure this, we recommend that such extensions incorporate uuids created by nsiuuidgenerator into the urns of the generators they create. methods calculateupdateinterval() calculates the interval until the microsummary should be updated for the next time, depending on the page content. if the generator doesn't specify an interval, null is re
turned. long calculateupdateinterval( in nsidomnode apagecontent ); parameters apagecontent the content of the page being summarized. re
turn value the interval in milliseconds until the next update request. equals() microsummary-generator equivalence test. generators are considered equal if their canonical locations (uri attribute) are equal. boolean equals( in nsimicrosummarygenerator aother )...
...generatemicrosummary() generate a microsummary by processing the generator template against the page content. if a generator doesn't need content, pass null as the parameter to this method. note: in the future, this may be expanded to support rich text content. ...
...ual. generatemicrosummary() generate a microsummary by processing the generator template against the page content. if a generator doesn't need content, pass null as the parameter to this method. note: in the future, this may be expanded to support rich text content. astring generatemicrosummary( in nsidomnode apagecontent ); parameters apagecontent the content of the page being summarized. re
turn value the text result of processing the template. see also microsummary topics creating a microsummary ...
nsIMimeConverter
y native code, as xpconnect translation causes it to not work properly. string encodemimepartiistr(in string header, in boolean structured, in string mailcharset, in long fieldnamelen, in long encodedwordsize); parameters propertyname the name of the property to retrieve. re
turn value the value of the property. encodemimepartiistr_utf8() encodes a string into a mime-encoded form according to rfc 2047. string encodemimepartiistr_utf8(in autf8string header, in boolean structured, in string mailcharset, in long fieldnamelen, in ...
...the encoded string. decodemimeheadertocharptr() void setstringproperty(in string propertyname, in string propertyvalue); parameters propertyname the name of the property to set. propertyvalue the value of the property. decodemimeheader() string getstringproperty(in string propertyname); parameters propertyname the name of the property to retrieve. re
turn value the value of the property. b64encoderinit() get an integer property. usually you would use this to store you own properties. unsigned long getuint32property(in string propertyname); parameters propertyname the name of the property to retrieve. thunderbird stored uint32 properties (not a complete list): indexed used for spotlight integration on osx. notaphishmessage indi...
...rty. usually you would use this to store you own properties. unsigned long getuint32property(in string propertyname); parameters propertyname the name of the property to retrieve. thunderbird stored uint32 properties (not a complete list): indexed used for spotlight integration on osx. notaphishmessage indicates whether phisihing filters have been run on a message yet. re
turn value the value of the property. qpencoderinit() void setuint32property(in string propertyname, in unsigned long propertyval); parameters propertyname the name of the property to set. propertyval the value of the property. encoderdestroy() marks this header as read. thunderbird provides a utility function which performs this for the currently selected messag...
nsINavHistoryResultViewObserver
indicated row. drop_after 1 the drag operation wishes to insert the dragged item after the indicated row. methods candrop() implement this method to report whether or not a drop is permitted onto the specified location. ...
...ondrop() called when the user drops something onto the view being observed. void ondrop( in long row, in long orientation ); parameters row the row at which the drop occurred. ...
...ondrop() called when the user drops something onto the view being observed. void ondrop( in long row, in long orientation ); parameters row the row at which the drop occurred. ...
nsIParserUtils
gremovals (1 << 6) flag for sanitizer: log messages to the console for everything that gets sanitized. methods converttoplaintext() converts html to plain text. astring converttoplaintext( in astring src, in unsigned long flags, in unsigned long wrapcol ); parameters src the html source to parse (c++ callers are allowed but not required to use the same string for the re
turn value.) flags conversion option flags defined in nsidocumentencoder. wrapcol number of characters per line; 0 for no auto-wrapping. re
turn value the plain text conversion of the html specified in src. parsefragment() parses markup into a sanitized document fragment. nsidomdocumentfragment parsefragment( in astring fragment, in unsigned long flags, in boolean isxml, in nsiuri bas...
...tfragment parsefragment( in astring fragment, in unsigned long flags, in boolean isxml, in nsiuri baseuri, in nsidomelement element ); parameters fragment the input markup. flags sanitization option flags defined above. isxml true if |fragment| is xml and false if html. baseuri the base url for this fragment. element the context node for the fragment parsing algorithm. re
turn value an nsidomdocumentfragment object for the resulting sanitized document fragment. sanitize() parses a string into an html document, sanitizes the document, and re
turns the result serialized to a string. the sanitizer is designed to protect against xss when sanitized content is inserted into a different-origin context without an iframe-equivalent sandboxing mechanism. by default, the sani...
...ffect. note: if -moz-binding is not present, <style> elements and style attributes, and if sanitizerallowstyle is specified, the sanitized content may still be xss dangerous if loaded into a non-gecko web engine! astring sanitize( in astring src, in unsigned long flags ); parameters src the html source to parse (c++ callers are allowed but not required to use the same string for the re
turn value). flags sanitization option flags defined above. re
turn value the resulting text. ...
nsIPlacesView
d only. place string theuri (as a string) of the root place that the view displays. this may be modified dynamically to update the view. see displaying places information using views for examples. selectednode nsinavhistoryresultnode the selected node in the view. if there are multiple selected nodes, this is null. read only. methods getdragableselection() re
turns an array of selected nsinavhistoryresultnode objects that can be dragged from the view. nsinavhistoryresultnode[] getdragableselection(); parameters none. re
turn value an array of nsinavhistoryresultnode objects. getremovableselectionranges() re
turns an array whose elements are themselves arrays of nsinavhistoryresultnode objects that can be removed from the view. each inner array repres...
...(); parameters none. re
turn value an array of nsinavhistoryresultnode objects. getremovableselectionranges() re
turns an array whose elements are themselves arrays of nsinavhistoryresultnode objects that can be removed from the view. each inner array represents a contiguous range of nodes that can be removed. nsinavhistoryresultnode[][] getremovableselectionranges(); parameters none. re
turn value an array of arrays of nsinavhistoryresultnode objects. getresult() re
turns the nsinavhistoryresult object that the view displays. nsinavhistoryresult getresult(); parameters none. re
turn value the nsinavhistoryresult object that the view displays. getresultnode() re
turns the root node, an nsinavhistorycontainerresultnode object, of the view's result. nsinavhistorycontainerresult...
...esultnode objects. getresult() re
turns the nsinavhistoryresult object that the view displays. nsinavhistoryresult getresult(); parameters none. re
turn value the nsinavhistoryresult object that the view displays. getresultnode() re
turns the root node, an nsinavhistorycontainerresultnode object, of the view's result. nsinavhistorycontainerresultnode getresultnode(); paramters none. re
turn value the root nsinavhistorycontainerresultnode of the view's result. getselectionnodes() re
turns an array of all currently selected nsinavhistoryresultnode objects of the view. the nodes are not necessarily re
turned in the same order in which they occur in the model, or in the same container, or from the same provider. nsinavhistoryresultnode[] getselectionnodes(); parameters none. retur...
nsIPrefService
refroot); void readuserprefs(in nsifile afile); void resetprefs(); void resetuserprefs(); void savepreffile(in nsifile afile); methods getbranch() call to get a preferences "branch" which accesses user preference data. using a set method on this object will always create or set a user preference value. when using a get method a user set value will be re
turned if one exists, otherwise a default value will be re
turned. nsiprefbranch getbranch( in string aprefroot ); parameters aprefroot the preference root tree on which to base this branch. for example, if the root browser.startup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply r...
...froot the preference root tree on which to base this branch. for example, if the root browser.startup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, or homepage_override. nsnull or "" (empty string) may be used to access to the entire preference tree. re
turn value nsiprefbranch - the object representing the requested branch. getdefaultbranch() call to get a preferences branch which accesses only the default preference data. using a set method on this object will always create or set a default preference value. when using a get method a default value will always be re
turned. note: few consumers will want to create default branch objects. many of t...
...froot the preference root tree on which to base this branch. for example, if the root browser.startup. is used, the branch will be able to easily access the preferences browser.startup.page, browser.startup.homepage, and browser.startup.homepage_override by simply requesting page, homepage, or homepage_override. nsnull or "" (empty string) may be used to access to the entire preference tree. re
turn value nsiprefbranch - the object representing the requested default branch. readuserprefs() called to read in the preferences specified in a user preference file. note: if nsnull is passed in for the afile parameter the default preferences file(s) [prefs.js, user.js] will be read and processed. void readuserprefs( in nsifile afile ); parameters afile the file to be read. resetprefs...
nsIProcess
this is only valid after the process has exited. read only. isrunning boolean true if the process is running, otherwise false. only accurate if the process was run with blocking disabled. read only. location nsifile the location of the executable file on disk. read only. gecko 1.9.1 note this attribute is no longer implemen...
...iately terminates the process represented by the nsiprocess object. this only works if the process was run without blocking enabled. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method did not work on windows or mac os x. now it does. void kill(); parameters none. run() starts executing the process. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method re
turned the process id of the newly executing process. it no longer re
turns a value. void run( 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 re
turns immediately. args an array of count arguments, using the native character set, to be passed to t...
...rver will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. runw() executes the file this object was initialized with. 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 re
turns 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 c...
nsIProtocolHandler
flag. uri_loadable_by_subsumers 1<<14 the uris for this protocol can be loaded only by callers 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_re
turn_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not re
turn 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 n...
... most protocols, port 25 (simple mail transfer protocol) is banned. when a uri containing this port number is encountered, this method is called to ask if the protocol handler wants to override the ban. boolean allowport( in long port, in string scheme ); parameters port the port for which an override is being requested. scheme the scheme for which an override is being requested. re
turn value re
turn true if the override is approved; otherwise, re
turn false. newchannel() constructs a new channel from the given uri for this protocol handler. nsichannel newchannel( in nsiuri auri ); parameters auri the uri for which to construct a channel. re
turn value re
turn the newly constructed channel. newuri() makes a uri object that is suitable for loading by this protocol, w...
... character set that should be used when communicating this uri to an origin server. if this is null, then utf-8 encoding is assumed and no character transformation is not performed. abaseuri if null, aspec must specify an absolute uri. otherwise, aspec may be resolved relative to abaseuri, depending on the protocol. if the protocol has no concept of relative uris, this parameter is ignored. re
turn value the new uri object suitable for loading using the protocol. see also nsiproxiedprotocolhandler adding a new protocol to mozilla writing a firefox protocol handler custom about: urls - similar to adding new protocol but adding onto the existing about: protocol ...
nsIPushSubscription
endpoint domstring the subscription url. pushcount long long the total number of messages sent to this subscription. lastpush long long the last time a message was sent to this subscription, in milliseconds since the epoch. quota long the number of remaining background messages for this subscription, or -1 if exempt. methods getkey() re
turns a byte array containing the key material for this subscription. the remote server can use these keys to encrypt and authenticate message payloads. the following key names are supported: p256dh the ecdh public key, used as the input keying material in the hkdf invocation during encryption. auth the shared authentication secret, used as the salt in the hkdf invocation. ...
... void getkey( in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key ); parameters name the encryption key name. keylen the keying material length. key the byte array containing the keying material. keylen and key are out parameters. when called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and re
turns key. please see method parameters in xpidl for more details on using out parameters in javascript. quotaapplies() indicates whether this subscription is subject to the background message quota. bool quotaapplies(); nsipushsubscription.quotaapplies() always re
turns false for system subscriptions. parameters none. isexpired() indicates whether this subscription has expired and must be ...
... parameters none. ...
nsIRadioInterfaceLayer
ameters cid missing description reason missing description exceptions thrown missing exception missing description dial() functionality for making and managing phone calls. ...
...number of sms needed. ...
...number of sms needed. ...
nsIScrollable
till possible. scrollbar_always 3 scrollbars always visible, even when scrolling is not possible. methods getcurscrollpos() obsolete since gecko 29.0 (firefox 29.0 / thunderbird 29.0 / seamonkey 2.26) long getcurscrollpos( in long scrollorientation ); parameters scrollorientation an integer representing the orientation of the scrollbar. re
turn value getdefaultscrollbarpreferences() long getdefaultscrollbarpreferences( in long scrollorientation ); parameters scrollorientation an integer representing the orientation of the scrollbar. re
turn value an integer representing the state of the scrollbar. getscrollbarvisibility() void getscrollbarvisibility( out boolean verticalvisible, out boolean horizontalvisible ); paramet...
...horizontal scroll range. minverticalpos an integer representing the minimal position of the vertical scroll range. ...
...resenting the minimal position of the vertical scroll range. ...
nsIServerSocket
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...
...ner to be notified when client connections are accepted. close() this method closes a server socket. this does not affect already connected client sockets (i.e., the nsisockettransport instances created from this server socket). this will cause the onstoplistening event to asynchronously fire with a status of ns_binding_aborted. void close(); parameters none. native code only!getaddress re
turns 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. in the case of an ip socket, the ip address field would be zeroed out to indicate a server socket bound to all network devices. therefore, this method cannot be used to determine the ip address of the local sys...
...vices, this address may not necessarily be specific to a single network device. in the case of an ip socket, the ip address field would be zeroed out to indicate a server socket bound to all network devices. therefore, this method cannot be used to determine the ip address of the local system. see nsidnsservice.myhostname() if this is what you need. prnetaddr getaddress(); parameters none. re
turn value the network address to which the socket is bound. init() initializes a server socket. void init( in long aport, in boolean aloopbackonly, in long abacklog ); parameters aport the port of the server socket. pass -1 to indicate no preference, and a port will be selected automatically. aloopbackonly if true, the server socket will only respond to connections on the local loop...
nsIStreamConverter
gecko 1.7 suppose you had code that converted 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. ...
... stream converter suppliers registering a stream converter: stream converter registration is a two step process. ...
...eam of one type, to a stream of another type. use this method when you have a stream you want to convert. nsiinputstream convert( in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt ); parameters afromstream the stream representing the original/raw data. afromtype the mime type of afromstream. atotype the mime type of the re
turned stream. actxt either an opaque context, or a converter specific context (implementation specific). re
turn value the converted stream. note: the re
turned stream may not already be converted. an efficient stream converter implementation will converter data on demand rather than buffering the converted data until it is used. ...
nsIStringBundleService
undle createextensiblebundle(in string aregistrykey); void flushbundles(); wstring formatstatusmessage(in nsresult astatus, in wstring astatusarg); methods createbundle() nsistringbundle createbundle( in string aurlspec ); parameters aurlspec the url of the properties file to load. this is typically a locale url, e.g. chrome://global/locale/global.properties re
turn value a string bundle corresponding to the properties file. this string bundle has functions available on it. on the re
turn value object on you can call functions like getstringfromname and formatstringfromname see nsistringbundle. createextensiblebundle() nsistringbundle createextensiblebundle( in string aregistrykey ); parameters aregistrykey the name of the category under whic...
... flushbundles() flushes the string bundle cache - useful when the locale changes or when we need to get some extra memory back. ...
...t a message received by a nsiprogresseventsink's onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsierrorservice). astatusarg the status message argument(s). multiple arguments can be separated by newline ('\n') characters. re
turn value the formatted message. see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. the localizing js/jsm files uses the nsistringbundleservice: bootstrapped extensions :: localization (l10n) nsistringbundle ...
nsISyncMessageSender
nal] in nsiprincipal principal); jsval sendrpcmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); sendsyncmessage() like sendasyncmessage(), except blocks the sender until all listeners of the message have been invoked. re
turns an array containing re
turn 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 to listeners. throws ns_error_not_initialized if the sender is not initialized. for example,...
...ject. the message payload. a structured clone of this becomes the data property of the received message. objects object. an object each of whose properties is an object. this becomes the objects property of the received message, with each original object replaced with a cross process object wrapper for it. principal nsiprincipal re
turns array: an array of structured clones of the objects re
turned by all the listeners to this message, one element for each listener. if there was only one listener, it is an array with a single element. sendrpcmessage() like sendsyncmessage(), except re-entrant. new rpc messages may be issued even if, earlier on the call stack, we are waiting for a reply to an earlier sendrpcmessage() call. paramet...
...ject. the message payload. a structured clone of this becomes the data property of the received message. objects object. an object each of whose properties is an object. this becomes the objects property of the received message, with each original object replaced with a cross process object wrapper for it. principal nsiprincipal re
turns array: an array of structured clones of the objects re
turned by all the listeners to this message, one element for each listener. if there was only one listener, it is an array with a single element. ...
nsITaggingService
en uri are ignored. void untaguri( in nsiuri auri, in nsivariant atags ); parameters auri the url to un-tag. atags array of tags to unset. pass null to remove all tags from the given uri. geturisfortag() this method retrieves all uris tagged with the given tag. nsivariant geturisfortag( in astring atag ); parameters atag the tag name. ...
...nored. void untaguri( in nsiuri auri, in nsivariant atags ); parameters auri the url to un-tag. atags array of tags to unset. pass null to remove all tags from the given uri. geturisfortag() this method retrieves all uris tagged with the given tag. nsivariant geturisfortag( in astring atag ); parameters atag the tag name. ...
...turisfortag( in astring atag ); parameters atag the tag name. re
turn value re
turns array of uris tagged with atag. gettagsforuri() this method retrieves all tags set for the given uri. nsivariant gettagsforuri( in nsiuri auri, [optional] out unsigned long length, [retval, array, size_is(length)] out wstring atags ); parameters auri the uri for which to re
turn the tags. length optional on re
turn, contains the number of tags re
turned in atags. this optional parameter was required prior to gecko 2.0. atags on re
turn, contains an array of tags for the specified uri. re
turn value re
turns array of tags (sorted by name). see also places using the places tagging service ...
nsITaskbarPreviewController
a surface with the controller's width and height, the values of which are obtained immediately prior to calling this method. boolean drawpreview( in nsidomcanvasrenderingcontext2d ctx ); parameters ctx an nsidomcanvasrenderingcontext2d object representing the drawing context into which the preview is to be rendered. note that this context is not actually attached to a canvas element. re
turn value true if you want a frame drawn around the preview, otherwise false. drawthumbnail() invoked by the taskbar preview when it needs to draw the thumbnail in the taskbar's application preview window. boolean drawthumbnail( in nsidomcanvasrenderingcontext2d ctx, in unsigned long width, in unsigned long height ); parameters ctx an nsidomcanvasrenderingcontext2d object representing...
...ject representing the drawing context into which the thumbnail is to be rendered. note that this context is not actually attached to a canvas element. width the width of the surface backing the drawing context. height the height of the surface backing the drawing context. note: it's guaranteed that width ÷ height will equal the thumbnailaspectratio, within the margin of rounding errors. re
turn value true if you want a frame drawn around the thumbnail, otherwise false. onactivate() invoked when the user clicks on the tab preview. boolean onactivate(); parameters none. re
turn value true if the top level window corresponding to the preview should be activated, false if activation is not accepted. onclick() invoked when one of the buttons on the window preview's toolbar is click...
...the top level window corresponding to the preview should be activated, false if activation is not accepted. onclick() invoked when one of the buttons on the window preview's toolbar is clicked by the user. void onclick( in nsitaskbarpreviewbutton button ); parameters button an nsitaskbarpreviewbutton object representing the button that was pressed. this can be compared to the buttons re
turned by the nsitaskbarwindowpreview.getbutton(). onclose() invoked when the user presses the close button on the tab preview. void onclose(); parameters none. see also nsitaskbarpreview nsitaskbartabpreview nsitaskbarwindowpreview nsitaskbarpreviewbutton nsiwintaskbar ...
nsIThread
ion before the thread joins with the current thread (see pr_jointhread() for details). during the execution of this method call, events for the current thread may continue to be processed. warning: this method may not be called from the thread itself. instead, you must only call it from another thread (usually the thread that created it, or the main application thread). when this function re
turns, the thread will be shut down and will no longer be available to receive events. void shutdown() parameters none. exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down. haspendingevents() ...
...f, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down. haspendingevents() determines whether or not the thread has events that are ready to be processed. note: this method must be called from within the thread itself, and not from another thread. boolean haspendingevents() parameters none. re
turn value true if there are pending events at the time the function was called. since other threads may add events to the current thread, it's possible that by the time this method re
turns, the event queue may no longer be empty, even if a false result is reported. exceptions thrown ns_error_unexpected the method was called when this thread wasn't the current thread. processnextevent() proce...
...hat 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 re
turns immediately if the queue is empty. re
turn value re
turns true if an event was processed, or false if there were no pending events. exceptions thrown ns_error_unexpected this method was called when this thread wasn't the current thread. see also the thread manager nsithreadmanager nsithreadpool nsithreadinternal nsithreadobserver nsithreadeventfilter ...
nsITransaction
sient boolean the transaction's transient state. this attribute is checked by the transaction manager after the transaction's execute() method is called. if the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undotransaction() and redotransaction() methods can be called. if the transient state is true, the transaction manager re
turns immediately after the transaction's dotransaction() method is called, no references to the transaction are maintained. transient transactions cannot be undone or redone by the transaction manager. read only. methods dotransaction() executes the transaction. void dotransaction(); parameters none. merge() attempts to merge a transaction into "this" transaction. both transactions must be in the...
...nager. read only. methods dotransaction() executes the transaction. void dotransaction(); parameters none. merge() attempts to merge a transaction into "this" transaction. both transactions must be in their undo state, dotransaction() methods already called. the transaction manager calls this method to coalesce a new transaction with the transaction on the top of the undo stack. this method re
turns a boolean value that indicates the merge result. a true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. if true, the transaction manager will release() the new transaction instead of pushing it on the undo stack. boolean merge( in nsitransaction atransaction ); parameters atransaction the previously executed transaction t...
...value that indicates the merge result. a true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. if true, the transaction manager will release() the new transaction instead of pushing it on the undo stack. boolean merge( in nsitransaction atransaction ); parameters atransaction the previously executed transaction to merge. re
turn value missing description redotransaction() executes the transaction again. can only be called on a transaction that was previously undone. in most cases, the redotransaction method will actually call the dotransaction() method to execute the transaction again. void redotransaction(); parameters none. undotransaction() restores the state to what it was before the transaction was executed. void u...
nsITreeSelection
index, in long count ); parameters index index of the change. count number of rows changed. clearrange() clears the range. void clearrange( in long startindex, in long endindex ); parameters startindex index to clearing at. endindex index to stop clearing at. clearselection() clears the selection. void clearselection(); parameters none. getrangeat() re
turns two objects whose value properties represent the minimum and maximum indices of the given selection range. see the tree selection tutorial. void getrangeat( in long i, out long min, out long max ); parameters i index of range to get (0 <= i < getrangecount()) min index of first object in range. max index of last object in this range. for single selections, ...
...represent the minimum and maximum indices of the given selection range. see the tree selection tutorial. void getrangeat( in long i, out long min, out long max ); parameters i index of range to get (0 <= i < getrangecount()) min index of first object in range. max index of last object in this range. for single selections, min == max. getrangecount() re
turns a count of selection ranges. long getrangecount(); parameters none. re
turn value long - number of selection ranges invalidateselection() can be used to invalidate the selection. void invalidateselection(); parameters none. invertselection() inverts the selection. void invertselection(); parameters none. isselected() indicates whether or not the row at the specified index is part of the select...
...selection ranges invalidateselection() can be used to invalidate the selection. void invalidateselection(); parameters none. invertselection() inverts the selection. void invertselection(); parameters none. isselected() indicates whether or not the row at the specified index is part of the selection. boolean isselected( in long index ); parameters index index of the row to check. re
turn value rangedselect() select the range specified by the indices. void rangedselect( in long startindex, in long endindex, in boolean augment ); parameters startindex index to start selecting at. endindex index to stop selecting at. this parameter is inclusive; to select one item, set endindex == startindex. augment if true, the range is added to the selection witho...
nsIUTF8ConverterService
is article. inherits from: nsisupports last changed in gecko 1.7 method overview autf8string convertstringtoutf8(in acstring astring, in string acharset, in boolean askipcheck); autf8string converturispectoutf8(in acstring aspec, in string acharset); methods convertstringtoutf8() ensure that astring is encoded in utf-8. if not, convert to utf-8 assuming it's encoded in acharset and re
turn the converted string in utf-8. autf8string convertstringtoutf8( in acstring astring, in string acharset, in boolean askipcheck, in boolean aallowsubstitution ); parameters astring a string to ensure its utf8ness. acharset the charset to convert from if astring is not in utf-8. askipcheck determines whether or not to skip 'asciiness' and 'utf8nes...
...n ascii / utf-8 so that astring has to go through the conversion. skipping asciiness/utf8ness check. the most common case is the input is in 7bit non-ascii character sets like iso-2022-jp, hz or utf-7 (in its original form or a modified form used in imap folder names). aallowsubstitution when true, allow the decoder to substitute invalid input sequences by replacement characters. re
turn value the converted string in utf-8. exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and re
turn the result. make sure that all character...
...l-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and re
turn the result. make sure that all characters outside us-ascii in your input spec are url-escaped if your spec is not in utf-8 (before url-escaping) because the presence of non-ascii characters is blindly regarded as an indication that your input spec is in unescaped utf-8 and it will be re
turned without further processing. no valid spec going around in mozilla code would break this assumption. autf8string converturispectoutf8( in acstring aspec, in string acharset ); parameters aspec an url-escaped uri spec to ensure its utf8ness. acharset the character set to convert from if aspec is not in utf-8. re
turn value the converted spec in utf-8. exceptions thrown ns_error_uconv_nocon...
nsIUTF8StringEnumerator
xpcom/ds/nsistringenumerator.idlscriptable an object can implement this interface to allow a client to iterate over a set of strings provided by the object. inherits from: nsisupports last changed in gecko 1.7 method overview autf8string getnext(); boolean hasmore(); methods getnext() re
turns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which re
turns pr_true. ...
... gecko 1.7 method overview autf8string getnext(); boolean hasmore(); methods getnext() re
turns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which re
turns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. autf8string getnext(); parameters none. re
turn value the next string in the enumerator. throws an exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be re
turned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getnext() calls. calling this method doesn't affect...
...more strings. hasmore() reports whether or not the enumerator has any strings that can be re
turned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getnext() calls. calling this method doesn't affect the internal state of the enumerator. boolean hasmore(); parameters none. re
turn value true if there are remaining strings in the enumerator, otherwise false. ...
nsIWebNavigationInfo
;1 as a service: var webnavigationinfo = components.classes["@mozilla.org/webnavigation-info;1"] .getservice(components.interfaces.nsiwebnavigationinfo); method overview unsigned long istypesupported(in acstring atype, in nsiwebnavigation awebnav); constants support type constants constant value description unsupported 0 re
turned by istypesupported() to indicate lack of support for a type. note: this is guaranteed not to change, so that boolean tests can be done on the re
turn value if istypesupported to detect whether a type is supported at all. image 1 re
turned by istypesupported() to indicate that a type is supported as an image. plugin 2 re
turned by istypesupported() to indicate that...
...anteed not to change, so that boolean tests can be done on the re
turn value if istypesupported to detect whether a type is supported at all. image 1 re
turned by istypesupported() to indicate that a type is supported as an image. plugin 2 re
turned by istypesupported() to indicate that a type is supported via an npapi ("netscape 4 api") plug-in. this is not the value re
turned for "xpcom plug-ins". other 1 << 15 note: other re
turn types may be added here in the future as they become relevant. re
turned by istypesupported() to indicate that a type is supported via some other means. methods istypesupported() determines whether or not the specified mime type is supported by the given nsiwebnavigation object. this lets you determine whether a...
...av ); parameters atype the mime type to check. awebnav the nsiwebnavigation object on which to check for compatibility. you may specify null to check for compatibility with nsiwebnavigation objects that are in their default state; otherwise, the result is determined based on the configuration of the specified object (that is, how it is configured by using nsiwebbrowsersetup). re
turn value re
turns one of the support type constants, indicating whether or not the specified mime type is supported, and in what form that support exists. example let webnavigationinfo_service = components.classes["@mozilla.org/webnavigation-info;1"] .getservice(components.interfaces.nsiwebnavigationinfo); let support_code = webnavigationinfo_service.istypesupported(co...
nsIXSLTProcessor
urce); nsidomdocumentfragment transformtofragment(in nsidomnode source, in nsidomdocument output); methods clearparameters() removes all set parameters from this nsixsltprocessor. this will make the processor use the default-value for all parameters as specified in the stylesheet. void clearparameters(); parameters none. getparameter() gets a parameter if previously set by setparameter(). re
turns null otherwise. nsivariant getparameter( in domstring namespaceuri, in domstring localname ); parameters namespaceuri the namespaceuri of the xslt parameter. localname the local name of the xslt parameter. re
turn value an nsivariant containing the value of the parameter. importstylesheet() imports the specified stylesheet into this xsltprocessor for transformations. void importstylesheet(...
... in nsivariant value ); parameters namespaceuri the namespaceuri of the xslt parameter. localname the local name of the xslt parameter. value the new value of the xslt parameter. transformtodocument() transforms the node source applying the stylesheet imported by importstylesheet(). nsidomdocument transformtodocument( in nsidomnode source ); parameters source the node to be transformed. re
turn value an document containing the result of the transformation. transformtofragment() transforms the node source applying the stylesheet imported by importstylesheet(). the created fragment will be owned by the specified output document. nsidomdocumentfragment transformtofragment( in nsidomnode source, in nsidomdocument output ); parameters source the node to be transformed. output the docum...
...t containing the result of the transformation. transformtofragment() transforms the node source applying the stylesheet imported by importstylesheet(). the created fragment will be owned by the specified output document. nsidomdocumentfragment transformtofragment( in nsidomnode source, in nsidomdocument output ); parameters source the node to be transformed. output the document to own the re
turned document fragment. re
turn value a documentfragment containing the resulting transform. ...
nsIXULTemplateBuilder
bindings for a result has changed. in this case, the rules are not reapplied as it is expected that the same rule will still apply. the builder will resynchronize any variables that are referenced in the action body. void resultbindingchanged( in nsixultemplateresult aresult ); parameters aresult the result to change errors throws ns_error_null_pointer if aresult is null getresultforid() re
turns the result for a given id. only one such result is re
turned and is always the result with that id associated with the active match. this method will re
turn null is there is no result for the id. nsixultemplateresult getresultforid( in astring aid ); parameters aid the id to re
turn the result for re
turn value the result for the given id. getresultforcontent() retrieves the result correspondin...
...hasgeneratedcontent() determines whether or not the node has content generated for it. this method is intended to be called only by the rdf query processor. if atag is set, the content must have a tag name that matches atag. ...
...ether or not the node has content generated for it. this method is intended to be called only by the rdf query processor. if atag is set, the content must have a tag name that matches atag. atag may be ignored for builders that don't generate real dom content. boolean hasgeneratedcontent( in nsirdfresource anode, in nsiatom atag ); parameters anode node to check. atag tag that must match. re
turn value re
turns true if the node has content generated for it; otherwise re
turns false. addrulefilter() adds a rule filter for a given rule, which may be used for specialized rule filtering. any existing filter on the rule is removed. the default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out result...
nsIZipReaderCache
if the zip reader for the given file is no...
...ipentry); obsolete since gecko 10 nsizipreader getzip(in nsifile zipfile); void init(in unsigned long cachesize); methods getinnerzip() re
turns a (possibly shared) cached nsizipreader for a zip inside another zip. nsizipreader getinnerzip( in nsifile zipfile, in autf8string zipentry ); parameters zipfile the zip file. zipentry the zip entry. re
turn value the nsizipreader for the given zip file. getzip() re
turns a (possibly shared) cached nsizipreader for a zip file. if the zip reader for the given file is not in the cache, a new nsizipreader is opened (see nsizipreader.open()). ...
...n autf8string zipentry ); parameters zipfile the zip file. zipentry the zip entry. re
turn value the nsizipreader for the given zip file. getzip() re
turns a (possibly shared) cached nsizipreader for a zip file. if the zip reader for the given file is not in the cache, a new nsizipreader is opened (see nsizipreader.open()). otherwise the previously created nsizipreader is re
turned. note: if nsizipreader.close has been called on the shared nsizipreader, this method will re
turn the closed nsizipreader nsizipreader getzip( in nsifile zipfile ); parameters zipfile the zip file. re
turn value the nsizipreader for the given zip file. init() initializes a new zip reader cache. void init( in unsigned long cachesize ); parameters cachesize the number of re...
NS ENSURE TRUE
summary macro re
turns re
turn-value if expr evaluates to false. syntax ns_ensure_true( expr, re
turn-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo = new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) re
turn ns_error_out_of_memory; // thou shalt not re
turn ns_error_failure.. ...
...lue if expr evaluates to false. syntax ns_ensure_true( expr, re
turn-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo = new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) re
turn ns_error_out_of_memory; // thou shalt not re
turn ns_error_failure.. ...
...::mozstringmucking() { char *foo = new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) re
turn ns_error_out_of_memory; // thou shalt not re
turn ns_error_failure.. ...
NS_CStringCopy
api reference summary the ns_cstringcopy function copies the value from one nsacstring instance to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_cstringcopy( nsacstring& adeststring, const nsacstring& asrcstring ); parameters adeststring [in] a nsacstring instance to be modified. asrcstring [in] a nsacstring instance containing the new string value. re
turn values the ns_cstringcopy function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacs...
...see bug 239123 for details. ...
...is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { re
turn ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsacstring& avalue) { re
turn ns_cstringcopy(mvalue, avalue); } history this function was frozen in mozilla 1.7. see bug 239123 for details. see also nsacstring ...
NS_CStringGetMutableData
ummary the ns_cstringgetmutabledata function gives the caller write access to the string's internal buffer. #include "nsstringapi.h" pruint32 ns_cstringgetmutabledata( nsacstring& astring, pruint32 adatalength, char** adata ); parameters astring [in] a nsacstring instance to modify. adatalength [in] the number of characters to resize the string's internal buffer to or pr_uint32_max to re
turn the buffer as-is. adata [out] upon re
turn, if the function was successful, then *adata references the string's internal buffer. re
turn values this function re
turns the number of characters contained in the string's internal buffer (excluding any null-terminator). this value will be zero if the function failed to resize its internal buffer to the size requested. remarks this function provides mut...
...this function does not necessarily null-terminate astring's internal buffer after resizing it. ...
...this function does not necessarily null-terminate astring's internal buffer after resizing it. that behavior depends on the implementation of astring. if astring is a reference to a nscstringcontainer, then its data will be null-terminated by this function. ...
NS_StringCopy
api reference summary the ns_stringcopy function copies the value from one nsastring instance to another. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcopy( nsastring& adeststring, const nsastring& asrcstring ); parameters adeststring [in] a nsastring instance to be modified. asrcstring [in] a nsastring instance containing the new string value. re
turn values the ns_stringcopy function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalu...
...see bug 239123 for details. ...
...ow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { re
turn ns_stringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsastring& avalue) { re
turn ns_stringcopy(mvalue, avalue); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsastring ...
Frequently Asked Questions
nly need the |nsifoo| interface for a short time // so i control its lifetime by declaring it inside // a block statement. ...
...hich i don't need an |nsifoo| re
turn rv; } editors note: move this discussion to the efficiency section, and link to it from here. make an nscomptr leak (for a debug test)? call a getter that uses a raw xpcom interface pointer as an `in/out' parameter? call a getter that fills in an nsifoo*& parameter? call a getter that doesn't addref its result? ...
... in an nsifoo*& parameter? call a getter that doesn't addref its result? any xpcom function that re
turns an interface pointer, i.e., a `getter', must have already addrefed that pointer. if it didn't, you should probably report it as a bug. no matter which code pattern you use to solve this problem, you should comment it, e.g., // warning: this getter doesn't addref() its result. if the getter re
turns the new pointer as its function result, no worries, general does nscomptr bloat the code? are nscomptrs fast? can i use them in tight loops? bibliography web resources nscomptr.h, and nscomptr.cpp are the source to nscomptr. you can examine the source to nscomptr online using (the wonderful) lxr. exploring this code is not an adventure for the faint of heart. some com ownership guidelin...
Using nsIDirectoryService
this document. bear in mind that this list is not static. components can add and remove locations at their will. second, you must acquire the implementation and call get() passing the known string key. in the example below, prop is a string that references your requested file locations. ...
...at can provide an nsifile. to do this, you must get the implementation again like above. when you have it, queryinterface for the nsidirectoryservice interface. apart from this interface there is a function, registerprovider which will allow you to register a nsidirectoryserviceprovider, which implements the getfile callback function: var provider = { getfile : function(prop, persistant) { // re
turn an nsifile }, } components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryservice).registerprovider(provider); when the callback is called, it will be passed the string key, and should re
turn an nsifile. the persistant flag allows you to specify if you want the nsdirectoryservice to cache this value. in most cases you would set this to be true.
...even before registering components. if you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its initialize method - it will register itself. again, if you do this, do not initialize the profile service - it's either one or the other. related pages code_snippets:file_i/o original document information authors: conrad carlen, doug
turner last updated date: september 26, 2000 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Weak reference
... nsresult addobserver( nsiobserver* ); nsresult notifyobservers( nsimessage* ); // ... private: nsweakptr mobserver; // ...or imagine a list of observers here }; // ... nsresult nsobservable::addobserver( nsiobserver* aobserver ) { mobserver = getter_addrefs( ns_getweakreference(aobserver) ); // ...or append this to the list of observers re
turn ns_ok; } nsresult nsobservable::notifyobservers( nsimessage* amessage ) { nscomptr<nsiobserver> observer = do_queryreferent(mobserver); if ( observer ) observer->noticemessage(amessage); else mobserver = 0; // or remove this observer from the list, he's gone away re
turn ns_ok; } // ... it's key to note that an nsweakptr has exactly the same interface a...
...these requirements is that every call to queryinterface against the same (aggragate) object for the same interface must yield the same result, no matter what interface pointer you call it through, and no matter when you call it. this is impossible in our situation, since we explicitly rely on the the fact that part of the `aggregate' can be destroyed. subsequent attempts to reach that part must re
turn nsnull. sometimes our queryinterface through the weak pointer would re
turn a pointer to the `real' interface, and sometimes it would re
turn nsnull. we just broke com. it's clear, therefore, that the weak reference can't be aggregated to the target object. hence, we can't use queryinterface to move between them. i know this sounds more convenient, but the global routine ns_getweakreference makes ...
...ns_getweakreference makes it easy to go from the target object to the weak reference; and nsiweakreference::queryreferent gives you the same functionality as queryinterface for getting back. additionally, nscomptr now supports the new key do_queryreferent to simplify life even further. how do i make a class support weak references? in javascript, just make sure that your queryinterface method re
turns your object for the nsisupportsweakreference interface, and you're set; xpconnect does all the work for you. just roll in nssupportsweakreference, a mix-in class that does all the work, and adjust your queryinterface accordingly, e.g., //... #include "nsweakreference.h" class nsfoo : public nsifoo, ..., public nssupportsweakreference { ... }; // ...if you used the table macros to implement ...
pyxpidl
the newer utility has the advantage of not needing any code to be compiled in order to use it, and let us remove a bunch of old code from the tree. pyxpidl has been in use for a while, but replaced xpidl in the gecko sdk starting in gecko 9.0. using pyxpidl pyxpidl is in the sdk in the sdkdir/sdk/bin/ directory. unlike xpidl, which combined all the functions into a single utility, pyxpidl is comprised of two utilities: header.py, which generates c++ headers from idl, and typelib.py, which generates xpt files. ...
...rating typelibs generating typelib files is done using the typelib.py utility: sdkdir/sdk/bin/typelib.py --cachedir=<path> -o <outputfilename.xpt> <filename.idl> comparing pyxpidl to xpidl this table provides a mapping of old xpidl options to pyxpidl. ...
...pelib.py utility: sdkdir/sdk/bin/typelib.py --cachedir=<path> -o <outputfilename.xpt> <filename.idl> comparing pyxpidl to xpidl this table provides a mapping of old xpidl options to pyxpidl. ...
Folders and message lists
folder interface contains many methods and attributes for working with folders. to get the nsimsgfolder instance for the currently-displayed folder, just use gfolderdisplay.displayedfolder. getting the currently-selected message the folderdisplaywidget has several ways of getting the currently-selected message(s), depending on what exactly you're trying to do: gfolderdisplay.selectedcount: re
turns the number of messages currently selected. gfolderdisplay.selectedmessage: re
turns the first currently-selected message. when using this, be sure that there's only one selected message (or that you only care about the first one). otherwise, use one of the methods described below. gfolderdisplay.selectedmessages: re
turns an array of nsimsgdbhdrs for the selected messages. if a collapsed thread ...
...like selectedmessages, this also includes messages in selected collapsed threads when so enabled. ...
...rayofmsghdrs. like selectmessage, this function will attempt to scroll the view so the entire selection is visible (which may not be possible for large selections). gfolderdisplay.clearselection(): clears the list of selected messages. listing messages in a folder if you have a message folder, and would like to list all the messages in that folder, you can use the .messages attribute, which re
turns an nsisimpleenumerator. it's used like this: // import the fixiterator() function. components.utils.import("resource:///modules/iteratorutils.jsm"); for (let msghdr in fixiterator(myfolder.messages, components.interfaces.nsimsgdbhdr)) { // do something with msghdr... } ...
Declaring types
each type you declare using js-ctypes corresponds to a compatible c declaration. types are declared in terms of other, already defined types. at the core of all this is a set of predefined types provided by js-ctypes. these are all primitive types, upon which all other types are eventually based. primitive types primitive types are those types that represent a single value in memory, as opposed to arrays, structures, or functions. ...
... { "tm_year": ctypes.int }, { "tm_wday": ctypes.int }, { "tm_yday": ctypes.int }, { "tm_isdst": ctypes.int } ]); to find other types see here: predefined types - primitive types. you can then declare and use a function that uses this structure, like this: // declare the libc asctime() function, which re
turns a char * and accepts a pointer to a tm structure. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); var thetime = new struct_tm; thetime.tm_hour = 3; thetime.tm_min = 15; ... var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last lin...
...ointer to a tm structure. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); var thetime = new struct_tm; thetime.tm_hour = 3; thetime.tm_min = 15; ... var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last line converts the c string re
turned by the libc asctime() function into a javascript string by calling the cdata readstring() method. for another example see here: getcursorpos opaque structures an opaque structure is one whose content fields are not known, or are not intended to be accessed directly. they can also be used to handle forward declarations, by declaring a structure as opaque if it needs to include a structure tha...
Working with ArrayBuffers
. this feature is based on the following work: //github.com/realityripple/uxp/blob/master/js/src/ctypes/ctypes.cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas. this example is based on the fact that the imagedata re
turned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer. the following codeblock provides a basic example of getting and setting uint8clampedarray and arraybuffer of imagedata: // context is a canvasrenderingcontext2d of some canvas var imagedata = context.getimagedata(x, y, w, h); var array = imagedata.data; // array is a uint8clampedarray var buffer = image...
... pixels). method 3: transfer byte array by calling memcpy this is the recommended method, as it only takes a couple of milliseconds, even for large arrays. notice that the following example does not cast the pixelbuffer. passing an arraybuffer object to pointer type will pass the pointer to buffer (based on //github.com/realityripple/uxp/blob/master/js/src/ctypes/ctypes.cpp#3080). further, it re
turns datapointer, and there is no extra allocation (based on //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301). var lib; switch (os.constants.sys.name.tolowercase()) { case 'winnt': case 'winmo': case 'winnt': //windows lib = ctypes.open('msvcrt'); break; case 'darwin': // mac lib = ctypes.open('libc.dylib'); break; c...
... ctypes.open(ctypes.libraryname('c')); } catch (ex) { throw new error('i dont know where to memcpy is defined on your operating system, "' + os.constants.sys.name + '"'); lib.close(); } } try { var memcpy = lib.declare('memcpy', os.constants.sys.name.tolowercase().indexof('win') == 0 ? ...
Mozilla
pchannel::opencacheentry(). all top level document loading (navigation) channels are set chooseapplicationcache flag, which happens in nsdocshell::douriload(). channels having that flag set are searching for nsiapplicationcache object prior inspecting normal http cache. nsiapplicationcacheservice::chooseapplicationcache is given the url the channel is about to load. it synchronously re
turns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace. benchmarking debug builds (--enable-debug) and non-optimized builds (--disable-optimize) are much slower. any performance metrics gathered by such builds are largely unrelat...
... displaying places information using views views are one component of the places model-view-controller design. use them to display nsinavhistoryresult objects to the user. see querying places for information about obtaining and using nsinavhistoryresult objects, which this page assumes you are familiar with. error codes re
turned by mozilla apis the following tables list errors that can occur when calling various mozilla apis. each error is listed by its name and an error code in parentheses. an error will typically be displayed on the error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for example, by u...
...document describes how an embedder or other gecko/necko-using application can implement download resuming. implementing queryinterface this document describes the right way to write queryinterface(). infallible memory allocation there's ongoing work to implement infallible memory allocators. these are memory allocation routines that never re
turn null; that is, they always successfully re
turn the requested block of memory. this is in contrast to a traditional, fallible memory allocator that can re
turn null indicating that the request failed. integrated authentication this entails support for the the simple and protected gss-api negotia...
Initialization and Destruction - Plugins
tance->pdata. nperror npp_destroy(npp instance, npsaveddata **save); the instance parameter represents the plug-in instance to delete. the plug-in can use the optional save parameter to save data for reuse by a new instance with the same url. the data is passed to npp_new through its saved parameter. for example, a video player could save the last frame number to be displayed. when the user re
turns to the page, the previous frame number is passed to the new instance of the plug-in, so it can initially display the same frame. note that you cannot count on data being saved this way; the data may be lost if the browser restarts or purges memory. ownership of the buf field of the npsaveddata structure passes from the plug-in to the browser when npp_destroy re
turns. the example in this sectio...
...initialize and shutdown example. initialize and shutdown example this example demonstrates the use of the np_initialize and np_shutdown methods. /* define global variable to hold the user agent string. */ static char* useragent = null; /* initialize function. */ nperror np_initialize(void) { /* get the user agent from the browser. */ char* result = npn_useragent(); if (result == null) re
turn nperr_out_of_memory_error; /* allocate some memory so that you can keep a copy of it. */ useragent = (char*) npn_memalloc(strlen(result) + 1); if (useragent == null) re
turn nperr_out_of_memory_error; /* copy the string to your memory. */ strcpy(useragent, result); re
turn nperr_no_error; } /* shutdown function */ nperror np_shutdown(void) { /* delete the memory you allocated. */ ...
...that you can keep a copy of it. */ useragent = (char*) npn_memalloc(strlen(result) + 1); if (useragent == null) re
turn nperr_out_of_memory_error; /* copy the string to your memory. */ strcpy(useragent, result); re
turn nperr_no_error; } /* shutdown function */ nperror np_shutdown(void) { /* delete the memory you allocated. ...
Memory - Plugins
loc automatically frees cached information if necessary to fulfill a request for memory, calls to npn_memalloc may succeed where direct calls to newptr fail. the npn_memalloc method has the following syntax: void *npn_memalloc (uint32 size); the size parameter is an unsigned long integer that represents the amount of memory, in bytes, to allocate in the browser's memory space. this function re
turns a pointer to the allocated memory or null if not enough memory is available. the npn_memfree method deallocates a block of memory that was allocated using npn_memalloc only. npn_memfree does not free memory allocated by other means. void npn_memfree (void *ptr); the ptr parameter represents a block of memory previously allocated using npn_memalloc. flushing memory (mac os only) the npn_mem...
...npn_memflush only when it is not possible to call npn_memalloc, for example, when calling system methods that allocate memory indirectly. if npn_memalloc is called, calls to npn_memflush have no effect. for example, suppose that the plug-in calls newgworld, and that the call fails because of insufficient memory. the plug-in should try calling npn_memflush to free enough memory. if npn_memflush re
turns a value indicating that enough memory was freed, the plug-in can call newgworld again. calling npn_memflush is particularly important to systems with small amounts of ram and with virtual memory
turned off. to request that the browser free as much memory as possible, call npn_memflush repeatedly until it re
turns 0. uint32 npn_memflush (uint32 size); the size parameter is an unsigned long int...
...h is particularly important to systems with small amounts of ram and with virtual memory
turned off. to request that the browser free as much memory as possible, call npn_memflush repeatedly until it re
turns 0. uint32 npn_memflush (uint32 size); the size parameter is an unsigned long integer that represents the amount of memory, in bytes, to free in the browser's memory space. this function re
turns the amount of freed memory, in bytes, or 0 if no memory could be freed. « previousnext » ...
Set a breakpoint - Firefox Developer Tools
ditional breakpoint using the context menu (see above), or by highlighting the line you want to break at in the source pane and pressing ctrl + shift + b (windows/linux) or cmd + shift + b (macos). when you first choose to set a conditional breakpoint, a text entry line will appear into which you add the condition you want it to break on: once you've entered your condition and pressed enter/re
turn, the line number will be highlighted in orange: breakpoints list once you've set some breakpoints, the breakpoints list in the right-hand column shows the filename and line number for each one: unsetting a breakpoint once a breakpoint has been set, you can unset it again in various ways: click on the line number highlight. highlight the line of code the breakpoint is set on and pressi...
...eakpoint once a breakpoint has been set, you can unset it again in various ways: click on the line number highlight. highlight the line of code the breakpoint is set on and pressing ctrl + b (windows/linux) or cmd + b (macos). bring up the context menu over the line highlight and choose the remove breakpoint option. other context menu options worth mentioning are: disable breakpoint:
turn it off, but don't remove it completely. disable breakpoints on line and remove breakpoints on line: remove or disable column breakpoints. if the breakpoint is an unconditional breakpoint, you'll get an option add condition, which allows you to
turn it into a conditional breakpoint. if the breakpoint is a conditional breakpoint, you'll get an option edit condition, which allows you to change th...
...ver when stepping through your code. previously you’d have to scroll through the scopes panel to find variable values, or hover over a variable in the source pane. now when execution pauses, you can view relevant variables immediately. note: there is also a new option in the context menu for the actual code in the source pane — hide inline preview/show inline preview — which allows you to
turn the inline variables on/off. ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
s) { for(;;) { if (!totals.has(site)) totals.set(site, 0); totals.set(site, totals.get(site) + count); if (!site) break; site = site.parent; } } // compute parent-to-child links, since saved stack frames // have only parent links. var rootchildren = new map; function childmapfor(site) { if (!site) re
turn rootchildren; let parentmap = childmapfor(site.parent); if (parentmap.has(site)) re
turn parentmap.get(site); var m = new map; parentmap.set(site, m); re
turn m; } for (let [site, total] of totals) { childmapfor(site); } // print the allocation count for |site|. print // |children|'s entries as |site|'s child nodes. indent // th...
...tils is not defined, be sure you've selected browser from the scratchpad's environment menu, as described in step 2.) save the following html text to a file, and visit the file in your browser. make sure the current browser tab is displaying this page. <div onclick="dodivsandspans()"> click here to make the page do some allocations. ...
... save the following html text to a file, and visit the file in your browser. make sure the current browser tab is displaying this page. <div onclick="dodivsandspans()"> click here to make the page do some allocations. ...
Index - Firefox Developer Tools
m of the source pane. the debugger formats the source and displays it as a new file with a name like: "{ } [original-name]". 127 search to search for a particular file, press control + p (or command + p on a mac) and type the search term. the source pane will display a list of all matching files as you type. you can use the up and down arrows to move through the list, and re
turn to open the file you want: 128 set a breakpoint javascript, tools, breakpoint, column breakpoint, conditional breakpoint there are many different types of breakpoint that can be set in the debugger; this article covers standard (unconditional) breakpoints and conditional breakpoints. 129 set a conditional breakpoint conditional, debugger, debugging, devtools, d...
...eaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. 130 set watch expressions when debugging code, sometimes it's useful to watch expressions as executions are paused. the debugger features a pane for entering expressions to be watched (watch expressions). as you step through code, the debugger will watch the expression and re
turn any results. 131 step through code debugger, devtools, javascript, step through code when the debugger is stopped at a breakpoint, you can step through it using four buttons in the toolbar: 132 use a source map the javascript sources executed by the browser are often transformed in some way from the original sources created by a developer. for example: ...
...logpoints print a message to the console panel instead of pausing code execution. 135 set an xhr breakpoint debugger, debugging, javascript, xhr breakpoint an xhr (xmlhttprequest) breakpoint breaks code execution when an xhr request is dispatched so that you can examine the current state of the program. you can break on all requests or on those that include a specific url. to
turn on the feature: 136 set event listener breakpoints debugger, dev tools, event debugging, event handler, event listener, javascript debugging, tools, breakpoint, events starting with firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automatically break when the code hits an event handler. this artic...
Network request list - Firefox Developer Tools
the column to the left of it to fit its contents. the reset columns command on the context menu also resets the width of the columns to the default values. clicking the column header label sorts the request list by that column. you can reset the sort to the default by selecting "reset sorting" from the context menu. here is a list of all available columns: status: the http status code re
turned. the numeric code is displayed on a colored background, to help unusual ones stand out. if there was no response, this column is empty. or you might see a red circle with a diagonal slash for responses that were blocked by the browser or the server. method: the http request method used. domain: domain of the path requested. if the request used ssl/tls and the connection had security we...
... block requests matching patterns you specify. click the request blocking icon in the toolbar. this opens the blocking sidebar. (click the icon again when you want to close the sidebar.) enter a string in the field with the placeholder text block resource when url contains. reload the page to test it with the specified url blocked. other actions you can take with request blocking: to
turn all request blocking off or on: toggle the checkbox next to enable request blocking. to
turn a specific block off or on: toggle the checkbox next to that item. to delete a blocked item, click the x icon that appears when you focus the item. (starting with firefox 77) right-click any item in the list and choose from the context menu: enable all enables blocking of all items in the list. ...
...o find all 404, not found, errors, you can type "404" into the search and auto-complete suggests "status-code:404" so you'll end up with something like this: search in requests use the search panel to run a full-text search on headers and content. click the search icon in the toolbar. this opens the search sidebar. enter a string in the search field of the sidebar, and press enter or re
turn. the search results area below the search field displays the requests that contain that string in the request or response headers or in the content of the response. you can expand each item to show the specific item that matches the string. clicking an item in the search results highlights that item in the monitor list, and displays the corresponding information in the request details pane. ...
Intensive JavaScript - Firefox Developer Tools
using requestanimationframe in the first attempt at fixing this, we'll split up the function into a number of m...
...to keep inside its frame budget. ...
...the code that actually performs the computations is exactly the same as the original code. so how does this version perform? switch the radio button to "use a worker", and capture a new profile. you should see something like this: in this profile we pushed the button...
Waterfall - Firefox Developer Tools
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() ...
... call stack at the point the promise was made. for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("ready!"); } function runtimer(t) { re
turn new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mark an instant in the recording. to make a timestamp marker, call console.timestamp(). you can pass an argument to label the timestamp.
...= 0) { console.timestamp(i.tostring()); } var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } console.timeend("calculating..."); re
turn primes; } in the waterfall you'll now see something like this: ...
Animation - Web APIs
stance. properties animation.currenttime the current time value of the animation in milliseconds, whether running or paused. if the animation lacks a timeline, is inactive or hasn't been played yet, its value is null. animation.effect gets and sets the animationeffectreadonly associated with this animation. this will usually be a keyframeeffect object. ...
...e a keyframeeffect object. animation.finished read only re
turns 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 re
turns 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 re
turns the current ready promise for this animation. animation.replacestate re
turns the replace state of the animation. this will be active if the animation has been replaced, or persisted if animation.persist() has bee...
...tion.commitstyles() for commiting the end styling state of an animation to the element being animated, even after that animation has been removed. animation.onremove for setting and running an event handler that fires when the animation is removed (i.e., put into an active replace state). animation.persist() for when you explicitly want an animations to be retained. animation.replacestate to re
turn the replace state of the animation. this will be active if the animation has been removed, or persisted if persist() has been invoked. accessibility concerns blinking and flashing animation can be problematic for people with cognitive concerns such as attention deficit hyperactivity disorder (adhd). additionally, certain kinds of motion can be a trigger for vestibular disorders, epilepsy, and ...
AnimationEffect.getComputedTiming() - Web APIs
the getcomputedtiming() method of the animationeffect interface re
turns the calculated timing properties for this animation effect. although many of the attributes of the re
turned object are common to the effecttiming contained in the object re
turned by the animationeffect.gettiming() method, the values re
turned by this object differ in the following ways: duration re
turns the calculated value of the iteration duration. if effecttiming.duration is the string auto, this attribute will re
turn 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element re
turned using window.getcomputedstyle(elem). ...
...lculated value of the iteration duration. if effecttiming.duration is the string auto, this attribute will re
turn 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element re
turned using window.getcomputedstyle(elem). syntax var currenttimevalues = animation.getcomputedtiming(); parameters none. re
turn value a computedeffecttiming dictionary object, which contains the following properties: endtime the end time of the animation in milliseconds from the animation's start (if the keyframeeffect is associated with an animation). (also includes effecttiming.enddelay in that calculation.) activeduration the length of time in milliseconds that the animation's effects will run. this is equal to ...
... length of time in milliseconds that the animation's effects will run. this is equal to the iteration duration multiplied by the iteration count. localtime the current time of the animation in milliseconds. if the keyframeeffect is not associated with an animation, its value is null. progress indicates how far along the animation is through its current iteration with values between 0 and 1. re
turns null if the animation is not running or its keyframeeffect isn't associated with an animation. currentiteration the number of times this animation has looped, starting from 0. re
turns null if the animation is not running or its keyframeeffect isn't associated with an animation. specifications specification status comment web animationsthe definition of 'animationeffe...
AudioBuffer - Web APIs
s implementing the mediaelementaudiosourcenode are more suitable. the buffer contains data in the following format: non-interleaved ieee754 32-bit linear pcm with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. if the audiobuffer has multiple channels, they are stored in separate buffer. ...
...the following format: non-interleaved ieee754 32-bit linear pcm with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. if the audiobuffer has multiple channels, they are stored in separate buffer. constructor audiobuffer() creates and re
turns a new audiobuffer object instance. properties audiobuffer.samplerate read only re
turns a float representing the sample rate, in samples per second, of the pcm data stored in the buffer. audiobuffer.length read only re
turns an integer representing the length, in sample-frames, of the pcm data stored in the buffer. audiobuffer.duration read only re
turns a double representing the duration, in seconds, of the pcm data stored in the buffer. audiobuffer.numberofchannels read only...
...loat representing the sample rate, in samples per second, of the pcm data stored in the buffer. audiobuffer.length read only re
turns an integer representing the length, in sample-frames, of the pcm data stored in the buffer. audiobuffer.duration read only re
turns a double representing the duration, in seconds, of the pcm data stored in the buffer. audiobuffer.numberofchannels read only re
turns an integer representing the number of discrete audio channels described by the pcm data stored in the buffer. methods audiobuffer.getchanneldata() re
turns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel). audiobuffer.copyfromchannel() copies the samples from the specified channel of the audiobuffe...
AudioParam.value - Web APIs
syntax var curvalue = audioparam.value; audioparam.value = newvalue; value a floating-point number indicating the parameter's value as of the current time. ...
...nsider this example: const source = new audiobuffersourcenode(...); const rate = 5.3; source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863. one solution is to use the math.fround() method, which re
turns the single-precision value equivalent to the 64-bit javascript value specified—when setting value, like this: const source = new audiobuffersourcenode(...); const rate = math.fround(5.3); source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); in this case, the log output will be true. value of a property which is changing over time the value of an audioparam can...
... setting value, like this: const source = new audiobuffersourcenode(...); const rate = math.fround(5.3); source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); in this case, the log output will be true. value of a property which is changing over time the value of an audioparam can either be fixed or can vary over time. this is reflected by the value getter, which re
turns the value of the parameter as of the audio rendering engine's most recent render quantum, or moment at which audio buffers are processed and updated. in addition to processing audio buffers, each render quantum updates the value of each audioparam as needed given the current time and any established time-based parameter value changes. upon first creating the parameter, its value is set to its d...
AudioParamDescriptor - Web APIs
properties name the domstring which represents the name of the audioparam. ...
...and register it. note that this should be done in a separate file. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
... (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ? parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) re
turn true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audiowork...
AudioTrack.language - Web APIs
for tracks that include multiple languages (such as a movie in english in which a few lines are spoken in other languages), this should be the video's primary language. syntax var audiotracklanguage = audiotrack.language; value a domstring specifying the bcp 47 (rfc 5646) format language tag of the primary language used in the audio track, or an empty string ("") if the language is not specified or known, or if the track doesn't contain speech. for example, if the primary language used in the track is united states english, this value would be "en-us". for brazilian portuguese, the value would be "pt-br". ...
... in the audio track, or an empty string ("") if the language is not specified or known, or if the track doesn't contain speech. for example, if the primary language used in the track is united states english, this value would be "en-us". for brazilian portuguese, the value would be "pt-br". example this example locates all of a media element's primary language and translated audio tracks and re
turns a list of objects containing each of those tracks' id, kind, and language. this could then be used to build a user interface for selecting the language the user would like to listen to while watching a movie, for example. function getavailablelanguages(el) { var tracklist = []; const wantedkinds = [ "main", "translation" ]; el.audiotracks.foreach(function(track) { if (wantedk...
...user would like to listen to while watching a movie, for example. function getavailablelanguages(el) { var tracklist = []; const wantedkinds = [ "main", "translation" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, language: track.language }); } }); re
turn tracklist; } specifications specification status comment html living standardthe definition of 'audiotrack.language' in that specification. living standard html5the definition of 'audiotrack.language' in that specification. recommendation ...
AudioWorkletGlobalScope - Web APIs
has a single audioworklet available under the audioworklet property, which runs its code in a single audioworkletglobalscope. as the global execution context is shared across the current baseaudiocontext, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining audioworkletprocessor-derived classes. properties currentframe read only re
turns an integer that represents the ever-increasing current sample-frame of the audio block being processed. it is incremented by 128 (the size of a render quantum) after the processing of each audio block. currenttime read only re
turns a double that represents the ever-increasing context time of the audio block being processed. it is equal to the currenttime property of the baseaudiocontext the w...
... methods registerprocessor() registers a class derived from the audioworkletprocessor interface. ...
...ssor { constructor () { super() // current sample-frame and time at the moment of instantiation // to see values change, you can put these two lines in process method console.log(currentframe) console.log(currenttime) } // the process method is required - simply output silence, // which the outputs are already filled with process (inputs, outputs, parameters) { re
turn true } } // the sample rate is not going to change ever, // because it's a read-only property of a baseaudiocontext // and is set only during its instantiation console.log(samplerate) // you can declare any variables and use them in your processors // for example it may be an arraybuffer with a wavetable const usefulvariable = 42 console.log(usefulvariable) registerprocessor('test-processor'...
AudioWorkletNode.parameters - Web APIs
they are instantiated during creation of the underlying audioworkletprocessor according to its parameterdescriptors static getter. syntax audioworkletnodeinstance.parameters value the audioparammap object containing audioparam instances. they can be automated in the same way as with default audionodes, and their calculated values can be used in the process method of your audioworkletprocessor. examples to demonstrate creation and usage of custom audioparams, we'll expand the example from audioworkletnode page. ...
...and register it. note that this should be done in a separate file. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
... (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ? parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) re
turn true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audiowork...
AudioWorkletNode - Web APIs
ned audionode, which can be connected to an audio routing graph along with other nodes. it has an associated audioworkletprocessor, which does the actual audio processing in a web audio rendering thread. constructor audioworkletnode() creates a new instance of an audioworkletnode object. properties also inherits properties from its parent, audionode. audioworkletnode.port read only re
turns a messageport used for bidirectional communication between the node and its associated audioworkletprocessor. the other end is available under the port property of the processor. audioworkletnode.parameters read only re
turns an audioparammap — a collection of audioparam objects. they are instantiated during the creation of the underlying audioworkletprocessor. if the audioworkletprocessor h...
...with this mechanism it is possible to make your own audioparam objects accessible from your audioworkletnode. ...
...ich will output white noise, and register it. note that this should be done in a separate file. // white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) re
turn true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkl...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
the property is not a part of the audioworkletprocessor interface, but, if defined, it is called internally by the audioworkletprocessor constructor to create a list of custom audioparam objects in the parameters property of the associated audioworkletnode. defining the getter is optional. syntax audioworkletprocessorsubclass.parameterdescriptors; value an iterable of audioparamdescriptor-based objects. ...
...and register it. note that this should be done in a separate file. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
... (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ? parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) re
turn true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audiowork...
BeforeUnloadEvent - Web APIs
when no value is provided, the event is processed silently. some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
...onaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeunloadevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} bubbles no cancelable yes target objects defaultview interface event examples window.addeventlistener("beforeunload", function( event ) { event.re
turnvalue = "\o/"; }); // is equivalent to window.addeventlistener("beforeunload", function( event ) { event.preventdefault(); }); webkit-derived browsers don't follow the spec for the dialog box. an almost-cross-browser working example would be close to the below example. window.addeventlistener("beforeunload", function (e) { var confirmationmessage = "\o/"; (e || window.event).re
turnvalue ...
...w.addeventlistener("beforeunload", function( event ) { event.preventdefault(); }); webkit-derived browsers don't follow the spec for the dialog box. an almost-cross-browser working example would be close to the below example. window.addeventlistener("beforeunload", function (e) { var confirmationmessage = "\o/"; (e || window.event).re
turnvalue = confirmationmessage; // gecko + ie re
turn confirmationmessage; /* safari, chrome, and other * webkit-derived browsers */ }); specifications specification status comment html living standardthe definition of 'beforeunloadevent' in that specification. living standard initial definition ...
Blob.slice() - Web APIs
end optional an index into the blob indicating the first byte that will *not* be included in the new blob (i.e. ...
...tenttype); parameters start optional an index into the blob indicating the first byte to include in the new blob. if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is 0. if you specify a value for start that is larger than the size of the source blob, the re
turned blob has size 0 and contains no data. end optional an index into the blob indicating the first byte that will *not* be included in the new blob (i.e. the byte exactly at this index is not included). if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is size. ...
... the byte exactly at this index is not included). if you specify a negative value, it's treated as an offset from the end of the blob toward the beginning. for example, -10 would be the 10th from last byte in the blob. the default value is size. contenttype optional the content type to assign to the new blob; this will be the value of its type property. the default value is an empty string. re
turn value a new blob object containing the specified subset of the data contained within the blob on which this method was called. the original blob is not altered. specifications specification status comment file apithe definition of 'blob.slice()' in that specification. working draft initial definition ...
BlobBuilder - Web APIs
ppend( in blob data ); void append( in string data, [optional] in string endings ); parameters data the data to append to the blob being constructed. endings specifies how strings containing \n are to be written out. this can be "transparent" (endings unchanged) or "native" (endings changed to match host os filesystem convention). the default value is "transparent". ...
...tten out. this can be "transparent" (endings unchanged) or "native" (endings changed to match host os filesystem convention). the default value is "transparent". getblob() re
turns the blob object that has been constructed using the data passed through calls to append(). blob getblob( in domstring contenttype optional ); parameters contenttype optional the mime type of the data to be re
turned in the blob. this will be the value of the blob object's type property. re
turn value a blob object containing all of the data passed to any calls to append() made since the blobbuilder was created. this also resets the blobbuilder so that the next call to append() is starting a new, empty blob. getfile() re
turns a file object. file getfile( in domstring name, [optional] in domstring...
...ining all of the data passed to any calls to append() made since the blobbuilder was created. this also resets the blobbuilder so that the next call to append() is starting a new, empty blob. getfile() re
turns a file object. file getfile( in domstring name, [optional] in domstring contenttype ); parameters name the file name. contenttype optional the mime type of the data to be re
turned in the file. this will be the value of the file object's type property. re
turn value a file object. ...
Bluetooth - Web APIs
the bluetooth interface of the web bluetooth api re
turns a promise to a bluetoothdevice object with the specified options. interface interface bluetooth : eventtarget { promise<boolean> getavailability(); attribute eventhandler onavailabilitychanged; [sameobject] readonly attribute bluetoothdevice? referringdevice; promise<sequence<bluetoothdevice>> getdevices(); promise<bluetoothdevice> requestdevice(optional requestdeviceoptions options = {}); }; bluetooth includes bluetoothdeviceeventhandlers; bluetooth includes characteristiceventhandlers; bluetooth includes serviceeventhandlers; properties inherits properties from its parent eventtarget. bluetooth.referringdevice read only re
turns a reference to the device, if any, from which the user opened the current page. for...
...ened the current page. for example, an eddystone beacon might advertise a url, which the user agent allows the user to open. a bluetoothdevice representing the beacon would be available through navigator.bluetooth.referringdevice. events bluetooth.onavailabilitychanged an event handler that runs when an event of type availabilitychanged has fired. ...
...rough navigator.bluetooth.referringdevice. events bluetooth.onavailabilitychanged an event handler that runs when an event of type availabilitychanged has fired. methods bluetooth.getavailability() re
turns a promise that resolved to a boolean indicating whether the user-agent has the ability to support bluetooth. some user-agents let the user configure an option that affects what is re
turned by this value. if this option is set, that is the value re
turned by this method. bluetooth.getdevices() re
turns a promise that resolved to an array of bluetoothdevices which the origin already obtained permission for via a call to bluetooth.requestdevice(). bluetooth.requestdevice() re
turns a promise to a bluetoothdevice object with the specified options. specifications specific...
BluetoothAdvertisingData - Web APIs
he web bluetooth api provides advertising data about a particular bluetooth device. ...
...ribute unsigned short? appearance; readonly attribute byte? txpower; readonly attribute byte? rssi; readonly attribute map manufacturerdata; readonly attribute map servicedata; }; properties bluetoothadvertisingdata.appearance read only re
turns one of the values defined by the org.bluetooth.characteristic.gap.appearance characteristic. bluetoothadvertisingdata.txpower read only re
turns the transmission power at which the device is broadcasting, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.rssi read only re
turns the power at which the device’s packets are being received, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.manufacturerdata read only re...
...s the transmission power at which the device is broadcasting, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.rssi read only re
turns the power at which the device’s packets are being received, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.manufacturerdata read only re
turns a map that relates company identifier codes to arraybuffers. bluetoothadvertisingdata.servicedata read only re
turns a map that relates uuids to arraybuffers. methods none. ...
BluetoothRemoteGATTService - Web APIs
eristicuuid characteristic); promise<sequence<bluetoothgattcharacteristic>> getcharacteristics(optional bluetoothcharacteristicuuid characteristic); promise<bluetoothgattservice> getincludedservice(bluetoothserviceuuid service); promise<sequence<bluetoothgattservice>> getincludedservices(optional bluetoothserviceuuid service); }; properties bluetoothremotegattservice.deviceread only re
turns information about a bluetooth device through an instance of bluetoothdevice. bluetoothremotegattservice.isprimaryread only re
turns a boolean indicating whether this is a primary or secondary service. bluetoothremotegattservice.uuidread only re
turns a domstring representing the uuid of this service. methods bluetoothremotegattservice.getcharacteristic() re
turns a promise to an instan...
...a boolean indicating whether this is a primary or secondary service. bluetoothremotegattservice.uuidread only re
turns a domstring representing the uuid of this service. methods bluetoothremotegattservice.getcharacteristic() re
turns a promise to an instance of bluetoothgattcharacteristic for a given universally unique identifier (uuid). bluetoothremotegattservice.getcharacteristics() re
turns a promise to an array of bluetoothgattcharacteristic instances for an optional universally unique identifier (uuid). bluetoothremotegattservice.getincludedservice() re
turns a promise to an instance of bluetoothremotegattservice for a given universally unique identifier (uuid). ...
... (uuid). bluetoothremotegattservice.getcharacteristics() re
turns a promise to an array of bluetoothgattcharacteristic instances for an optional universally unique identifier (uuid). bluetoothremotegattservice.getincludedservice() re
turns a promise to an instance of bluetoothremotegattservice for a given universally unique identifier (uuid). bluetoothremotegattservice.getincludedservices() re
turns a promise to an array of bluetoothremotegattservice instances for an optional universally unique identifier (uuid). specifications specification status comment web bluetooththe definition of 'bluetoothremotegattservice' in that specification. draft initial definition. ...
Body - Web APIs
ith an associated body (a stream), a used flag (initially unset), and a mime type (initially the empty byte sequence). properties body.body read only a simple getter used to expose a readablestream of the body contents. body.bodyused read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. ...
...operties body.body read only a simple getter used to expose a readablestream of the body contents. body.bodyused read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. it re
turns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. it re
turns a promise that resolves with a blob. body.formdata() takes a response stream and reads it to completion. ...
... read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. it re
turns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. it re
turns a promise that resolves with a blob. body.formdata() takes a response stream and reads it to completion. it re
turns a promise that resolves with a formdata object. body.json() takes a response stream and reads it to completion. it re
turns a promise that resolves with the result of parsing the body text as json. body.text() takes a response stream and reads it to completion. it re
turns a promise that resolves with a usvstring (text). the response is always decoded using utf-8. examples the example below...
CSSPositionValue - Web APIs
methods none. ...
... methods none. ...
...pixels from the left of the page. let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-position') ); we set the object-position property, then check the values re
turned. #image { width: 300px; height: 300px; border: 1px solid black; background-color: #dededf; object-fit: none; } <p>check the developer tools to see the log in the console and to inspect the style attribute on the image.</p> <img id="image" src="https://udn.realityripple.com/samples/db/4f9fbd7dfb.svg" alt="mdn logo"/> ...
CSSStyleDeclaration - Web APIs
represents an object that is a css declaration block, and exposes style information and various style-related methods and properties. a cssstyledeclaration object can be exposed using three different apis: via htmlelement.style, which deals with the inline styles of a single element (e.g., <div style="...">). via the cssstylesheet api. for example, document.stylesheets[0].cssrules[0].style re
turns a cssstyledeclaration object on the first css rule in the document's first stylesheet. via window.getcomputedstyle(), which exposes the cssstyledeclaration object as a read-only interface. attributes cssstyledeclaration.csstext textual representation of the declaration block. setting this attribute changes the style. cssstyledeclaration.lengthread only the number of properties. see the...
...on.lengthread only the number of properties. see the item() method below. cssstyledeclaration.parentruleread only the containing cssrule. css properties cssstyledeclaration.cssfloat special alias for the float css property. cssstyledeclaration named properties dashed and camel-cased attributes for all supported css properties. methods cssstyledeclaration.getpropertypriority() re
turns the optional priority, "important". cssstyledeclaration.getpropertyvalue() re
turns the property value given a property name. cssstyledeclaration.item() re
turns a css property name by its index, or the empty string if the index is out-of-bounds. an alternative to accessing nodelist[i] (which instead re
turns undefined when i is out-of-bounds). this is mostly useful for non-javascript dom impl...
...when i is out-of-bounds). this is mostly useful for non-javascript dom implementations. cssstyledeclaration.removeproperty() removes a property from the css declaration block. cssstyledeclaration.setproperty() modifies an existing css property or creates a new css property in the declaration block. cssstyledeclaration.getpropertycssvalue() only supported via getcomputedstyle in firefox. re
turns the property value as a cssprimitivevalue or null for shorthand properties. example var styleobj = document.stylesheets[0].cssrules[0].style; console.log(styleobj.csstext); for (var i = styleobj.length; i--;) { var namestring = styleobj[i]; styleobj.removeproperty(namestring); } console.log(styleobj.csstext); specifications specification status comment css ...
CSSStyleSheet.insertRule() - Web APIs
type: for rule-sets, both a selector and a style declaration. for at-rules, both an at-identifier and the rule content. index optional a positive integer less than or equal to stylesheet.cssrules.length, representing the newly inserted rule's position in cssstylesheet.cssrules. the default is 0. (in older implementations, this was required. see browser compatibility for details.) re
turn value the newly inserted rule's index within the stylesheet's rule-list. restrictions css has some intuitive and not-so-intuitive restrictions affecting where rules can be inserted. violating them will likely raise a domexception. if index > cssrulelist.length, the method aborts with an indexsizeerror. if rule cannot be inserted at index 0 due to some css constraint, the method aborts with...
...= len; ++i) { newcharcode = selectorandrule.charcodeat(i); if (!isescaped && (newcharcode === 125)) { // 125 = "}".charcodeat(0) closebracketpos = i; } isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } if (closebracketpos === -1) break a; // no closing bracket was found! ...
... working draft no change from document object model (dom) level 2 style specification. document object model (dom) l...
CSSStyleSheet.ownerRule - Web APIs
examples this snippet of code looks for rules which were not imported into the document using an @import at-rule. ...
... examples this snippet of code looks for rules which were not imported into the document using an @import at-rule. ...
... examples this snippet of code looks for rules which were not imported into the document using an @import at-rule. ...
CSSStyleSheet - Web APIs
the stylesheet's cssrules property. for example, one rule might be a cssstylerule object containing a style such as: h1, h2 { font-size: 16pt; } another rule might be an at-rule such as @import or @media, and so forth. see the notes section for the various ways a cssstylesheet object can be obtained. properties inherits properties from its parent, stylesheet. cssrules read only re
turns a live cssrulelist which maintains an up-to-date list of the cssrule objects that comprise the stylesheet. this is normally used to access individual rules like this: stylesheet.cssrules[i] // where i = 0..cssrules.length-1 to add or remove items in cssrules, use the cssstylesheet's insertrule() and deleterule() methods. ownerrule read only if this stylesheet is imported into the docu...
...st of the cssrule objects that comprise the stylesheet. this is normally used to access individual rules like this: stylesheet.cssrules[i] // where i = 0..cssrules.length-1 to add or remove items in cssrules, use the cssstylesheet's insertrule() and deleterule() methods. ownerrule read only if this stylesheet is imported into the document using an @import rule, the ownerrule property re
turns the corresponding cssimportrule; otherwise, this property's value is null. methods inherits methods from its parent, stylesheet. deleterule() deletes the rule at the specified index into the stylesheet's rule list. insertrule() inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule. legacy properties these properties are legacy pr...
...insertrule() inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule. legacy properties these properties are legacy properties first introduced by microsoft long ago; they shouldn't be used but are not likely to be removed anytime soon. rules read only the rules property is functionally identical to the standard cssrules property; it re
turns a live cssrulelist which maintains an up-to-date list of all of the rules in the style sheet. legacy methods these methods are legacy methods first introduced by microsoft; they should not be used if they can be avoided, but are not in danger of being removed anytime soon. addrule() adds a new rule to the stylesheet given the selector to which the style applies and the style block to ap...
CSSUnitValue.CSSUnitValue() - Web APIs
examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. ...
... examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. ...
... examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors. ...
CSSUnparsedValue.entries() - Web APIs
specifications specification status comment css typed om level 1the definition of 'entries()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'entries()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'entries()' in that specification. ...
Determining the dimensions of elements - Web APIs
an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the htmlelement.offsetwidth and htmlelement.offsetheight properties. most of the time these are the same as width and height of element.getboundingclientrect(), when there aren't any transforms applied to the element. in case of transforms, the offsetwidth and offsetheight re
turns the element's layout width and height, while getboundingclientrect() re
turns the rendering width and height. as an example, if the element has width: 100px; and transform: scale(0.5); the getboundingclientrect() will re
turn 50 as the width, while offsetwidth will re
turn 100. what's the size of the displayed content? if you need to know how much space the actual displayed content takes up, in...
... ...
...he content, regardless of how much of it is currently visible, you need to use the element.scrollwidth and element.scrollheight properties. these re
turn the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars. for example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, scrollwidth will re
turn 600 while scrollheight will re
turn 400. ...
Cache.add() - Web APIs
the add() method of the cache interface takes a url, retrieves it, and adds the resulting response object to the given cache. the add() method is functionally equivalent to the following: fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } re
turn cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly. note: add() will overwrite any key/value pair previously stored in the cache that matches the request. syntax cache.add(request).then(function() { // request has been added to the cache }); parameters request the request you want to add to the cache. this can be a request object or a url. re
turn value a promise that resolves with undefined. exceptions exception ...
... parameters request the request you want to add to the cache. this can be a request object or a url. re
turn value a promise that resolves with undefined. exceptions exception happens when typeerror the url scheme is not http or https. the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not re
turn successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it. this.addeventlistener('instal...
...ported status is always 0.) examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { re
turn cache.add('/sw-test/index.html'); }) ); }); specifications specification status comment service workersthe definition of 'cache: add' in that specification. working draft initial definition. ...
Cache.addAll() - Web APIs
match the request, but will fail if a resulting put() operation would overwrite a previous cache entry stored by the same addall() method. syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache. you can specify the request object instead of the url. ...
...hat you want to be fetched and added to the cache. you can specify the request object instead of the url. re
turn value a promise that resolves with undefined. exceptions exception happens when typeerror the url scheme is not http or https. the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not re
turn successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it. this.addeventlistener...
...tatus is always 0.) examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it. ...
CacheStorage.delete() - Web APIs
the delete() method of the cachestorage interface finds the cache object matching the cachename, and if found, deletes the cache object and re
turns a promise that resolves to true. if no cache object is found, it resolves to false. you can access cachestorage through the global caches property. syntax caches.delete(cachename).then(function(boolean) { // your cache is now deleted }); parameters cachename the name of the cache you want to delete. re
turn value a promise that resolves to true if the cache object is found and deleted, and false otherwise. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. here we have an array of cache names we want to keep (ca...
... name of the cache you want to delete. re
turn value a promise that resolves to true if the cache object is found and deleted, and false otherwise. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. here we have an array of cache names we want to keep (cachestokeep). we re
turn the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array. if not, we delete it using delete(). ...
...ated. here we have an array of cache names we want to keep (cachestokeep). we re
turn the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array. if not, we delete it using delete(). this.addeventlistener('activate', function(event) { var cachestokeep = ['v2']; event.waituntil( caches.keys().then(function(keylist) { re
turn promise.all(keylist.map(function(key) { if (cachestokeep.indexof(key) === -1) { re
turn caches.delete(key); } })); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: delete' in that specification. working draft initial definition. ...
CacheStorage.has() - Web APIs
examples the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. ...
... examples the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. ...
... promise that resolves to true if the cache exists or false if not. examples the following example first checks whether a cache called 'v1' exists. if so, we add a list of assets to it. if not then we run some kind of cache set-up function. caches.has('v1').then(function(hascache) { if (!hascache) { somecachesetupfunction(); } else { caches.open('v1').then(function(cache) { re
turn cache.addall(myassets); }); } }).catch(function() { // handle exception here. }); specifications specification status comment service workersthe definition of 'cachestorage: has' in that specification. working draft initial definition. ...
CanvasRenderingContext2D.getImageData() - Web APIs
note: image data can be painted onto a canvas using the putimagedata() method. you can find more information about getimagedata() and general manipulation of canvas contents in pixel manipulation with canvas. ...
... note: image data can be painted onto a canvas using the putimagedata() method. you can find more information about getimagedata() and general manipulation of canvas contents in pixel manipulation with canvas. ...
...edata will be extracted. sy the y-axis coordinate of the top-left corner of the rectangle from which the imagedata will be extracted. sw the width of the rectangle from which the imagedata will be extracted. positive values are to the right, and negative to the left. sh the height of the rectangle from which the imagedata will be extracted. positive values are down, and negative are up. re
turn value an imagedata object containing the image data for the rectangle of the canvas specified. the coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh). exceptions indexsizeerror thrown if either sw or sh are zero. securityerror the canvas contains or may contain pixels which were loaded from an origin other than th...
Transformations - Web APIs
ge some drawing settings and draw the third semi-transparent white rectangle. so far this is pretty similar to what we've done in previous sections. however once we call the first restore() statement, the top drawing state is removed from the stack, and settings are restored. if we hadn't saved the state using save(), we would need to change the fill color and transparency manually in order to re
turn to the previous state. this would be easy for two properties, but if we have more than that, our code would become very long, very fast. when the second restore() statement is called, the original state (the one we set up before the first call to save) is restored and the last rectangle is once again drawn in black. screenshotlive sample translating the first of the transformation methods we'...
...nvas and its origin to a different point in the grid. translate(x, y) moves the canvas and its origin on the grid. x indicates the horizontal distance to move, and y indicates how far to move the grid vertically. it's a good idea to save the canvas state before doing any transformations. in most cases, it is just easier to call the restore method than having to do a reverse translation to re
turn to the original state. also if you're translating inside a loop and don't save and restore the canvas state, you might end up missing part of your drawing, because it was drawn outside the canvas edge. a translate example this example demonstrates some of the benefits of translating the canvas origin. without the translate() method, all of the rectangles would be drawn at the same position (0,0...
...,0). the translate() method also gives us the freedom to place the rectangle anywhere on the canvas without having to manually adjust coordinates in the fillrect() function. this makes it a little easier to understand and use. in the draw() function, we call the fillrect() function nine times using two for loops. in each loop, the canvas is translated, the rectangle is drawn, and the canvas is re
turned back to its original state. note how the call to fillrect() uses the same coordinates each time, relying on translate() to adjust the drawing position. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ctx.save(); ctx.fillstyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)'; ...
Client.url - Web APIs
the url read-only property of the client interface re
turns the url of the current service worker client. syntax var clienturl = client.url; value a usvstring. ...
... working draft initial definition. ...
... working draft initial definition. ...
Clients.matchAll() - Web APIs
the matchall() method of the clients interface re
turns a promise for a list of service worker client objects. include the options parameter to re
turn all service worker clients whose origin is the same as the associated service worker's origin. if options are not included, the method re
turns only the service worker clients controlled by the service worker. syntax self.clients.matchall(options).then(function(clients) { // do something with your clients list }); parameters options optional an options object allowing you to set options for the matching operation. ...
... re
turns only the service worker clients controlled by the service worker. syntax self.clients.matchall(options).then(function(clients) { // do something with your clients list }); parameters options optional an options object allowing you to set options for the matching operation. available options are: includeuncontrolled: a boolean — if set to true, the matching operation will re
turn all service worker clients who share the same origin as the current service worker. otherwise, it re
turns only the service worker clients controlled by the current service worker. the default is false. type: sets the type of clients you want matched. available values are "window", "worker", "sharedworker", and "all". the default is "all". ...
... set to true, the matching operation will re
turn all service worker clients who share the same origin as the current service worker. otherwise, it re
turns only the service worker clients controlled by the current service worker. the default is false. type: sets the type of clients you want matched. available values are "window", "worker", "sharedworker", and "all". the default is "all". re
turn value a promise that resolves to an array of client objects. in chrome 46/firefox 54 and later, this method re
turns clients in most recently focused order, correct as per spec. examples clients.matchall(options).then(function(clientlist) { for (var i = 0 ; i < clientlist.length ; i++) { if (clientlist[i].url === 'index.html') { clients.openwindow(clientlist[i]); // or do s...
Clipboard - Web APIs
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 re
turn 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, that can be accessed fr...
... be accessed from most or all programs within the environment via defined programming interfaces. a typical application accesses clipboard functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces. methods clipboard is based on the eventtarget interface, and includes its methods. read() requests arbitrary data (such as images) from the clipboard, re
turning 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; re
turns 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 r...
...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; re
turns 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 re
turned promise. writetext() writes text to the system clipboard, re
turning a promise which is resolved once the text is fully copied into the clipboard. clipboard availability the asynchronous clipboard api is a relatively recent addition, and the process of implementing it in browsers is not yet complete. due to both potential security concerns and technical complexities, the process of integrat...
ConstantSourceNode.offset - Web APIs
the default value is 1.0. ...
...the default value is 1.0. ...
...t is read-only, the value property within is not. so you can change the value of offset by setting the value of constantsourcenode.offset.value: myconstantsourcenode.offset.value = newvalue; syntax let offsetparameter = constantaudionode.offset; let offset = constantsourcenode.offset.value; constantsourcenode.offset.value = newvalue; value an audioparam object indicating the a-rate value re
turned for every sample by this node. the default value is 1.0. to access the offset parameter's current value, access the parameter's value property, as shown in the syntax box above. example this example shows how to set up a constantsourcenode so its offset is used as the input to a pair of gainnodes; this snippet is derived from the complete example you can find in controlling multiple paramete...
ContentIndex.delete() - Web APIs
examples below is an asynchronous function, that removes an item from the content index. ...
... examples below is an asynchronous function, that removes an item from the content index. ...
...nction, 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) re
turn; // 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'); specifications specification status comment unknownthe definition of 'delete' in that specification. unknown initial definition. ...
ContentIndex - Web APIs
the contentindex interface of the content index api allows developers to register their offline enabled content with the browser. properties there are no properties of this interface. methods contentindex.add registers an item with the content index. contentindex.delete unregisters an item from the currently indexed content. contentindex.getall re
turns a promise that resolves with an iterable list of content index entries. examples feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface. // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // con...
... async function createreadinglist() { ...
... listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) re
turn; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); specif...
Content Index API - Web APIs
content available offline. contentindexevent the contentindexevent interface of the content index api defines the object used to represent the contentdelete event. service worker additions the following additions to the serviceworker have been specified in the content index api spec to provide an entry point for using content indexing. serviceworkerregistration.index read only re
turns a reference to the contentindex interface for indexing cached pages. serviceworkerglobalscope.oncontentdelete an event handler fired whenever a contentdelete event occurs. this happens when content is removed by the user agent. examples all the following examples assume a service worker has been registered. for more information see the service worker api. feature detection and interface...
... async function createreadinglist() { ...
... listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index. async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) re
turn; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); conten...
CredentialsContainer - Web APIs
the credentialscontainer interface of the the credential management api exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. this interface is accessible from navigator.credentials. properties none. event handlers none. methods credentialscontainer.create()secure context re
turns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created. in exceptional circumstances, the promise may reject. credentialscontainer.get()secure context re
turns a promise that resolves with the credential instance that matches the provided parameters. credentialscontainer.preventsilentaccess()secure context sets a flag that specifies whether automatic log in...
...for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. earlier versions of the spec called this method requireusermediation(). ...
...mise. for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. earlier versions of the spec called this method requireusermediation(). see browser compatibility for support details. credentialscontainer.store()secure context stores a set of credentials for a user, inside a provided credential instance and re
turns that instance in a promise. examples // tbd specifications specification status comment credential management level 1 working draft initial definition. web authentication: an api for accessing public key credentials level 1 recommendation initial definition. ...
DOMException() - Web APIs
example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. candidate recommendation adds the constructor for the domexception class. ...
... example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. candidate recommendation adds the constructor for the domexception class. ...
...h a specified message and name. syntax var domexception = new domexception(); var domexception = new domexception(message); var domexception = new domexception(message, name); parameters message optional a description of the exception. if not present, the empty string '' is used. name optional re
turns a domstring that contains one of the strings associated with an error constant. re
turn value domexception a newly created domexception object. example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification. candidate recommendation adds the constructor for the domexception class. browser compatibility the compatibility table on this page is generated from structured data. if you'...
DOMImplementation.hasFeature() - Web APIs
syntax const flag = document.implementation.hasfeature(feature, version); parameters feature a domstring representing the feature name. version a domstring representing the version of the specification defining the feature. ...
... syntax const flag = document.implementation.hasfeature(feature, version); parameters feature a domstring representing the feature name. version a domstring representing the version of the specification defining the feature. ...
...ment.implementation.hasfeature(feature, version); parameters feature a domstring representing the feature name. version a domstring representing the version of the specification defining the feature. specifications specification status comment domthe definition of 'domimplementation.hasfeature' in that specification. living standard modified to always re
turn true except for svg features. document object model (dom) level 3 core specificationthe definition of 'domimplementation.hasfeature' in that specification. obsolete no change from document object model (dom) level 2 core specification document object model (dom) level 2 core specificationthe definition of 'domimplementation.hasfeature' in that specification. obsolete ...
DOMQuad - Web APIs
a domquad is a collection of four dompoints defining the corners of an arbitrary quadrilateral. re
turning domquads lets getboxquads() re
turn accurate information even when arbitrary 2d or 3d transforms are present. it has a handy bounds attribute re
turning a domrectreadonly for those cases where you just want an axis-aligned bounding rectangle. constructor domquad.domquad() creates a new domquad object. properties p1,p2,p3,p4 read only are dompoint objects for each of the domquad object's four corners. methods domquad.fromrect() re
turns a new domquad object based on the passed set of coordinates. ...
... specifications specification status comment geometry interfaces module level 1the definition of 'domquad' in that specification. ...
...rectangle. constructor domquad.domquad() creates a new domquad object. properties p1,p2,p3,p4 read only are dompoint objects for each of the domquad object's four corners. methods domquad.fromrect() re
turns a new domquad object based on the passed set of coordinates. domquad.fromquad() re
turns a new domquad object based on the passed set of coordinates. domquad.getbounds() re
turns a domrect object with the coordinates and dimensions of the domquad object. domquad.tojson() re
turns a json representation of the domquad object. specifications specification status comment geometry interfaces module level 1the definition of 'domquad' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly - Web APIs
the domrectreadonly interface specifies the standard properties used by domrect to define a rectangle whose properties are immutable. constructor domrectreadonly() defined to create a new domrectreadonly object. note that this constructor cannot be called by 3rd party javascript; doing so re
turns an "illegal constructor" typeerror. properties domrectreadonly.x read only the x coordinate of the domrect's origin. domrectreadonly.y read only the y coordinate of the domrect's origin. ...
...y 3rd party javascript; doing so re
turns an "illegal constructor" typeerror. properties domrectreadonly.x read only the x coordinate of the domrect's origin. domrectreadonly.y read only the y coordinate of the domrect's origin. domrectreadonly.width read only the width of the domrect. domrectreadonly.height read only the height of the domrect. domrectreadonly.top read only re
turns the top coordinate value of the domrect (usually the same as y.) domrectreadonly.right read only re
turns the right coordinate value of the domrect (usually the same as x + width). domrectreadonly.bottom read only re
turns the bottom coordinate value of the domrect (usually the same as y + height). ...
... static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions. ...
DOMUserData - Web APIs
domuserdata is not persisted nor serialized and will not be present after the application has restarted or after a crash. if you are interested in persisting data you might rather need to use nsisessionstore. ...
... domuserdata is not persisted nor serialized and will not be present after the application has restarted or after a crash. if you are interested in persisting data you might rather need to use nsisessionstore. ...
... domuserdata is not persisted nor serialized and will not be present after the application has restarted or after a crash. if you are interested in persisting data you might rather need to use nsisessionstore. ...
DisplayMediaStreamConstraints.audio - Web APIs
se. syntax displaymediastreamconstraints.audio = allowaudioflag; displaymediastreamconstraints.audio = mediatrackconstraints; displaymediastreamconstraints = { audio: allowaudioflag|mediatrackconstraints; } value the value may be either a boolean or a mediatrackconstraints object. ...
...the audio track is always considered optional. ...
......
Document.createNodeIterator() - Web APIs
syntax const nodeiterator = document.createnodeiterator(root[, whattoshow[, filter]]); values root the root node at which to begin the nodeiterator's traversal. whattoshow optional is an optional unsigned long representing a bitmask created by combining the constant properties of nodefilter. it is a convenient way of filtering for certain types of node. it defaults to 0xffffffff representing the show_all constant. constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. nodefilter.show_attribute 2 shows attribute attr nodes. this is meaningful only when creating a treewalker with an attr node as its root. ...
...r.show_text 4 shows text nodes. filter optional an object implementing the nodefilter interface. its acceptnode() method will be called for each node in the subtree based at root which is accepted as included by the whattoshow flag to determine whether or not to include it in the list of iterable nodes (a simple callback function may also be used instead). the method should re
turn one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip. see the example. note: prior to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), this method accepted an optional fourth parameter (entityreferenceexpansion) that is not part of the dom4 specification, and has therefore been removed. this parameter indicated whether or not the children of entity r...
...art of the dom4 specification, and has therefore been removed. this parameter indicated whether or not the children of entity reference nodes were visible to the iterator. since such nodes were never created in browsers, this paramater had no effect. example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode(node) { re
turn node.nodename.tolowercase() === 'p' ? nodefilter.filter_accept : nodefilter.filter_reject; } } ); const pars = []; let currentnode; while (currentnode = nodeiterator.nextnode()) { pars.push(currentnode); } specifications specification status comment domthe definition of 'document.createnodeiterator' in that specification. living standard ...
Document.createTreeWalker() - Web APIs
syntax document.createtreewalker(root, whattoshow[, filter[, entityreferenceexpansion]]); parameters root a root node of this treewalker traversal. typically this will be an element owned by the document. whattoshow optional a unsigned long representing a bitmask created by combining the constant properties of nodefilter. it is a convenient way of filtering for certain types of node. it defaults to 0xffffffff representing the show_all constant. constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. ...
...w_text 4 shows text nodes. filter optional a nodefilter, that is an object with a method acceptnode, which is called by the treewalker to determine whether or not to accept a node that has passed the whattoshow check. entityreferenceexpansion optional a boolean flag indicating if when discarding an entityreference its whole sub-tree must be discarded at the same time. re
turn value a new treewalker object. example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array. var treewalker =...
...s the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array. var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var nodelist = []; var currentnode = treewalker.currentnode; while(currentnode) { nodelist.push(currentnode); currentnode = treewalker.nextnode(); } specifications specification status comment domthe definition of 'document.createtreewalker' in that specification. living standard removed the expandentityreferences pa...
Document.doctype - Web APIs
dom level 2 doesn't support editing the document type declaration. ...
... dom level 2 doesn't support editing the document type declaration. ...
...ent.doctype; doctype is a read-only property. example var doctypeobj = document.doctype; console.log( "doctypeobj.name: " + doctypeobj.name + "\n" + "doctypeobj.internalsubset: " + doctypeobj.internalsubset + "\n" + "doctypeobj.publicid: " + doctypeobj.publicid + "\n" + "doctypeobj.systemid: " + doctypeobj.systemid ); notes the property re
turns null if there is no dtd associated with the current document. dom level 2 doesn't support editing the document type declaration. specifications specification status comment domthe definition of 'document: doctype' in that specification. living standard ...
Document.getElementsByClassName() - Web APIs
syntax var elements = document.getelementsbyclassname(names); // or: var elements = rootelement.getelementsbyclassname(names); elements is a live htmlcollection of found elements. ...
... syntax var elements = document.getelementsbyclassname(names); // or: var elements = rootelement.getelementsbyclassname(names); elements is a live htmlcollection of found elements. ...
... is no matching element: document.getelementsbyclassname('test')[0] we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value. here we'll find all div elements that have a class of 'test': var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement){ re
turn testelement.nodename === 'div'; }); get the first element whose class is 'test' this is the most commonly used method of operation. <html> <body> <div id="parent-id"> <p>hello world 1</p> <p class="test">hello world 2</p> <p>hello world 3</p> <p>hello world 4</p> </div> <script> var parentdom = document.getelementbyid("parent-id"); ...
Document.getElementsByName() - Web APIs
the getelementsbyname() method of the document object re
turns a nodelist collection of elements with a given name in the document. syntax var elements = document.getelementsbyname(name); elements is a live nodelist collection, meaning it automatically updates as new elements with the same name are added to/removed from the document. name is the value of the name attribute of the element(s). ...
... of the element(s). example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents. the re
turned nodelist collection contains all elements with the given name, such as <meta>, <object>, and even elements which do not support the name attribute at all. the getelementsbyname method works differently in ie10 and below. there, getelementsbyname() also re
turns elements that have an id attribute with the specified value. be careful not to use the same string as both a name and an id. the ge...
...ect>, and even elements which do not support the name attribute at all. the getelementsbyname method works differently in ie10 and below. there, getelementsbyname() also re
turns elements that have an id attribute with the specified value. be careful not to use the same string as both a name and an id. the getelementsbyname method works differently in ie. there, getelementsbyname() does not re
turn all elements which may not have a name attribute (such as <span>). both ie and edge re
turn an htmlcollection, not a nodelist specifications specification status comment html living standardthe definition of 'document.getelementsbyname()' in that specification. living standard document object model (dom) level 2 html specificationthe definition of...
Document.getElementsByTagNameNS() - Web APIs
re
turns a list of elements with the given tag name belonging to the given namespace. the complete document is searched, including the root node. syntax elements = document.getelementsbytagnamens(namespace, name) elements is a live nodelist (but see the note below) of found elements in the order they appear in the tree. namespace is the namespace uri of elements to look for (see element.namespaceuri). name is either the local name of elements to look for or the special value *, which matches all elements (see element.localname). note: while the w3c specification says elements is a nodelist, this method re
turns a htmlcollection both in gecko and internet explorer. opera re
turns a nodelist, but with a nameditem method implemented, which makes it similar to a htmlcollection. as of janua...
...see bug 14869 for details. note: currently parameters in this method are case-sensitive, but they were case-insensitive in firefox 3.5 and before. ...
... living standard ...
Document.lastStyleSheetSet - Web APIs
note: this value doesn't change when document.enablestylesheetsforset() is called. ...
... note: this value doesn't change when document.enablestylesheetsforset() is called. ...
... note: this value doesn't change when document.enablestylesheetsforset() is called. ...
Document.requestStorageAccess() - Web APIs
conditions for granting storage access storage access is granted based on a series of checks described here: if the document already has been granted access, resolve. if the document has a null origin, reject. if the document's frame is the main frame, resolve. if the sub frame's origin is equal to the main frame's, resolve. if the sub frame is not sandboxed, skip to step 7. if the sub frame doesn't have the token allow-storage-access-by-user-activation, reject. if the sub frame's parent frame is not the top frame, reject. ...
...requesting origin has storage access to is decremented by one. note: if the requesting origin is not classified as a tracking origin, the access request is automatically given an ephemeral storage access grant, which will go away when the page is reloaded. the user is never shown a prompt in this case, and calling requeststorageaccess() won’t have any side effects besides changing the value re
turned by document.hasstorageaccess(). debugging the storage access grant threshold may make it more difficult to test your website under the condition where firefox prompts the user for access. to make testing easier, we have added two preferences in about:config that control prompting upon requeststorageaccess() calls: dom.storage_access.auto_grants can be set to false to disable the automatic...
...e access grants at which users will begin to receive prompts. for example, if you want to configure firefox to automatically grant access on the first site where requeststorageaccess() is called and then prompt afterwards, you should adjust the value of the dom.storage_access.max_concurrent_auto_grants preference to 1. syntax var promise = document.requeststorageaccess(); parameters none. re
turn value a promise that fulfills with undefined if the access to first-party storage was granted, and rejects if access was denied. when the promise gets resolved, the resolve handler will run as if a user gesture is being processed, whether the promise was fulfilled or rejected: in the former case, code can then start to call apis that require user activation and things can move forward. in t...
DocumentOrShadowRoot.fullscreenElement - Web APIs
the documentorshadowroot.fullscreenelement read-only property re
turns the element that is currently being presented in full-screen mode in this document, or null if full-screen mode is not currently in use. although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. syntax var element = document.fullscreenelement; re
turn value the element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the re
turned value is null. ...
...if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. syntax var element = document.fullscreenelement; re
turn value the element object that's currently in full-screen mode; if full-screen mode isn't currently in use by the document>, the re
turned value is null. example this example presents a function, isvideoinfullscreen(), which looks at the value re
turned by fullscreenelement; if the document is in full-screen mode (fullscreenelement isn't null) and the full-screen element's nodename is video, indicating a <video> element, the function re
turns true, indicating that the video is in full-screen mode. ...
...oks at the value re
turned by fullscreenelement; if the document is in full-screen mode (fullscreenelement isn't null) and the full-screen element's nodename is video, indicating a <video> element, the function re
turns true, indicating that the video is in full-screen mode. function isvideoinfullscreen() { if (document.fullscreenelement && document.fullscreenelement.nodename == 'video') { re
turn true; } re
turn false; } specifications specification status comment fullscreen apithe definition of 'document.fullscreenelement' in that specification. living standard initial definition ...
DocumentOrShadowRoot.getSelection() - Web APIs
the getselection() property of the documentorshadowroot interface re
turns a selection object representing the range of text selected by the user, or the current position of the caret. syntax var selection = documentorshadowrootinstance.getselection() parameters none. re
turns a selection object. example function foo() { var selobj = document.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert()), the object's tostring() method is called and the re
turned value is passed to the function. this can make the object appear to be a string when used with other functions when it i...
...o be a string when used with other functions when it is really an object with properties and methods. in the above example, selobj.tostring() is automatically called when it is passed to window.alert(). however, attempting to use a javascript string property or method such as length or substr directly on a selection object results in an error if it does not have that property or method and may re
turn unexpected results if it does. to use a selection object as a string, call its tostring() method directly: var selectedtext = selobj.tostring(); selobj is a selection object. selectedtext is a string (selected text). related objects you can call window.getselection(), which works identically to document.getselection(). it is worth noting that currently getselection() doesn't work on the ...
...s a string (selected text). related objects you can call window.getselection(), which works identically to document.getselection(). it is worth noting that currently getselection() doesn't work on the content of <input> elements in firefox. htmlinputelement.setselectionrange()) could be used to work around this. notice also the difference between selection and focus. document.activeelement re
turns the focused element. specifications specification status comment shadow domthe definition of 'documentorshadowroot' in that specification. obsolete initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat...
DocumentOrShadowRoot.styleSheets - Web APIs
stylesheets retrieved from the dom are placed after, sorted in tree order. ...
... stylesheets retrieved from the dom are placed after, sorted in tree order. ...
... stylesheets retrieved from the dom are placed after, sorted in tree order. ...
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
code. in the <table> tree of figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children. each <tbody>'s child (<tr>) has two children (<td>). finally, each <td> has one child: a text node. example: setting the background color of a paragraph getelementsbytagname(tagnamevalue) is a method available in any dom element or the root document element. when called, it re
turns an array with all of the element's descendants matching the tag name. the first element of the list is located at position [0] in the array. html <body> <input type="button" value="set paragraph background color" onclick="set_background()"> <p>hi</p> <p>hello</p> </body> javascript function set_background() { // get a list of all the body elements (there will only be one), // and t...
...ect for an html element, you can set its properties. for example, if you want to set the style background color property, you just add: myp.style.background = "rgb(255,0,0)"; // setting inline style attribute creating textnodes with document.createtextnode("..") use the document object to invoke the createtextnode method and create your text node. you just need to pass the text content. the re
turn value is an object that represents the text node. mytextnode = document.createtextnode("world"); this means that you have created a node of the type text_node (a piece of text) whose text data is "world", and mytextnode is your reference to this node object. to insert this text into your html page, you need to make this text node a child of some other node element. inserting elements with app...
...","2"); } </script> </head> <body onload="start()"> </body> </html> manipulating the table with dom and css getting a text node from the table this example introduces two new dom attributes. first it uses the childnodes attribute to get the list of child nodes of mycel. the childnodes list includes all child nodes, regardless of what their name or type is. like getelementsbytagname(), it re
turns a list of nodes. the differences are that (a) getelementsbytagname() only re
turns elements of the specified tag name; and (b) getelementsbytagname() re
turns descendants at any level, not just immediate children. once you have the re
turned list, use [x] method to retrieve the desired child item. this example stores in myceltext the text node of the second cell in the second row of the table. t...
EXT_disjoint_timer_query.getQueryEXT() - Web APIs
if pname is ext.query_counter_bits_ext: a glint indicating the number of bits used to hold the query result for the given target. ...
... if pname is ext.query_counter_bits_ext: a glint indicating the number of bits used to hold the query result for the given target. ...
... if pname is ext.query_counter_bits_ext: a glint indicating the number of bits used to hold the query result for the given target. ...
EXT_disjoint_timer_query - Web APIs
sult is available. ext.time_elapsed_ext elapsed time (in nanoseconds). ext.timestamp_ext the current time. ext.gpu_disjoint_ext a glboolean indicating whether or not the gpu performed any disjoint operation. methods this extension exposes eight new methods. ext.createqueryext() creates a new webglquery. ext.deletequeryext() deletes a given webglquery. ...
... examples var ext = gl.getextension('ext_disjoint_timer_query'); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. ...
...ebglquery. ext.beginqueryext() the timer starts when all commands prior to beginqueryext have been fully executed. ext.endqueryext() the timer stops when all commands prior to endqueryext have been fully executed. ext.querycounterext() records the current time into the corresponding query object. ext.getqueryext() re
turns information about a query target. ext.getqueryobjectext() re
turn the state of a query object. examples var ext = gl.getextension('ext_disjoint_timer_query'); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. working draft initial definition. ...
Element.getAttributeNS() - Web APIs
the getattributens() method of the element interface re
turns the string value of the attribute with the specified namespace and name. if the named attribute does not exist, the value re
turned will either be null or "" (the empty string); see notes for details. syntax attrval = element.getattributens(namespace, name) parameters namespace the namespace in which to look for the specified attribute. name the name of the attribute to look for. re
turn value the string value of the specified attribute. if the attribute doesn't exist, the result is null. note: earlier versions of the dom specification had this method described as re
turning an empty string for non-existent attributes, but it was not typically implemented this way since null makes more sense. the dom4 specification now sa...
... examples the following svg document reads the value of the foo attribute in a custom namespace. ...
...orted in xml documents. html5 documents have to use getattribute() instead. getattributens() differs from getattribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on mozilla. prior to the dom4 specification, this method was specified to re
turn an empty string rather than null for non-existent attributes. however, most browsers instead re
turned null. starting with dom4, the specification now says to re
turn null. however, some older browsers re
turn an empty string. for that reason, you should use hasattributens() to check for an attribute's existence prior to calling getattributens() if it is possible that the requested attribute does no...
Element.getAttributeNames() - Web APIs
using getattributenames() along with getattribute(), is a memory-efficient and performant alternative to accessing element.attributes. ...
... using getattributenames() along with getattribute(), is a memory-efficient and performant alternative to accessing element.attributes. ...
... living standard initial definition ...
Element.getClientRects() - Web APIs
each domrect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. for tables with captions, the caption is included even though it's outside the border box of the table. ...
...aption is included even though it's outside the border box of the table. when called on svg elements other than an outer-<svg>, the "viewport" that the resulting rectangles are relative to is the viewport that the element's outer-<svg> establishes (and to be clear, the rectangles are also transformed by the outer-<svg>'s viewbox transform, if any). originally, microsoft intended this method to re
turn a textrectangle object for each line of text. however, the cssom working draft specifies that it re
turns a domrect for each border box. for an inline element, the two definitions are the same. but for a block element, mozilla will re
turn only a single rectangle. firefox 3.5 note firefox 3.5 adds width and height properties to the textrectangle object. the amount of scrolling that has ...
...border box. for an inline element, the two definitions are the same. but for a block element, mozilla will re
turn only a single rectangle. firefox 3.5 note firefox 3.5 adds width and height properties to the textrectangle object. the amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the rectangles. the re
turned rectangles do not include the bounds of any child elements that might happen to overflow. for html <area> elements, svg elements that do not render anything themselves, display:none elements, and generally any elements that are not directly rendered, an empty list is re
turned. rectangles are re
turned even for css boxes that have empty border-boxes. the left, top, right, and bottom coordinates...
Element.getElementsByClassName() - Web APIs
the element method getelementsbyclassname() re
turns a live htmlcollection which contains every descendant element which has the specified class name or names. the method getelementsbyclassname() on the document interface works essentially the same way, except it acts on the entire document, starting at the document root. syntax var elements = element.getelementsbyclassname(names); parameters names a domstring containing one or more class names to match on, separated by whitespace. re
turn value an htmlcollection providing a live-updating list of every element which is a member of every class in names. usage notes as always, the re
turned collection is live, meaning that it always reflects the current state of the dom tree rooted at the element on which the function was called. as n...
...however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classlist.remove('colorbox'); matches.item(i).classlist.ad...
...ill then become item(0). filtering the results using array methods we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value. here we'll find all <div> elements that have a class of test: var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement) { re
turn testelement.nodename === 'div'; }); specifications specification status comment domthe definition of 'element.getelementsbyclassname()' in that specification. living standard initial definition ...
Element.localName - Web APIs
the element.localname read-only property re
turns the local part of the qualified name of an element. in previous dom specifications this api was defined within the node interface. syntax name = element.localname re
turn value a domstring representing the local part of the element's qualified name. example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = ...
...icular xml documents. ...
...s:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partner> </ecomm:business> note: in gecko 1.9.2 and earlier, the property re
turns the upper-cased version of the local name for html elements in html doms (as opposed to xhtml elements in xml doms). in later versions, in compliance with html5, the property re
turns in the case of the internal dom storage, which is lower case for both html elements in html doms and xhtml elements in xml doms. the tagname property continues to re
turn in the upper case for html elements in html doms. specifications specification status comment domthe definition of 'element.localname' in that specification. living standard initial definitio...
Element.requestFullscreen() - Web APIs
if permission is denied, the promise is rejected and the element receives a fullscreenerror event instead. ...
...uestfullscreen(options); parameters options optional a fullscreenoptions object providing options that control the behavior of the transition to full-screen mode. currently, the only option is navigationui, which controls whether or not to show navigation ui while the element is in full-screen mode. the default value is "auto", which indicates that the browser should decide what to do. re
turn value a promise which is resolved with a value of undefined when the transition to full screen is complete. exceptions rather than throw a traditional exception, the requestfullscreen() procedure announces error conditions by rejecting the promise it has re
turned. the rejection handler receives one of the following exception values: typeerror the typeerror exception may be delivered in any...
...h>. it is not a <dialog> element. it must either be located within the top-level document or in an <iframe> which has the allowfullscreen attribute applied to it. additionally, of course, the feature policy "fullscreen" permission must be granted. detecting full-screen activation you can determine whether or not your attempt to switch to full-screen mode is successful by using the promise re
turned by requestfullscreen(), as seen in the example below. to learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the document. it's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to tem...
Element.setAttributeNodeNS() - Web APIs
setattributenodens adds a new namespaced attribute node to an element. syntax replacedattr = element.setattributenodens(attributenode) replacedattr is the replaced attribute node, if any, re
turned by this function. attributenode is an attr node. ...
... note that if you try to set without cloning the node, mozilla gives an ns_error_dom_inuse_attribute_err "attribute already in use" error, as the dom requires cloning for attr to be reused (unlike other nodes which can be moved). dom ...
...lla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // re
turns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is re
turned. note that if you try to set without cloning the node, mozilla gives an ns_error_dom_inuse_attribute_err "attribute already in use" error, as the dom requires cloning for attr to be reused (unlike other nodes which can be moved). dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for deal...
Event.composedPath() - Web APIs
examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow dom as the text content of a <p> element. ...
... examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow dom as the text content of a <p> element. ...
...losed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.log(e.composed); console.log(e.composedpath()); }); when you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. first, the composed property re
turns true beause the click event is always able to propagate across shadow boundaries. second, you'll notice a difference in the value of composedpath for the two elements. the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element'...
Event.msConvertURL() - Web APIs
ic to internet explorer and the microsoft edge browser. syntax var retval = dragevent.msconverturl(file, targettype, targeturl); parameters file [in] type: file the file object to be converted. targettype [in] type: domstring one of the following values indicating the desired conversion type: "specified", "base64", or "unchanged". targeturl [in, optional] type: url the target url. ...
...rosoft edge browser. syntax var retval = dragevent.msconverturl(file, targettype, targeturl); parameters file [in] type: file the file object to be converted. targettype [in] type: domstring one of the following values indicating the desired conversion type: "specified", "base64", or "unchanged". targeturl [in, optional] type: url the target url. re
turn value this method does not re
turn a value. ...
...target url. re
turn value this method does not re
turn a value. example var bloblist = []; document.getelementbyid("pastezone").addeventlistener('paste', handlepaste, false); function handlepaste(evt) { var filelist = window.clipboarddata.files; // note that window.datatransfer.files is not applicable. if (!filelist) { console.log("filelist is null."); re
turn; } for (var i = 0; i < filelist.length; i++) { var file = filelist[i]; var url = url.createobjecturl(file); if (evt.converturl) { // use standard if available. evt.converturl(file, "specified", url); } else { evt.msconverturl(file, "specified", url); } console.log("local file: " + file.name + " (" + file.size + ")"...
FetchEvent.isReload - Web APIs
the isreload read-only property of the fetchevent interface re
turns true if the event was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. ...
...hevent interface re
turns true if the event was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. ...
...vent was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. example self.addeventlistener('fetch', function(event) { event.respondwith( if (event.isreload) { //re
turn something } else { //re
turn something else }; ); }); ...
FileReader - Web APIs
the filereader object 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 re
turned 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. to read files by pathname in javascript, standard ajax solutions should be used to do server-side file reading, with cors permission if reading cross-domain. note: this feature i...
...eader 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. to read files by pathname in javascript, standard ajax solutions should be used to do server-side file reading, with cors permission if reading cross-domain. note: this feature is available in web workers. constructor filereader() re
turns a newly constructed filereader. see using files from web applications for details and examples. properties filereader.error read only a domexception representing the error that occurred while reading the file. filereader.readystate read only a number indicating the state of the filereader. this is one of the following: empty 0 no data has been loaded yet. ...
... event is triggered each time the reading operation is completed (either in success or failure). filereader.onprogress a handler for the progress event. this event is triggered while reading a blob content. as filereader inherits from eventtarget, all those events can also be listened for by using the addeventlistener method. methods filereader.abort() aborts the read operation. upon re
turn, the readystate will be done. filereader.readasarraybuffer() starts reading the contents of the specified blob, once finished, the result attribute contains an arraybuffer representing the file's data. filereader.readasbinarystring() starts reading the contents of the specified blob, once finished, the result attribute contains the raw binary data from the file as a string. filereader.reada...
FileSystemDirectoryEntry.createReader() - Web APIs
the filesystemdirectoryentry interface's method createreader() re
turns a filesystemdirectoryreader object which can be used to read the entries in the directory. syntax directoryreader = filesystemdirectoryentry.createreader(); parameters none. re
turn value a filesystemdirectoryreader object which can be used to read the directory's entries. example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and re
turns them in an array. function readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); ...
...tion readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); } }, function(error) { /* handle error -- error is a fileerror object */ }); }; getentries(); re
turn entries; } this works by creating an internal function, getentries(), which calls itself recursively to get all the entries in the directory, concatenating each batch to the array. each iteration, readentries() is called to get more entries. when it re
turns an empty array, the end of the directory has beenr reached, and the recursion ends. once control is re
turned to readdirectory(), the array i...
...ries; } this works by creating an internal function, getentries(), which calls itself recursively to get all the entries in the directory, concatenating each batch to the array. each iteration, readentries() is called to get more entries. when it re
turns an empty array, the end of the directory has beenr reached, and the recursion ends. once control is re
turned to readdirectory(), the array is re
turned to the caller. specifications specification status comment file and directory entries apithe definition of 'createreader()' in that specification. draft initial specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/br...
FileSystemEntry.toURL() - Web APIs
the filesystementry interface's method tourl() creates and re
turns a string containing a url which can be used to identify the file system entry. this is done by exposing a new url scheme—filesystem:—that can be used as the value of src and href attributes. syntax filesystementry.tourl([mimetype]); parameters mimetype optional an optional string specifying the mime type to use when interpreting the file. this can be used to help deal with files whose types aren't recognized automatically by the user agent. if this parameter is omitted, the user agent uses its standard algorithms to identify the file. ...
... the value of src and href attributes. syntax filesystementry.tourl([mimetype]); parameters mimetype optional an optional string specifying the mime type to use when interpreting the file. this can be used to help deal with files whose types aren't recognized automatically by the user agent. if this parameter is omitted, the user agent uses its standard algorithms to identify the file. re
turn value a domstring containing a url that can then be used as a document reference in html content, or an empty string if the url can't be generated (such as if the file system implementation doesn't support tourl()). example if you have a filesystemfileentry corresponding to an image file in a file system available to your web site or app, you can call tourl() to get its url for use in html. if...
...s if the file system implementation doesn't support tourl()). example if you have a filesystemfileentry corresponding to an image file in a file system available to your web site or app, you can call tourl() to get its url for use in html. if your site is located at http://my-awesome-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the url re
turned by tourl() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". code that makes use of this might look like this: let img = document.createelement("img"); img.src = imagefileentry.tourl(); document.body.appendchild(img); assuming the scenario mentioned before the code, the result would be html that looks ...
FontFace - Web APIs
properties this interface doesn't inherit any property. ...
...s downloaded and ready to use. fontface.family a cssomstring that retrieves or sets the family of the font. it is equivalent to the font-family descriptor. fontface.featuresettings a cssomstring that retrieves or sets infrequently used font features that are not available from a font's variant properties. it is equivalent to the font-feature-settings descriptor. fontface.loaded read only re
turns a promise that resolves with the current fontface object when the font specified in the object's constructor is done loading or rejects with a syntaxerror. fontface.status read only re
turns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error". fontface.stretch a cssomstring that retrieves or sets how the font stretches. it is equivalent ...
...etrieves or sets the variant of the font. it is equivalent to the font-variant descriptor. fontface.weight a cssomstring that contains the weight of the font. it is equivalent to the font-weight descriptor. methods this interface doesn't inherit any method. fontface.load() loads a font based on current object's constructor-passed requirements, including a location or source buffer, and re
turns a promise that resolves with the current fontface object. specifications specification status comment css font loading module level 3the definition of 'fontface' in that specification. working draft initial definition ...
Using the Frame Timing API - Web APIs
g an observer to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer callback. in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax. ...
... } } }); // observe frame, mark, measure and resource events observe_frame.observe({entrytypes: ['frame', 'mark', 'measure', 'resource']}); accessing frame data when a frame observer is invoked, the observer callback is given one argument that is a performanceobserverentrylist object. ...
...observer is invoked, the observer callback is given one argument that is a performanceobserverentrylist object. this object has three methods to retrieve frame data: performanceobserverentrylist.getentries() re
turns a list of explicitly observed performanceentry objects based on the list of entry types given to performanceobserver.observe(). performanceobserverentrylist.getentriesbytype() re
turns a list of explicitly observed performanceentry objects of the given entry type. performanceobserverentrylist.getentriesbyname() re
turns a list of explicitly observed performanceentry objects based on the given name and entry type. in the following example, the observer only processes "frame" entries. var threshold = 1500; var observe_frame = new performanceobserver(function(list) { var pe...
Geolocation API - Web APIs
the best available functionality on the device to access this information (for example, gps). the developer can now access this location information in a couple of different ways: geolocation.getcurrentposition(): retrieves the device's current location. geolocation.watchposition(): registers a handler function that will be called automatically each time the position of the device changes, re
turning the updated location. in both cases, the method call takes up to three arguments: a mandatory success callback: if the location retrieval is successful, the callback executes with a geolocationposition object as its only parameter, providing access to the location data. an optional error callback: if the location retrieval is unsuccessful, the callback executes with a geolocationposition...
...ns for retrieval of the position data. for further information on geolocation usage, read using the geolocation api. interfaces geolocation the main class of this api — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch. geolocationposition represents the position of a user. a geolocationposition instance is re
turned by a successful call to one of the methods contained inside geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates instance contains latitude, longitude, and other important related information. geolocationpositionerror a geolocationpositi...
...ssful call to one of the methods contained inside geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates instance contains latitude, longitude, and other important related information. geolocationpositionerror a geolocationpositionerror is re
turned by an unsuccessful call to one of the methods contained inside geolocation, inside an error callback, and contains an error code and message. navigator.geolocation the entry point into the api. re
turns a geolocation object instance, from which all other functionality can be accessed. dictionaries positionoptions represents an object containing options to pass in as a parameter of geoloc...
HTMLAnchorElement - Web APIs
is a domstring that reflects the hreflang html attribute, indicating the language of the linked resource. htmlanchorelement.media is a domstring that reflects the media html attribute, indicating the intended media for the linked resource. htmlhyperlinkelementutils.password is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only re
turns a usvstring containing the origin of the url, that is its scheme, its domain and its port. htmlhyperlinkelementutils.pathname is a usvstring representing the path name component, if any, of the referenced url. htmlhyperlinkelementutils.port is a usvstring representing the port component, if any, of the referenced url. htmlhyperlinkelementutils.protocol is a usvstring representing the proto...
...e protocol component, including trailing colon (':'), of the referenced url. htmlanchorelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use. htmlanchorelement.rel is a domstring that reflects the rel html attribute, specifying the relationship of the target object to the linked object. htmlanchorelement.rellist read only re
turns a domtokenlist that reflects the rel html attribute, as a list of tokens. htmlhyperlinkelementutils.search is a usvstring representing the search element, including leading question mark ('?'), if any, of the referenced url. htmlelement.tabindex is a long containing the position of the element in the tabbing navigation order for the current document. htmlanchorelement.target is a domstring...
...is obsolete. htmlanchorelement.shape is a domstring representing the shape of the active area. methods inherits methods from its parent, htmlelement, and implements those from htmlhyperlinkelementutils. htmlelement.blur() removes the keyboard focus from the current element. htmlelement.focus() gives the keyboard focus to the current element. htmlhyperlinkelementutils.tostring() re
turns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can't be used to modify the value. the blur() and focus() methods are inherited from htmlelement from html5 on, but were defined on htmlanchorelement in dom level 2 html and earlier specifications. specifications specification status comment html living standardthe defi...
HTMLAreaElement - Web APIs
tmlareaelement.media is a domstring containing that reflects the media html attribute, indicating target media of the linked resource. htmlareaelement.nohref is a boolean flag indicating if the area is inactive (true) or active (false). htmlhyperlinkelementutils.password is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only re
turns a usvstring containing the origin of the url, that is its scheme, its domain and its port. htmlhyperlinkelementutils.pathname is a usvstring containing the path name component, if any, of the referenced url. htmlhyperlinkelementutils.port is a usvstring containing the port component, if any, of the referenced url. htmlhyperlinkelementutils.protocol is a usvstring containing the protocol co...
...ng trailing colon ':'), of the referenced url. htmlareaelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the linked resource. htmlareaelement.rel is a domstring that reflects the rel html attribute, indicating relationships of the current document to the linked resource. htmlareaelement.rellist read only re
turns a domtokenlist that reflects the rel html attribute, indicating relationships of the current document to the linked resource, as a list of tokens. htmlhyperlinkelementutils.search is a usvstring containing the search element (including leading question mark '?'), if any, of the referenced url. htmlareaelement.shape is a domstring that reflects the shape html attribute, indicating the shape o...
...resource. htmlareaelement.type is a domstring that reflects the type html attribute, indicating the mime type of the linked resource. htmlhyperlinkelementutils.username is a usvstring containing the username specified before the domain name. methods inherits methods from its parent, htmlelement, and implements those from htmlhyperlinkelementutils. htmlhyperlinkelementutils.tostring() re
turns a usvstring containing the whole url of the script executed in the worker. it is a synonym for htmlhyperlinkelementutils.href. specifications specification status comment html living standardthe definition of 'htmlareaelement' in that specification. living standard the following property has been added: download. technically, the url-related properties, media...
HTMLAudioElement - Web APIs
properties no specific properties; inherits properties from its parent, htmlmediaelement, and from htmlelement. methods inherits methods from its parent, htmlmediaelement, and from htmlelement. it offers no methods of its own. obsolete mozilla-only methods the followi...
...le into it if the file url is given. properties no specific properties; inherits properties from its parent, htmlmediaelement, and from htmlelement. methods inherits methods from its parent, htmlmediaelement, and from htmlelement. it offers no methods of its own. obsolete mozilla-only methods the following methods are non-standard and should not be used. ...
... examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load. ...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
asstream() internal method used to create a new input stream that, when ready, would provide the contents of the canvas as image data. however, this non-standard and internal method has been removed. syntax void canvas.mozfetchasstream(callback, type); parameters callback an nsiinputstreamcallback. type optional a domstring indicating the image format. the default type is image/png. re
turn value none. examples save to disk with mozfetchasstream (chrome context only) this technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico. it saves to the desktop it uses fileutils.jsm. also uses netutil.jsm var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.move...
...k in windows xp as winxp cannot convert from png to ico. it saves to the desktop it uses fileutils.jsm. ...
...eginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); var netutilcallback = function() { re
turn function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfascallback = function(iconname) { re
turn function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputstream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asynccopy(instream, outstream, netutilcallback()); } } canvas.mozfetchasstream(mfascallback('myicon'), 'image/vnd.microsoft.icon'); specifications not part of any specifica...
HTMLCanvasElement.toBlob() - Web APIs
ect as a single argument. mimetype optional a domstring indicating the image format. the default type is image/png. qualityargument optional a number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. if this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. other arguments are ignored. re
turn value none. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents come from secure examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format. the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a co...
...link is created by setting the download attribute. the value of the download attribute is the name it will use as the file name. ...
...ue saves it to the desktop and is only useful in firefox chrome context or add-on code as os apis are not present on web sites. var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { re
turn function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer. cu.import('resource://gre/modules/osfile.jsm'); var writepath = os.path.join(os.constants.path.desktopdir, iconname + '.ico'); var promise = os.file.writeatomic(writepath, new uint8array(r.result), ...
HTMLElement.offsetTop - Web APIs
syntax toppos = element.offsettop; parameters toppos is the number of pixels from the top of the closest relatively positioned parent element. example var d = document.getelementbyid("div1"); var toppos = d.offsettop; if (toppos > 10) { // object is offset more // than 10 pixels from its parent } specification specification status comment css object model (cssom) view modulethe definition of 'offsettop' in that specification. working draft browser compatibility the compatibility table on this page is generated from structured data. ...
...(having display:none does not affect this browser.) ...
...(having display:none does not affect this browser.) ...
HTMLFormElement.reportValidity() - Web APIs
living standard html 5.1the definition of 'htmlformelement.reportvalidity()' in that specification. ...
... living standard html 5.1the definition of 'htmlformelement.reportvalidity()' in that specification. ...
... living standard html 5.1the definition of 'htmlformelement.reportvalidity()' in that specification. ...
HTMLImageElement.naturalWidth - Web APIs
syntax let naturalwidth = htmlimageelement.naturalwidth; value an integer value indicating the intrinsic width of the image, in css pixels. ...
... syntax let naturalwidth = htmlimageelement.naturalwidth; value an integer value indicating the intrinsic width of the image, in css pixels. this is the width at which the image is naturally drawn when no constraint or specific value is established for the image. ...
...y drawn when no constraint or specific value is established for the image. this natural width is corrected for the pixel density of the device on which it's being presented, unlike the value of width. if the intrinsic width is not available—either because the image does not specify an intrinsic width or because the image data is not available in order to obtain this information, naturalwidth re
turns 0. example this example simply displays both the natural, density-adjusted size of an image as well as its rendered size as altered by the page's css and other factors. html <div class="box"> <img src="/files/16797/clock-demo-400px.png" class="image"> </div> <div class="output"> </div> the html features a 400x398 pixel image which is placed inside a <div>. css .box { width: 200px; h...
HTMLMediaElement.textTracks - Web APIs
the read-only texttracks property on htmlmediaelement objects re
turns a texttracklist object listing all of the texttrack objects representing the media element's text tracks, in the same order as in the list of text tracks. you can detect when tracks are added to and removed from an <audio> or <video> element using the addtrack and removetrack events. however, these events aren't sent directly to the media element itself. instead, they're sent to the track list object of the htmlmediaelement that corresponds to the type of track that was added to the element the re
turned list is live; that is, as tracks are added to and removed from the media element, the list's contents change dynamically. once you have a reference to the list, you can monitor it for changes to detect when new t...
...tles" src="samplesubtitles_ja.vtt" srclang="ja"> <track kind="subtitles" src="samplesubtitles_oz.vtt" srclang="oz"> <track kind="metadata" src="keystage1.vtt" srclang="en" label="key stage 1"> <track kind="metadata" src="keystage2.vtt" srclang="en" label="key stage 2"> <track kind="metadata" src="keystage3.vtt" srclang="en" label="key stage 3"> </video> the htmlmediaelement.texttracks re
turns a texttrackslist thru which we can iterate. here we print all the properties of each english track to the console. var tracks = document.queryselector('video').texttracks; for (var i = 0, l = tracks.length; i < l; i++) { /* tracks.length == 10 */ if (tracks[i].language == 'en') { console.dir(tracks[i]); } } properties & methods properties length re
turns the number of text...
...ish track to the console. var tracks = document.queryselector('video').texttracks; for (var i = 0, l = tracks.length; i < l; i++) { /* tracks.length == 10 */ if (tracks[i].language == 'en') { console.dir(tracks[i]); } } properties & methods properties length re
turns the number of text tracks in texttracklist object. methods gettrackbyid() the gettrackbyid(id) method re
turns the first texttrack in the texttracklist object that matches the id, or null if there is no match. specifications specification status comment html living standardthe definition of 'htmlmediaelement.texttracks' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement.texttracks' in that specification. recomm...
HTMLProgressElement - Web APIs
alignment-baseline="middle">htmlprogresselement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlprogresselement.max is a double value reflecting the content attribute of the same name, limited to numbers greater than zero. its default value is 1.0. ...
...ddle">htmlprogresselement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlprogresselement.max is a double value reflecting the content attribute of the same name, limited to numbers greater than zero. its default value is 1.0. ...
...rom its parent, htmlelement. htmlprogresselement.max is a double value reflecting the content attribute of the same name, limited to numbers greater than zero. its default value is 1.0. htmlprogresselement.positionread only re
turns a double value re
turning the result of dividing the current value (value) by the maximum value (max); if the progress bar is an indeterminate progress bar, it re
turns -1. htmlprogresselement.value is a double value that reflects the current value; if the progress bar is an indeterminate progress bar, it re
turns 0. htmlprogresselement.labelsread only re
turns nodelist containing the list of <label> elements that are labels for this element. methods no specific method; inherits properties from its parent, htmlelement. specifications specificat...
HTMLSelectElement.form - Web APIs
for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. ...
...for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. ...
...for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. ...
HTMLTableRowElement - Web APIs
domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of the element's contents with respect to the surrounding context. the possible values are "left", "right", and "center". htmltablerowelement.bgcolor is a domstring containing the background color of the cells. it reflects the obsolete bgcolor attribute. htmltablerowelement.cells read only re
turns a live htmlcollection containing the cells in the row. the htmlcollection is live and is automatically updated when cells are added or removed. htmltablerowelement.ch is a domstring containing one single character. this character is the one to align all the cell of a column on. it reflects the char and default to the decimal points associated with the language, e.g. '.' for english, or ',' f...
...erty was optional and was not very well supported. htmltablerowelement.choff is a domstring containing a integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by htmltablerowelement.ch. this property was optional and was not very well supported. htmltablerowelement.rowindex read only re
turns a long value which gives the logical position of the row within the entire table. if the row is not part of a table, re
turns -1. htmltablerowelement.sectionrowindex read only re
turns a long value which gives the logical position of the row within the table section it belongs to. if the row is not part of a section, re
turns -1. htmltablerowelement.valign is a domstring representing an enum...
...omexception with the indexsizeerror value. htmltablerowelement.insertcell() inserts a new cell just before the given position in the row. if the given position is not given or is -1, it appends the cell to the row. if the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than -1, it raises a domexception with the indexsizeerror value. re
turns a reference to a htmltablecellelement [en-us]. specifications specification status comment html living standardthe definition of 'htmltablerowelement' in that specification. living standard html5the definition of 'htmltablerowelement' in that specification. recommendation the parameter of insertcell is now optional and default to -1. doc...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
example this example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
... example this example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
... example this example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. ...
The HTML DOM API - Web APIs
f the html dom that involve engaging with html elements. discussion of other areas, such as drag and drop, websockets, web storage, etc. can be found in the documentation for those apis. structure of an html document the document object model (dom) is an architecture that describes the structure of a document; each document is represented by an instance of the interface document. a document, in
turn, consists of a hierarchical tree of nodes, in which a node is a fundamental record representing a single object within the document (such as an element or text node). nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. each node is ba...
...html element classes inherit from. this expands the element class to add html-specific general features to the element nodes. properties added by htmlelement include for example hidden and innertext. htmlelement also adds all the global event handlers. an html document is a dom tree in which each of the nodes is an html element, represented by the htmlelement interface. the htmlelement class, in
turn, implements node, so every element is also a node (but not the other way around). this way, the structural features implemented by the node interface are also available to html elements, allowing them to be nested within each other, created and deleted, moved around, and so forth. the htmlelement interface is generic, however, providing only the functionality common to all html elements such as ...
...t: the ability to receive and handle events such as mouse clicks, play and pause events, and so forth. there are elements that share commonalities and thus have an additional intermediary type. for example, the <audio> and <video> elements both present audiovisual media. the corresponding types, htmlaudioelement and htmlvideoelement, are both based upon the common type htmlmediaelement, which in
turn is based upon htmlelement and so forth. htmlmediaelement defines the methods and properties held in common between audio and video elements. these element-specific interfaces make up the majority of the html dom api, and are the focus of this article. to learn more about the actual structure of the dom, see introduction to the dom. html dom target audience the features exposed by the html dom ...
Ajax navigation example - Web APIs
html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { re
turn; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: vmsg = json.parse(this.responsetext); document.title = opageinfo.title = vmsg.page; document.getelementbyid(starge...
... break; case 5: /* server error 5xx */ alert("server error #" + vmsg); break; default: /* unknown status */ ajaxerror(); } } closereq(); } function filterurl (surl, sviewmode) { re
turn surl.replace(rsearch, "") + ("?" + surl.replace(rhost, "&").replace(rview, sviewmode ? "&" + sviewkey + "=" + sviewmode : "").slice(1)).replace(rendqstmark, ""); } function getpage (spage) { if (bisloading) { re
turn; } oreq = new xmlhttprequest(); bisloading = true; oreq.onload = ajaxload; oreq.onerror = ajaxerror; if (spage) { opageinfo.ur...
...endchild(oloadingbox); } function requestpage (surl) { if (history.pushstate) { bupdateurl = true; getpage(surl); } else { /* ajax navigation is not supported */ location.assign(surl); } } function processlink () { if (this.classname === sajaxclass) { requestpage(this.href); re
turn false; } re
turn true; } function init () { opageinfo.title = document.title; history.replacestate(opageinfo, opageinfo.title, opageinfo.url); for (var olink, nidx = 0, nlen = document.links.length; nidx < nlen; document.links[nidx++].onclick = processlink); } const /* customizable constants */ stargetid = "ajax-content", s...
IDBDatabase - Web APIs
ted database. idbdatabase.version read only a 64-bit integer that contains the version of the connected database. when a database is first created, this attribute is an empty string. idbdatabase.objectstorenames read only a domstringlist that contains a list of the names of the object stores currently in the connected database. methods inherits from: eventtarget idbdatabase.close() re
turns immediately and closes the connection to a database in a separate thread. idbdatabase.createmutablefile() creates a file handle, allowing files to be stored inside an indexeddb database. idbdatabase.createobjectstore() creates and re
turns a new object store or index. idbdatabase.deleteobjectstore() destroys the object store with the given name in the connected database, along with any inde...
...runs in a separate thread. ...
...isten to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort fired when when a transaction is aborted and bubbles up to the connection object. also available via the onabort property. close fired when the database connection is unexpectedly closed. also available via the onclose property. error fired when a request re
turns 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 upgrad...
IDBIndex.count() - Web APIs
exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. ...
... exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. dataerror the key or key range provided contains an invalid key. ...
... invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. myindex.count() is then used to count the number of records in the index, and the result of that request is logged to the console when its success callback re
turns. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live...
IDBIndex.openCursor() - Web APIs
the method sets the position of the cursor to the appropriate record, based on the specified direction. if the key range is not specified or is null, then the range includes all the records. a success event is always fired on the result object. if at least one record matches the key range, then the result property of the event is set to the new idbcursorwithvalue object; the value of the cursor object is set to a structured clone of the referenced value. if no records match the key range then then the result property of the event is set to null. ...
... = myindex.opencursor(); var request = myindex.opencursor(range); var request = myindex.opencursor(range, direction); parameters range optional a key or idbkeyrange to use as the cursor's range. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional the cursor's direction. see idbcursor constants for possible values. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbindex's transaction is inactive. typeerror the value for the direction parameter is invalid. dataerror the key or...
... invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using opencursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.obj...
IDBObjectStore.put() - Web APIs
the put() method of the idbobjectstore interface updates a given record in a database, or inserts a new record if the given item does not already exist. it re
turns an idbrequest object, and, in a separate thread, creates a structured clone of the value and stores the cloned value in the object store. this is for adding new records, or updating existing records in an object store when the transaction's mode is readwrite. if the record is successfully stored, then a success event is fired on the re
turned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. the put method is an update or insert method. see the idbobjectstore.add method for an insert only method. bear in mind that if you have a i...
...h to update (or insert). key optional the primary key of the record you want to update (e.g. from idbcursor.primarykey). this is only needed for object stores that have an autoincrement primary key, therefore the key is not in a field on the record object. in such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. ...
...ple, see our to-do notifications app (view example live.) const title = "walk dog"; // open up a transaction as usual const objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title const objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = () => { // grab the data object re
turned as the result const data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back into the database const updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this request is " + updateti...
IDBRequest.transaction - Web APIs
if a version upgrade is needed when opening a database then during the upgradeneeded event handler the transaction property will be an idbtransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the the upgrade. following the upgrade, the transaction property will again be null. ...
...if a version upgrade is needed when opening a database then during the upgradeneeded event handler the transaction property will be an idbtransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the the upgrade. following the upgrade, the transaction property will again be null. ...
...mple, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this request is " + updatet...
ImageCapture.getPhotoCapabilities() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
...ture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
... working draft initial definition. ...
ImageCapture.getPhotoSettings() - Web APIs
imageheight: the desired image height as an integer. the user agent selects the closest width value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. the user agent selects the closest width value to this setting if it only supports discrete widths. ...
...pture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
... working draft initial definition. ...
InstallEvent - Web APIs
px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">installevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object. properties inherits properties from its ancestor, event. installevent.activeworker read only re
turns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passe...
...}; self.addeventlistener('install', function(event) { var urlstoprefetch = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
...ch = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
compareVersion - Web APIs
/royalsw. note that the registry pathname is not the location of the software on the computer; it is the location of information about the software inside the client version registry. version an installversion object containing version information or a string in the format major.minor.release.build, where major, minor, release, and build are integer values representing version information. re
turns if the versions are the same or if software installation is not enabled, this method re
turns 0. if the version of registryname is smaller (earlier) than version, this method re
turns a negative number. otherwise, this method re
turns a positive number. in particular, this method re
turns one of the following values: -5 component not present or not registered. -4 registryname has a smaller (e...
... 0 the version numbers are the same; both objects represent the same version. 1 registryname has a larger (newer) build number than version. 2 registryname has a larger (newer) release number than version. 3 registryname has a larger (newer) minor number than version. 4 registryname has a larger (newer) major number than version. ...
...egistryname has a larger (newer) minor number than version. 4 registryname has a larger (newer) major number than version. the following constants can be used to check the value re
turned by compareversion: int major_diff = 4; int minor_diff = 3; int rel_diff = 2; int bld_diff = 1; int equal = 0; in communicator 4.5, the following constants are defined and available for checking the value re
turned by compareversion: <code>installtrigger.major_diff installtrigger.minor_diff installtrigger.rel_diff installtrigger.bld_diff installtrigger.equal </code> description the compareversion method compares the version of an installed file or package with a specified version. it is often used as a check against which to initiate the installation process. if registryname is not found in the client...
IntersectionObserver - Web APIs
nt whose bounds are used as the bounding box when testing for intersection. if no root value was passed to the constructor or its value is null, the top-level document's viewport is used. intersectionobserver.rootmargin read only an offset rectangle applied to the root's bounding box when calculating intersections, effectively shrinking or growing the root for calculation purposes. the value re
turned by this property may not be the same as the one specified when calling the constructor as it may be changed to match internal requirements. each offset can be expressed in pixels (px) or as a percentage (%). the default is "0px 0px 0px 0px". intersectionobserver.thresholds read only a list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area...
...et. notifications for a target are generated when any of the thresholds are crossed for that target. if no value was passed to the constructor, 0 is used. methods intersectionobserver.disconnect() stops the intersectionobserver object from observing any target. intersectionobserver.observe() tells the intersectionobserver a target element to observe. intersectionobserver.takerecords() re
turns an array of intersectionobserverentry objects for all observed targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element. examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionra...
...f intersectionobserverentry objects for all observed targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element. examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionratio <= 0) re
turn; loaditems(10); console.log('loaded new items'); }); // start observing intersectionobserver.observe(document.queryselector('.scrollerfooter')); specifications specification status comment intersection observerthe definition of 'intersectionobserver' in that specification. working draft ...
IntersectionObserverEntry - Web APIs
api describes the intersection between the target element and its root container at a specific moment of transition. instances of intersectionobserverentry are delivered to an intersectionobserver callback in its entries parameter; otherwise, these objects can only be obtained by calling intersectionobserver.takerecords(). ...
...ameter; otherwise, these objects can only be obtained by calling intersectionobserver.takerecords(). properties intersectionobserverentry.boundingclientrect read only re
turns the bounds rectangle of the target element as a domrectreadonly. the bounds are computed as described in the documentation for element.getboundingclientrect(). intersectionobserverentry.intersectionratio read only re
turns the ratio of the intersectionrect to the boundingclientrect. intersectionobserverentry.intersectionrect read only re
turns a domrectreadonly representing the target's visible area. intersectionobserverentry.isintersecting read only a boolean value which is true if the target element intersects with the intersection observer's root. if this is true, then, the intersectionobserverentry descri...
... intersectionobserverentry.isintersecting read only a boolean value which is true if the target element intersects with the intersection observer's root. if this is true, then, the intersectionobserverentry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting. intersectionobserverentry.rootbounds read only re
turns a domrectreadonly for the intersection observer's root. intersectionobserverentry.target read only the element whose intersection with the root changed. intersectionobserverentry.time read only a domhighrestimestamp indicating the time at which the intersection was recorded, relative to the intersectionobserver's time origin. methods this interface has no methods. specifications ...
Intersection Observer API - Web APIs
rectangle is determined like this: if the intersection root is the implicit root (that is, the top-level document), the root intersection rectangle is the viewport's rectangle. if the intersection root has an overflow clip, the root intersection rectangle is the root element's content area. otherwise, the root intersection rectangle is the intersection root's bounding client rectangle (as re
turned by calling getboundingclientrect() on it). the root intersection rectangle can be adjusted further by setting the root margin, rootmargin, when creating the intersectionobserver. the values in rootmargin define offsets added to each side of the intersection root's bounding box to create the final intersection root bounds (which are disclosed in intersectionobserverentry.rootbounds when the ca...
.... the threshold list is built programmatically in this example since there are a number of them and the number is intended to be adjustable. once options is ready, we create the new observer, calling the intersectionobserver() constructor, specifying a function to be called when intersection crosses one of our thresholds, handleintersect(), and our set of options. we then call observe() on the re
turned observer, passing into it the desired target element. we could opt to monitor multiple elements for visibility intersection changes with respect to the viewport by calling observer.observe() for each of those elements, if we wanted to do so. building the array of threshold ratios the buildthresholdlist() function, which builds the list of thresholds, looks like this: function buildthreshold...
...erver.observe() for each of those elements, if we wanted to do so. building the array of threshold ratios the buildthresholdlist() function, which builds the list of thresholds, looks like this: function buildthresholdlist() { let thresholds = []; let numsteps = 20; for (let i=1.0; i<=numsteps; i++) { let ratio = i/numsteps; thresholds.push(ratio); } thresholds.push(0); re
turn thresholds; } this builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value i/numsteps onto the thresholds array for each integer i between 1 and numsteps. it also pushes 0 to include that value. the result, given the default value of numsteps (20), is the following list of thresholds: # ratio # ratio 1 0.05 11 0.55 ...
KeyboardEvent.location - Web APIs
possible values are: constant value description dom_key_location_standard 0 the key has only one version, or can't be distinguished between the left and right versions of the key, and was not pressed on the numeric keypad or a key that is considered to be part of the keypad. dom_key_location_left 1 the key was the left-hand version of the key; for example, the left-hand control key was pressed on a standard 101 key us keyboard. this value is only used for keys that have more than one possible location on the keyboard. ...
...hand version of the key; for example, the right-hand control key is pressed on a standard 101 key us keyboard. this value is only used for keys that have more than one possible location on the keyboard. dom_key_location_numpad 3 the key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad. note: when numlock is locked, gecko always re
turns dom_key_location_numpad for the keys on the numeric pad. otherwise, when numlock is unlocked and the keyboard actually has a numeric keypad, gecko always re
turns dom_key_location_numpad too. on the other hand, if the keyboard doesn't have a keypad, such as on a notebook computer, some keys become numpad only when numlock is locked. when such keys fires key events, the location attribute value de...
...e location attribute value depends on the key. that is, it must not be dom_key_location_numpad. note: numlock key's key events indicate dom_key_location_standard both on gecko and internet explorer. dom_key_location_mobile obsolete since gecko 38 4 the key was on a mobile device; this can be on either a physical keypad or a virtual keyboard. note: gecko always re
turns dom_key_location_mobile on android (prior to 18) and maemo. however, at gecko 38, this is dropped. dom_key_location_joystick obsolete since gecko 38 5 the key was a button on a game controller or a joystick on a mobile device. note: gecko never fires trusted key events with dom_key_location_joystick except on android. starting 18, native key events on android may ha...
KeyboardLayoutMap.get() - Web APIs
example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
... example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
... example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
KeyboardLayoutMap - Web APIs
the keyboardlayoutmap interface of the the keyboard api is a map-like object with functions for retrieving the string associated with specific physical keys. a list of valid keys is found in the ui events keyboardevent code values specification. properties keyboardlayoutmap.entries read only re
turns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). keyboardlayoutmap.keys read only re
turns a new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only re
turns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read o...
...that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). keyboardlayoutmap.keys read only re
turns a new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only re
turns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only re
turns a new array iterator object that contains the values for each index in the keyboardlayoutmap object. methods keyboardlayoutmap.foreach() read only executes a provided function once for each element of keyboardlayoutmap. ...
...layoutmap.size read only re
turns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only re
turns a new array iterator object that contains the values for each index in the keyboardlayoutmap object. methods keyboardlayoutmap.foreach() read only executes a provided function once for each element of keyboardlayoutmap. keyboardlayoutmap.get() re
turns the element with the given key from the keyboardlayoutmap object. keyboardlayoutmap.has() re
turns a boolean indicating whether the keyboardlayoutmap object has an element with the specified key. examples the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. var keyboard ...
Location - Web APIs
n (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.hash = ''; }); }); result properties location.ancestororigins is a static domstringlist containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given location object. location.href is a stringifier that re
turns a usvstring containing the entire url. if changed, the associated document navigates to the new page. it can be set from a different origin than the associated document. location.protocol is a usvstring containing the protocol scheme of the url, including the final ':'. location.host is a usvstring containing the host, that is the hostname, a ':', and the port of the url. location.hostname ...
...al '/' followed by the path of the url. location.search is a usvstring containing a '?' followed by the parameters or "querystring" of the url. modern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. location.hash is a usvstring containing a '#' followed by the fragment identifier of the url. location.origin read only re
turns a usvstring containing the canonical form of the origin of the specific location. methods location.assign() loads the resource at the url provided in parameter. location.reload() reloads the current url, like the refresh button. location.replace() replaces the current resource with the one at the provided url (redirects to the provided url). the difference from the assign() method and ...
... url, like the refresh button. location.replace() replaces the current resource with the one at the provided url (redirects to the provided url). the difference from the assign() method and setting the href property is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the back button to navigate to it. location.tostring() re
turns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can't be used to modify the value. examples // create anchor element and use href property for the purpose of this example // a more correct alternative is to browse to the url and use document.location or window.location var url = document.createelement('a'); url.href = 'https://developer.mozi...
LockedFile - Web APIs
lockedfile.oncomplete the complete event is triggered each time a read or write operation is successful. lockedfile.onabort the abort event is triggered each time the abort() method is called. lockedfile.onerror the error event is triggered each time something goes wrong. methods lockedfile.getmetadata() allows to retrieve the file metadata (size and date of the last modification). re
turns a filerequest. lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer. re
turns a filerequest object. lockedfile.readastext() allows to retrieve a part of the content of the file as a string. re
turns a filerequest object. lockedfile.write() allows to write some data in the file starting at the location offset. re
turns a filerequest object. loc...
... lockedfile.flush() allows to guarantee that any buffered data has been transferred to disk. lockedfile.abort() makes the lockedfile inactive and cancels all ongoing operations. ...
... lockedfile.flush() allows to guarantee that any buffered data has been transferred to disk. lockedfile.abort() makes the lockedfile inactive and cancels all ongoing operations. ...
MediaDeviceInfo - Web APIs
the mediadeviceinfo interface contains information that describes a single media input or output device. the list of devices obtained by calling navigator.mediadevices.enumeratedevices() is an array of mediadeviceinfo objects, one per media device. properties mediadeviceinfo.deviceidread only re
turns a domstring that is an identifier for the represented device that is persisted across sessions. it is un-guessable by other applications and unique to the origin of the calling application. it is reset when the user clears cookies (for private browsing, a different identifier is used that is not persisted across sessions). mediadeviceinfo.groupidread only re
turns a domstring that is a group identifier. two devices have the same group identifier if they belong to the same physical device ...
...when the user clears cookies (for private browsing, a different identifier is used that is not persisted across sessions). mediadeviceinfo.groupidread only re
turns a domstring that is a group identifier. two devices have the same group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone. mediadeviceinfo.kindread only re
turns an enumerated value that is either "videoinput", "audioinput" or "audiooutput". mediadeviceinfo.labelread only re
turns a domstring that is a label describing this device (for example "external usb webcam"). for security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. the set of device label...
...r has granted persistent permission for media device access. the set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user. methods none. example here's an example that uses enumeratedevices() to get a list of devices. if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); re
turn; } // list cameras and microphones. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+s...
MediaDevices.enumerateDevices() - Web APIs
each object in the array describes one of the available media input and output devices. if enumeration fails, the promise is rejected. example here's an example of using enumeratedevices(). ...
...each object in the array describes one of the available media input and output devices. if enumeration fails, the promise is rejected. example here's an example of using enumeratedevices(). ...
...ach object in the array describes one of the available media input and output devices. if enumeration fails, the promise is rejected. example here's an example of using enumeratedevices(). it simply outputs a list of the device ids, with their labels if available. if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); re
turn; } // list cameras and microphones. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+s...
MediaDevices.ondevicechange - Web APIs
the fulfillment handler is called when the device list is ready. the list is passed into the fulfillment handler as an array of mediadeviceinfo objects, each describing one media input or output device. a foreach() loop is used to scan through all the devices. for each device, we create a new <li> object to be used to display it to the user. the line let [k...
...put or output device. a foreach() loop is used to scan through all the devices. for each device, we create a new <li> object to be used to display it to the user. the line let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); deserves special notice. this uses destructuring assignment (a new feature of ecmascript 6) to assign the values of the first three items in the array re
turned by string.match() to the variables kind, type, and direction. we do this because the value of mediadeviceinfo.kind is a single string that includes both the media type and the direction the media flows, such as "audioinput" or "videooutput". this line, then, pulls out the type ("audio" or "video") and direction ("input" or "output") so they can be used to construct the string displayed in the l...
...all updatedevicelist() in two places. the first is in the getusermedia() promise's fulfillment handler, to initially fill out the list when the stream is opened. the second is in the event handler for devicechange: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } with this code in place, each time the user plugs in a camera, microphone, or other media device, or
turns one on or off, we call updatedevicelist() to redraw the list of connected devices. result specifications specification status comment media capture and streamsthe definition of 'ondevicechange' in that specification. candidate recommendation initial specification. ...
MediaKeyStatusMap - Web APIs
the mediakeystatusmap interface of the encryptedmediaextensions api is a read-only map of media key statuses by key ids. properties mediakeystatusmap.size read only re
turns the number of key/value pars in the status map. methods mediakeystatusmap.entries() read only re
turns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order. mediakeystatusmap.foreach(callback[, argument]) read only calls callback once for each key-value pair in the status map, in insertion order. if argument is present it will be passed to the callback. ...
...iakeystatusmap.entries() read only re
turns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order. mediakeystatusmap.foreach(callback[, argument]) read only calls callback once for each key-value pair in the status map, in insertion order. if argument is present it will be passed to the callback. mediakeystatusmap.get() read only re
turns the value associated with the given key, or undefined if there is none. mediakeystatusmap.has() read only re
turns a boolean asserting whether a value has been associated with the given key. mediakeystatusmap.keys() read only re
turns a new iterator object containing keys for each element in the status map, in insertion order. ...
...et() read only re
turns the value associated with the given key, or undefined if there is none. mediakeystatusmap.has() read only re
turns a boolean asserting whether a value has been associated with the given key. mediakeystatusmap.keys() read only re
turns a new iterator object containing keys for each element in the status map, in insertion order. mediakeystatusmap.values() read only re
turns a new iterator object containing values for each element in the status map, in insertion order. mediakeystatusmap.[@@iterator]() read only re
turns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order. specifications specification status comment encrypted media extensionsthe definition of 'mediakeystatusmap'...
MediaRecorder.mimeType - Web APIs
this is the file format of the file that would result from writing all of the recorded data to disk. keep in mind that not all codecs are supported by a given container; if you write media using a codec that is not supported by a given media container, the resulting file may not work reliably if at all when you try to play it back. see our media type and format guide for information about container and codec support across browsers. note: the term "mime type" is officially considered to be historical; these strings are now officially known as media types. ...
... }) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assu...
...ole.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value re
turned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2". specifications specification status comment mediastream recordingthe definition of 'mediarecorder.mimetype' in that specification. working draft initial definition ...
MediaRecorder.onerror - Web APIs
aavailable event is sent to the mediarecorder with the remaining received data, and finally a stop event is sent. these errors may occur either directly because of a call to a mediarecorder method, or indirectly due to a problem arising during the recording process. example this example creates a new mediarecorder instance and starts recording using the user agent's default media format. ...
...this example creates a new mediarecorder instance and starts recording using the user agent's default media format. it re
turns either the mediarecorder or the name of the error that occurred if any exceptions are thrown during the setup process. function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { re
turn err.name; /* re
turn the error name */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; switch(error.name) { case invalidstateerror: shownotification("you can't record the video right " + "now. try again later."); break; case se...
... working draft initial definition ...
MediaSettingsRange - Web APIs
the mediasettingsrange interface of the the mediastream image capture api provides the possible range and value size of photocapabilities.imageheight and photocapabilities.imagewidth. a photocapabilities object can be retrieved by calling imagecapture.photocapabilities(). properties mediasettingsrange.max re
turns the maximum value of this settings. mediasettingsrange.min re
turns the minimum value of this setting. mediasettingsrange.step re
turns the minimum difference between consecutive values of this setting. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range. const input = document.queryselector('input[type="range"]'); var imagecaptu...
... results from getphotocapabilities().imagewidth to modify the size of an input range. ...
... working draft initial definition. ...
MediaSource - Web APIs
...
... containing the list of sourcebuffer objects associated with this mediasource. mediasource.activesourcebuffers read only re
turns a sourcebufferlist object containing a subset of the sourcebuffer objects contained within mediasource.sourcebuffers — the list of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks. mediasource.readystate read only re
turns an enum representing the state of the current mediasource, whether it is not currently attached to a media element (closed), attached and ready to receive sourcebuffer objects (open), or attached but the stream has been ended via mediasource.endofstream() (ended.) mediasource.duration gets and sets the duration of the current media being presented. event handlers mediasource.onsourceclose...
...) clears a seekable range previously set with a call to setliveseekablerange(). mediasource.endofstream() signals the end of the stream. mediasource.removesourcebuffer() removes the given sourcebuffer from the mediasource.sourcebuffers list. mediasource.setliveseekablerange() sets the range that the user can seek to in the media element. static methods mediasource.istypesupported() re
turns a boolean value indicating if the given mime type is supported by the current user agent — this is, if it can successfully create sourcebuffer objects for that mime type. examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. this example was written by nick desaulniers and can be viewed live here (you can also download the source for further ...
MediaStreamTrack.getConstraints() - Web APIs
these constraints indicate values and ranges of values that the web site or application has specified are required or acceptable for the included constrainable properties. constraints can be used to ensure that the media meets certain guidelines you prefer. for example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. ...
...r. for example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. constraints can also specify ideal and/or acceptable sizes or ranges of sizes. see capabilities, constraints, and settings for details on how to work with constrainable properties. ...
...can also specify ideal and/or acceptable sizes or ranges of sizes. see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const constraints = track.getconstraints() re
turn value a mediatrackconstraints object which indicates the constrainable properties the web site or app most recently set using applyconstraints(). the properties in the re
turned object are listed in the same order as when they were set, and only properties specifically set by the site or app are included. note: the re
turned set of constraints doesn't necessarily describe the actual state of the media. even if any of the constraints couldn't be met, they are still included in the re
turned object as originally set by the site's code. to get the currently active setting...
MediaTrackConstraints.cursor - Web APIs
s dictionary's cursor property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the cursor constrainable property, which is used to specify whether or not the cursor should be included in the captured video. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.cursor as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { cursor: constraint }; constraintsobject.cursor = constraint; value a constraindomstring which specifies whether or not the mouse cursor should be rendered into the video track in the mediastr...
...a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...
turned by the call to getdisplaymedia(). see how constraints are defined in capabilities, constraints, and settings for an explanation of how to define constraints. usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the re
turned mediatracksettings object's cursor object. for example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag = tr...
Using the Media Capabilities API - Web APIs
you can, therefore, test for the presence of the api like so: if ("mediacapabilities" in navigator) { // mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo() method. this re
turns a promise that fulfills with information about the media capabilities as to whether the video can be decoded, and whether decoding will be smooth and power efficient. you can also test audio decoding as well as video and audio encoding. creating a video decoding configuration the mediacapabilities.decodinginfo() method takes as a parameter a media decoding configuration. there are very specifi...
...r about decoding abilities now that we've created a video decoding configuration we can pass it as a paramater of the decodinginfo() method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient. ...
...fficient. var promise = navigator.mediacapabilities.decodinginfo(videoconfiguration); the decodinginfo() and encodinginfo() methods both re
turn promises. once the promises state is fulfilled, you can access the mediacapabilitiesinfo interface's supported, smooth, and powerefficient properties. ...
MouseEvent.region - Web APIs
example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method. ...
... example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method. ...
... example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method. ...
Navigation Timing API - Web APIs
the client side, which you can then transmit to a server using xmlhttprequest or other techniques. this api lets you measure data that was previously difficult to obtain, such as the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and so forth. interfaces performance the window.performance property re
turns a performance object. while this interface is defined by the high resolution time api, the navigation timing api adds two properties: timing and navigation, of the types below. performancenavigationtiming provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. for example, this interface can be used to determine how much time it takes t...
...s to store and retrieve metrics regarding the browser's document navigation events. for example, this interface can be used to determine how much time it takes to load or unload a document. performancetiming used as the type for the value of timing, objects of this type contain timing information that can provide insight into web page performance. performancenavigation the type used to re
turn the value of navigation, which contains information explaining the context of the load operation described by this performance instance. the navigation timing api can be used to gather performance data on the client side to be sent to a server via xhr as well as measure data that was very difficult to measure by other means such as time to unload a previous page, domain look up time, window.onl...
....onload total time, etc. examples calculate the total page load time to compute the total amount of time it took to load the page, you can use the following code: const perfdata = window.performance.timing; const pageloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler re
turns (loadeventend). this gives you the perceived page load time. calculate request response time you can calculate the time elapsed between the beginning of a request and the completion of getting the response using code like this: const connecttime = perfdata.responseend - perfdata.requeststart; here, the time at which the request was initiated (requeststart). from the time at which the respons...
Navigator.cookieEnabled - Web APIs
note: web browsers may prevent writing certain cookies in certain scenarios. for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute. ...
... note: web browsers may prevent writing certain cookies in certain scenarios. for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute. ...
...es are enabled or not. the property is read-only. syntax var cookieenabled = navigator.cookieenabled; cookieenabled is a boolean: true or false. note: when the browser is configured to block third-party cookies, and navigator.cookieenabled is invoked inside a third-party iframe, it re
turns true in safari, edge spartan and ie (while trying to set a cookie in such scenario would fail). it re
turns false in firefox and chromium-based browsers. note: web browsers may prevent writing certain cookies in certain scenarios. for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute. example if (!navigator.cookieenabled) { // the browser does not support or is blocking cookies from being set. } specifi...
NavigatorID - Web APIs
the navigatorid interface contains methods and properties related to the identity of the browser. there is no object of type navigatorid, but other interfaces, like navigator or workernavigator, implement it. properties the navigatorid interface doesn't inherit any properties. navigatorid.appcodename read only always re
turns "mozilla", in any browser. this property is kept only for compatibility purposes. ...
...lated to the identity of the browser. there is no object of type navigatorid, but other interfaces, like navigator or workernavigator, implement it. properties the navigatorid interface doesn't inherit any properties. navigatorid.appcodename read only always re
turns "mozilla", in any browser. this property is kept only for compatibility purposes. navigatorid.appname read only always re
turns "netscape", in any browser. this property is kept only for compatibility purposes. navigatorid.appversion read only re
turns either "4.0" or a string representing version information about the browser. do not rely on this property to re
turn a useful value. navigatorid.platform read only re
turns either the empty string or a string representing the platform the browser is running on. do not r...
...er. this property is kept only for compatibility purposes. navigatorid.appversion read only re
turns either "4.0" or a string representing version information about the browser. do not rely on this property to re
turn a useful value. navigatorid.platform read only re
turns either the empty string or a string representing the platform the browser is running on. do not rely on this property to re
turn a useful value. navigatorid.product read only always re
turns "gecko", in any browser. this property is kept only for compatibility purposes. navigatorid.useragent read only re
turns the user-agent string for the current browser. methods the navigatorid interface doesn't inherit any methods. navigatorid.taintenabled() always re
turns false. javascript taint/untaint functions were remo...
NavigatorPlugins.mimeTypes - Web APIs
re
turns a mimetypearray object, which contains a list of mimetype objects representing the mime types recognized by the browser. note: named properties of mimetypearray objects are no longer enumerable in the latest browser versions. syntax var mimetypes[] = navigator.mimetypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods. ...
...ns a list of mimetype objects representing the mime types recognized by the browser. note: named properties of mimetypearray objects are no longer enumerable in the latest browser versions. syntax var mimetypes[] = navigator.mimetypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods. ...
...etypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods. example function isjavapresent() { re
turn 'application/x-java-applet' in navigator.mimetypes; } function getjavaplugindescription() { var mimetype = navigator.mimetypes['application/x-java-applet']; if (mimetype === undefined) { // no java plugin present re
turn undefined; } re
turn mimetype.enabledplugin.description; } specifications specification status comment html living standardthe definition of 'navigatorplugins.mimetypes' in that specification. living standard initial definition. ...
NavigatorPlugins.plugins - Web APIs
re
turns a pluginarray object, listing the plugin objects describing the plugins installed in the application. in firefox 29 and later, enumeration of the navigator.plugins array may be restricted as a privacy measure. applications that must check for the presence of a browser plugin should query navigator.plugins or navigator.mimetypes by exact name instead of enumerating the navigator.plugins array and comparing every plugin's name. this privacy change does not disable any plugins; it just hides some plugin names from enumeration. syntax var plugins = navigator.plugins; plugins is pluginarray object used to access plugin objects either by name or as a list of items. ...
...ld query navigator.plugins or navigator.mimetypes by exact name instead of enumerating the navigator.plugins array and comparing every plugin's name. this privacy change does not disable any plugins; it just hides some plugin names from enumeration. syntax var plugins = navigator.plugins; plugins is pluginarray object used to access plugin objects either by name or as a list of items. the re
turned value is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. examples the following example function re
turns the version of the shockwave flash plugin. function getflashversion() { var flash = navigator.plugins.nameditem('shockwave flash'); if (typeof fla...
...th property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. examples the following example function re
turns the version of the shockwave flash plugin. function getflashversion() { var flash = navigator.plugins.nameditem('shockwave flash'); if (typeof flash != 'object') { // flash is not present re
turn undefined; } if(flash.version){ re
turn flash.version; } else { //no version property (e.g. in chrome) re
turn flash.description.replace(/shockwave flash /,""); } } the following example displays information about the installed plugin(s). var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><the...
Node.localName - Web APIs
in dom4 this api was moved from node to the element and attr interfaces. ...
...cular xml documents. ...
...:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partners> </ecomm:business> note: in gecko 1.9.2 and earlier, the property re
turns the upper-cased version of the local name for html elements in html doms (as opposed to xhtml elements in xml doms). in later versions, in compliance with html5, the property re
turns in the case of the internal dom storage, which is lower case for both html elements in html doms and xhtml elements in xml doms. the tagname property continues to re
turn in the upper case for html elements in html doms. for nodes of any type other than element_node and attribute_node localname is always null. specifications specification status comment document ob...
NodeFilter - Web APIs
filter. note: the browser doesn't provide any object implementing this interface. it is the user who is expected to write one, tailoring the acceptnode() method to its needs, and using it with some treewalker or nodeiterator objects. properties this interface neither implements nor inherits any properties. methods this interface doesn't inherit any methods. nodefilter.acceptnode() re
turns an unsigned short that will be used to tell if a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm. this method is expected to be written by the user of a nodefilter. possible re
turn values are: constant description filter_accept value re
turned by the nodefilter.acceptnode() method when a node should be accepted. ...
...f a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm. this method is expected to be written by the user of a nodefilter. possible re
turn values are: constant description filter_accept value re
turned by the nodefilter.acceptnode() method when a node should be accepted. filter_reject value to be re
turned by the nodefilter.acceptnode() method when a node should be rejected. for treewalker, child nodes are also rejected. for nodeiterator, this flag is synonymous with filter_skip. filter_skip value to be re
turned by nodefilter.acceptnode() for nodes to be skipped by the nodeiterator or treewalker object. the children of skipped nodes are still considered. this i...
... living standard document object model (dom) lev...
NodeIterator.previousNode() - Web APIs
the nodeiterator.previousnode() method re
turns the previous node in the set represented by the nodeiterator and moves the position of the iterator backwards within the set. this method re
turns null when the current node is the first node in the set. in old browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is called after the nodeiterator.detach()method. recent browsers never throw. ...
...rowsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is called after the nodeiterator.detach()method. recent browsers never throw. ...
...ed after the nodeiterator.detach()method. recent browsers never throw. syntax node = nodeiterator.previousnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // re
turns the next node previousnode = nodeiterator.previousnode(); // same result, since we backtracked to the previous node specifications specification status comment domthe definition of 'nodeiterator.previousnode' in that specification. living standard as detach() is now a no-op method, this method cannot throw anymore. document object model (dom) level 2 tra...
NotificationEvent - Web APIs
ick handler, the notificationevent interface represents a notification click event that is dispatched on the serviceworkerglobalscope of a serviceworker. this interface inherits from the extendableevent interface. constructor notificationevent() creates a new notificationevent object. properties inherits properties from its ancestor, event. notificationevent.notification read only re
turns a notification object representing the notification that was clicked to fire the event. notificationevent.action read only re
turns the string id of the notification button the user clicked. this value re
turns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. methods inherits methods from its parent, exten...
... living standard living standard. note: this interface is specified in the notifications api, but accessed through serviceworkerglobal...
... living standard living standard. note: this interface is specified in the notifications api, but accessed through serviceworkerglobalscope. browser compatibility the compatibility table on thi...
OffscreenCanvas - Web APIs
interface provides a canvas that can be rendered off screen. it is available in both the window and worker contexts. constructors offscreencanvas() offscreencanvas constructor. creates a new offscreencanvas object. properties offscreencanvas.height the height of the offscreen canvas. offscreencanvas.width the width of the offscreen canvas. methods offscreencanvas.getcontext() re
turns a rendering context for the offscreen canvas. offscreencanvas.converttoblob() creates a blob object representing the image contained in the canvas. offscreencanvas.transfertoimagebitmap() creates an imagebitmap object from the most recently rendered image of the offscreencanvas. examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas...
... offscreencanvas. examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate new frames. once a new frame has finished rendering in this context, the transfertoimagebitmap() method can be called to save the most recent rendered image. this method re
turns an imagebitmap object, which can be used in a variety of web apis and also in a second canvas without creating a transfer copy. to display the imagebitmap, you can use a imagebitmaprenderingcontext context, which can be created by calling canvas.getcontext("bitmaprenderer") on a (visible) canvas element. this context only provides functionality to replace the canvas's contents with the given im...
...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 re
turn an offscreencanvas object from an htmlcanvaselement object from the main thread. calling getcontext() will then obtain a renderingcontext from that offscreencanvas. main.js (main thread code): var htmlcanvas = document.getelementbyid("canvas"); var offscreen = htmlcanvas.transfercontroltooffscreen(); var worker = new worker("offscreencanvas.js"); worker.postmessage({canvas: offscreen}, [offscr...
ParentNode.children - Web APIs
syntax let children = node.children; value an htmlcollection which is a live, ordered collection of the dom elements which are children of node. you can access the individual child nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation. if the node has no element children, then children is an empty list with a length of 0. ...
...or by using javascript array-style notation. if the node has no element children, then children is an empty list with a length of 0. example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype. // adds document & documentfragment support for ie9 & safari. // re
turns array instead of htmlcollection. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { object.defineproperty(constructor.prototype, 'children', { get: function() { let i = 0, node, nodes = this.childnodes, children = []; while (node = nodes[i++]) { if (node.nodetype === 1) { childr...
... living standard initial definition. ...
ParentNode.firstElementChild - Web APIs
this property was initially defined in the elementtraversal pure interface. as this interface contained two distinct set of properties, one aimed at node that have children, one at those that are children, they have been moved into two separate pure interfaces, parentnode and childnode. in this case, firstelementchild moved to parentnode. this is a fairly technical change that shouldn't affect compatibility. ...
... living standard split the elementtraversal interface in childnode and parentnode. this method is now defin...
... living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented t...
ParentNode.lastElementChild - Web APIs
note: this property was initially defined in the elementtraversal pure interface. as this interface contained two distinct set of properties, one aimed at node that have children, one at those that are children, they have been moved into two separate pure interfaces, parentnode and childnode. in this case, lastelementchild moved to parentnode. this is a fairly technical change that shouldn't affect compatibility. ...
...ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // re
turns array instead of htmlcollection. ;(function(constructor) { if(constructor && constructor.prototype && constructor.prototype.lastelementchild == null) { object.defineproperty(constructor.prototype, 'lastelementchild', { get: function() { var node, nodes = this.childnodes, i = nodes.length - 1; while(node = nodes[i--]) { if(node.nodetype === 1) { ...
...nstead of htmlcollection. ;(function(constructor) { if(constructor && constructor.prototype && constructor.prototype.lastelementchild == null) { object.defineproperty(constructor.prototype, 'lastelementchild', { get: function() { var node, nodes = this.childnodes, i = nodes.length - 1; while(node = nodes[i--]) { if(node.nodetype === 1) { re
turn node; } } re
turn null; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.lastelementchild' in that specification. living standard splitted the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document a...
ParentNode - Web APIs
the parentnode mixin contains methods and properties that are common to all types of node objects that can have children. it's implemented by element, document, and documentfragment objects. see locating dom elements using selectors to learn how to use css selectors to find nodes or elements of interest. properties parentnode.childelementcount read only re
turns the number of children of this parentnode which are elements. parentnode.children read only re
turns a live htmlcollection containing all of the element objects that are children of this parentnode, omitting all of its non-element nodes. parentnode.firstelementchild read only re
turns the first node which is both a child of this parentnode and is also an element, or null if there is none. parentnode.lastelementchild read on...
... methods parentnode.append() inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. ...
... is none. methods parentnode.append() inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.prepend() inserts a set of node objects or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.queryselector() re
turns the first element with the current element as root that matches the specified group of selectors. parentnode.queryselectorall() re
turns a nodelist representing a list of elements with the current element as root that matches the specified group of selectors. parentnode.replacechildren() replaces the existing children of a node with a specified new set of children. specification s...
PaymentRequest.canMakePayment() - Web APIs
will let the user pay using payment request api, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by payment request api (or even provide instructions for paying by mail or by phone). syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch( error => { ... }) canpay = await paymentrequest.canmakepayment(); re
turns a promise to a boolean that resolves to 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 re
turned promise with a domexception. parameters none examples in the followin...
...entrquest() { const details = { total: { label: "total", amount: { currency: "usd", value: "0.00", }, }, }; const supportsapplepay = new paymentrequest( [{ supportedmethods: "https://apple.com/apple-pay" }], details ).canmakepayment(); // supports apple pay? ...
..., details ).canmakepayment(); // supports apple pay? if (await supportsapplepay) { // show apple pay logo, for instance re
turn; } // otherwise... let's see if we can use basic card const supportsbasiccard = await new paymentrequest( [{ supportedmethods: "basic-card" }], details ).canmakepayment(); if (supportsbasiccard) { // show basic card support re
turn; } // otherwise, make payments using html form element } specifications specification status comment payment request apithe definition of 'canmakepayment()' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to th...
PaymentRequest: merchantvalidation event - Web APIs
the validation url in accordance with the payment method documention. typically, a client should not access the validation url. ...
...this response lets the payment handler know if the merchant is validated. ...
...dler 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; re
turn await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. related events payerdetailchange, paymentmethodchange, shippingaddresschange, and shippingoptionchange specifications specification status comment payment request apithe defi...
PaymentRequest: paymentmethodchange event - Web APIs
entmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. the code assumes the existence of a method detailsforshipping(), which re
turns a paymentdetailsupdate object containing the shipping options for the ground shipping method, in the form found in the paymentshippingoption dictionary. by doing so, the payment form defaults to the ground shipping method. const options = { requestshipping: true }; const paymentrequest = new paymentrequest(paymentmethods, detailsforshipping("ground"), options); paymentrequest.addevent...
... related events merchantvalidation, shippingaddresschange, shippingoptionchange...
...unction called calculateservicefee(), which we might create to take the information about the transaction, such as the underlying credit card being used to service the apple pay request, and compute and re
turn an paymentdetailsupdate object that specifies changes to be applied to the paymentrequest in order to add any service fees that the payment method might require. before the event handler re
turns, it calls the event's paymentmethodchangeevent.updatewith.updatewith() method to integrate the changes into the request. related events merchantvalidation, shippingaddresschange, shippingoptionchange, and payerdetailchange specifications specification status comment payment request apithe definition of 'paymentmethodchange' in that specification. candidate recom...
PaymentRequest.shippingOption - Web APIs
the shippingoption read-only attribute of the paymentrequest interface re
turns either the id of a selected shipping option, null (if no shipping option was set to be selected) or a shipping option selected by the user. it is initially null by when no "selected" shipping options are provided. this attribute is only populated if the constructor is called with the requestshipping flag set to true. if requestshipping was false (or missing), shippingoption re
turns null, even the developer provides a selected a shipping option. syntax // re
turns 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 ...
... candidate recommendation initial definition. browser compatibility the compatibility table on thi...
... candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute...
PaymentResponse.details - Web APIs
in a real-world implementation this data would then be sent to a payment server. ...
...in a real-world implementation this data would then be sent to a payment server. ...
...in a real-world implementation this data would then be sent to a payment server. ...
performance.getEntries() - Web APIs
the items will be in chronological order based on the entries' starttime. ...
...(entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time. if you are only interested in performance entries of certain types or that have certain names, see getentriesbytype() and getentriesbyname(). note: this feature is available in web workers. ...
... general syntax: entries = window.performance.getentries(); re
turn value entries an array of performanceentry objects. the items will be in chronological order based on the entries' starttime. example function use_performanceentry_methods() { console.log("performanceentry tests ..."); if (performance.mark === undefined) { console.log("... ...
performance.getEntriesByName() - Web APIs
the getentriesbyname() method re
turns a list of performanceentry objects for the given name and type. the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time. note: this feature is available in web workers. syntax entries = window.performance.getentriesbyname(name, type); arguments name the name of the entry to retrieve. type optional the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. re
turn value entries a list of performanceentry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to re
turn. the items will be in chronological order bas...
... valid entry types are listed in performanceentry.entrytype. re
turn value entries a list of performanceentry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to re
turn. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is re
turned. example function use_performanceentry_methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
...ecified, only the name will be used to determine the entries to re
turn. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is re
turned. example function use_performanceentry_methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
performance.now() - Web APIs
the performance.now() method re
turns a domhighrestimestamp, measured in milliseconds. note: this feature is available in web workers. the re
turned value represents the time elapsed since the time origin. bear in mind the following points: in dedicated workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker. it used to be the same as t0 of the main context, but this was changed. in shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. ...
....now() in the window who spawned that worker. it used to be the same as t0 of the main context, but this was changed. in shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. it's important to keep in mind that to mitigate potential security threats such as spectre, browsers typically round the re
turned value by some amount in order to be less predictable. this inherently introduces a degree of inaccuracy by limiting the resolution or precision of the timer. for example, firefox rounds the re
turned time to 1 millisecond increments. the precision of the re
turned value is subject to change if/when the security concerns are alleviated through other means. syntax t = performance.now(); example...
... the precision of the re
turned value is subject to change if/when the security concerns are alleviated through other means. syntax t = performance.now(); example const t0 = performance.now(); dosomething(); const t1 = performance.now(); console.log(`call to dosomething took ${t1 - t0} milliseconds.`); unlike other timing data available to javascript (for example date.now), the timestamps re
turned by performance.now() are not limited to one-millisecond resolution. instead, they represent times as floating-point numbers with up to microsecond precision. also unlike date.now(), the values re
turned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like ntp). otherwise, performance.timing.navigati...
Performance - Web APIs
not available in workers. performance.timing read only a legacy performancetiming object containing latency-related performance information. not available in workers. performance.memory read only a non-standard extension added in chrome, this property provides an object with basic memory usage information. you should not use this non-standard api. performance.timeorigin read only re
turns the high resolution timestamp of the start time of the performance measurement. methods the performance interface doesn't inherit any methods. performance.clearmarks() removes the given mark from the browser's performance entry buffer. performance.clearmeasures() removes the given measure from the browser's performance entry buffer. performance.clearresourcetimings() removes all perfo...
...doesn't inherit any methods. performance.clearmarks() removes the given mark from the browser's performance entry buffer. performance.clearmeasures() removes the given measure from the browser's performance entry buffer. performance.clearresourcetimings() removes all performance entries with a entrytype of "resource" from the browser's performance data buffer. performance.getentries() re
turns a list of performanceentry objects based on the given filter. performance.getentriesbyname() re
turns a list of performanceentry objects based on the given name and entry type. performance.getentriesbytype() re
turns a list of performanceentry objects of the given entry type. performance.mark() creates a timestamp in the browser's performance entry buffer with the given name. performance.me...
...performance.getentriesbytype() re
turns a list of performanceentry objects of the given entry type. performance.mark() creates a timestamp in the browser's performance entry buffer with the given name. performance.measure() creates a named timestamp in the browser's performance entry buffer between two specified marks (known as the start mark and end mark, respectively). performance.now() re
turns a domhighrestimestamp representing the number of milliseconds elapsed since a reference instant. performance.setresourcetimingbuffersize() sets the browser's resource timing buffer size to the specified number of "resource" type performance entry objects. performance.tojson() is a jsonizer re
turning a json object representing the performance object. events listen to these events using add...
PerformanceEntry.name - Web APIs
value subtype entrytype values description url performanceframetiming, performancenavigationtiming frame, navigation the document's address. url performanceresourcetiming resource the resolved url of the requested resource. ...
... value subtype entrytype values description url performanceframetiming, performancenavigationtiming frame, navigation the document's address. url performanceresourcetiming resource the resolved url of the requested resource. ...
...sure was created by calling performance.measure(). domstring performancepainttiming paint either 'first-paint' or 'first-contentful-paint'. example the following example shows the use of the name property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
PerformanceEntry.startTime - Web APIs
the starttime property re
turns the first recorded timestamp of the performance entry. note: this feature is available in web workers. the value re
turned by this property depends on the performance entry's type: "frame" - re
turns the timestamp when the frame was started. "mark" - re
turns the timestamp when the mark was created by a call to performance.mark(). "measure" - re
turns the timestamp when the measure was created by a call to performance.measure(). "navigation" - re
turns the timestamp with a value of "0". "resource" - re
turns the timestamp immediately before the browser starts fetching the resource. this property is read only . syntax entry.starttime; re
turn value a domhighrestimestamp representing the first timestamp when the performance entry was created. note: if the...
... "resource" - re
turns the timestamp immediately before the browser starts fetching the resource. this property is read only . syntax entry.starttime; re
turn value a domhighrestimestamp representing the first timestamp when the performance entry was created. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property re
turns the performanceentry.fetchstart timestamp. example the following example shows the use of the starttime property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
... entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property re
turns the performanceentry.fetchstart timestamp. example the following example shows the use of the starttime property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
PerformanceResourceTiming.decodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged. ...
... example the following example, the value of the size properties of all "resource" type events are logged. ...
... example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. ...
PerformanceResourceTiming.redirectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
...imestamp representing the start time of the fetch which that initiates the redirect. if there are http redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property re
turns the starting time of the fetch that initiates the redirect; otherwise, zero is re
turned. note: this feature is available in web workers. syntax resource.redirectstart; re
turn value a timestamp representing the start time of the fetch which initiates the redirect. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource"...
PerformanceResourceTiming - Web APIs
ddle" alignment-baseline="middle">performanceresourcetiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: this feature is available in web workers. properties this interface extends the following performanceentry properties for resource performance entry types by qualifying and constraining them as follows: performanceentry.entrytyperead only re
turns "resource". performanceentry.nameread only re
turns the resources url. performanceentry.starttimeread only re
turns the timestamp for the time a resource fetch started. this value is equivalent to performanceentry.fetchstart. performanceentry.durationread only re
turns a timestamp that is the difference between the responseend and the starttime properties. the interface also supports the...
...urcetiming.initiatortyperead only a string representing the type of resource that initiated the performance entry, as specified in performanceresourcetiming.initiatortype. performanceresourcetiming.nexthopprotocolread only a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). performanceresourcetiming.workerstartread only re
turns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running. if the resource is not intercepted by a service worker the property will always re
turn 0. performanceresourcetiming.redirectstartread only a domhighrestimestamp that represents the start time o...
...plied content-codings. performanceresourcetiming.decodedbodysizeread only a number that is the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. performanceresourcetiming.servertimingread only an array of performanceservertiming entries containing server timing metrics. methods performanceresourcetiming.tojson() re
turns a domstring that is the json representation of the performanceresourcetiming object. example see the example in using the resource timing api. specifications specification status comment resource timing level 1the definition of 'performanceresourcetiming' in that specification. candidate recommendation initial definition. ...
Performance API - Web APIs
t of domhighrestimestamp is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. methods the performance interface has two methods. the now() method re
turns a domhighrestimestamp whose value that depends on the navigation start and scope. if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. the tojson() method re
turns a serialization of the performance object, for those attributes that can be serialized. properties the performance interface has ...
...at depends on the navigation start and scope. if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. the tojson() method re
turns a serialization of the performance object, for those attributes that can be serialized. properties the performance interface has two properties. ...
... interfaces performance provides methods and properties containing timing-related performance information for the given page. ...
Using Performance Timeline - Web APIs
o_work (n) { for (var i=0 ; i < n; i++) { var m = math.random(); } } function print_perf_entry(pe) { log("..name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } function print_performanceentries() { if (performance.mark === undefined) { log("... ...
...for (var j=0; j < properties.length; j++) { // check each property in window.performance var supported = properties[j] in p[i]; if (supported) { var pe = p[i]; log("... " + properties[j] + " = " + pe[properties[j]]); } else { log("... " + properties[j] + " = not supported"); } } } } this interface also includes a tojson() method that re
turns the serialization of the performanceentry object. the following examples show the use of this method. function perfentry_tojson() { // create a few performance entries performance.mark("mark-1"); performance.mark("mark-2"); performance.measure("meas-1", "mark-1", "mark-2"); var pelist = performance.getentries(); var pe = pelist[0]; if (pe.tojson === undefined) { log ("perfo...
...ect. the following examples show the use of this method. ...
Using Pointer Events - Web APIs
for example, for a pointerevent.pointerid value of 10, the resulting string is "#aaa". copying a touch object some browsers may re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object. function copytouc...
... result from this function is a string that can be used when calling <canvas> functions to set drawing colors. for example, for a pointerevent.pointerid value of 10, the resulting string is "#aaa". copying a touch object some browsers may re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object. function copytouch(touch) { re
turn { identifier: touch.pointerid, pagex: touch.clientx, pagey: touch.clienty }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier, then re
turns that touch's index into the array. function ongoingtouchindexbyid(idtofind) { for (var i = 0; i < ongoingtouches.length; i++) { var id = ongo...
...touch.clienty }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier, then re
turns that touch's index into the array. function ongoingtouchindexbyid(idtofind) { for (var i = 0; i < ongoingtouches.length; i++) { var id = ongoingtouches[i].identifier; if (id == idtofind) { re
turn i; } } re
turn -1; // not found } showing what's going on function log(msg) { var p = document.getelementbyid('log'); p.innerhtml = msg + "\n" + p.innerhtml; } specifications specification status comment pointer events – level 2the definition of 'pointerevent' in that specification. recommendation non-stable version. pointer eventsthe de...
PushManager.getSubscription() - Web APIs
example this code snippet is taken from a push messaging and notification sample. ...
... example this code snippet is taken from a push messaging and notification sample. ...
...hmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages. ...
RTCDtlsTransport.state - Web APIs
eceipt of a close_notify alert, or calling rtcpeerconnection.close(). failed the transport has failed as the result of an error (such as receipt of an error alert or failure to validate the remote fingerprint). examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states. the function re
turns an object containing properties whose values indicate how many of the senders are in each state. let pc = new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ... */ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(s...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport.state' in that specification. candidate recommendation initial definition. ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport.state' in that specification. candidate recommendation initial definition. ...
RTCIceCandidatePairStats.availableIncomingBitrate - Web APIs
the rtcicecandidatepairstats property availableincomingbitrate re
turns a value indicative of the available inbound capacity of the network connection represented by the candidate pair. the higher the value, the more bandwidth you can assume is available for incoming data. you can get the incoming outgoing bitrate from availableoutgoingbitrate. syntax availableincomingbitrate = rtcicecandidatepairstats.availableincomingbitrate; value a floating-point value which approximates the amount of available bandwidth for incoming data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. ...
...ng outgoing bitrate from availableoutgoingbitrate. syntax availableincomingbitrate = rtcicecandidatepairstats.availableincomingbitrate; value a floating-point value which approximates the amount of available bandwidth for incoming data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. ...
...value a floating-point value which approximates the amount of available bandwidth for incoming data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. the value re
turned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair. the re
turned value doesn't take into account overhead introduced by underlying protocols, including ip, udp, or tcp. note: the re
turned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2. specifications specification status comment identifiers for webrtc's statistics apith...
RTCIceServer.credential - Web APIs
the rtciceserver dictionary's credential property is a string providing the credential to use when connecting to the described server. this is typically a password, key, or other secret. this value is used when the rtciceserver describes a
turn server. syntax var iceserver = { ... credential = credential, ... ...
...his is typically a password, key, or other secret. this value is used when the rtciceserver describes a
turn server. syntax var iceserver = { ... credential = credential, ... }; var credential = iceserver.credential; iceserver.credential = newcredential; example this example creates a new rtcpeerconnection which uses a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server uses the username "webrtc" and the creative password "
turnpassword". ...
... }; var credential = iceserver.credential; iceserver.credential = newcredential; example this example creates a new rtcpeerconnection which uses a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server uses the username "webrtc" and the creative password "
turnpassword". mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "
turn:
turnserver.example.org", // a
turn server username: "webrtc", credential: "
turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification. candidate recommendation initial specification. ...
RTCIceServer.username - Web APIs
the rtciceserver dictionary's username property is a string which specifies the username to use when authenticating with the ice server being described. this value is used when the rtciceserver describes a
turn server. syntax var iceserver = { ... username = username, ... }; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections. ...
...hen the rtciceserver describes a
turn server. syntax var iceserver = { ... username = username, ... }; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server will use the username "webrtc" and the creative password "
turnpassword". ...
... }; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a
turn server at
turnserver.example.org to negotiate connections. logging into the
turn server will use the username "webrtc" and the creative password "
turnpassword". mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "
turn:
turnserver.example.org", // a
turn server username: "webrtc", credential: "
turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.username' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection() - Web APIs
syntax pc = new rtcpeerconnection([configuration]); parameters configuration optional an rtcconfiguration dictionary providing options to configure the new connection. rtcconfiguration dictionary bundlepolicy optional specifies how to handle negotiation of candidates when the remote peer is not compatible with the sdp bundle standard. this must be one of the values from the enum rtcbundlepolicy. if this value isn't included in the dictionary, "balanced" is assumed. certificates optional an array of objects of type rtccertificate which are used by the connection for authentication. ...
...g ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or
turn servers. if this isn't specified, the connection attempt will be made with no stun or
turn server available, which limits the connection to local peers. icetransportpolicy optional the current ice transport policy; this must be one of the values from the rtcicetransportpolicy enum. if this isn't specified, "all" is assumed. peeridentity optional a domstring which specifies the target peer ide...
...e rtcpeerconnection. if this value is set (it defaults to null), the rtcpeerconnection will not connect to a remote peer unless it can successfully authenticate with the given name. rtcpmuxpolicy optional the rtcp mux policy to use when gathering ice candidates, in order to support non-multiplexed rtcp. the value must be one of those from the rtcrtcpmuxpolicy enum. the default is "require". re
turn value a newly-created rtcpeerconnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection()' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.addIceCandidate() - Web APIs
ted and its use is strongly discouraged. you should update any existing code to use the promise-based version of addicecandidate() instead. the parameters for this form of addicecandidate() are described below, to aid in updating existing code. successcallback a function to be called when the ice candidate has been successfully added. this function receives no input parameters and doesn't re
turn a value. failurecallback a function to be called if attempting to add the ice candidate fails. receives as input a domexception object describing why failure occurred. re
turn value a promise which is fulfilled when the candidate has been successfully added to the remote peer's description by the ice agent. the promise does not receive any input parameters. exceptions when an error occurs...
... typeerror the specified candidate's sdpmid and sdpmlineindex are both null. ...
... typeerror the specified candidate's sdpmid and sdpmlineindex are both null. invalidstateerror the rtcpeerconnection currently has no remote peer established (remotedescription is null). ...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
ice trickling is the process of continuing to send candidates after the initial offer or answer has already been sent to the other peer. this property is only set after having called rtcpeerconnection.setremotedescription(). ideally, your signaling protocol provides a way to detect trickling support, so that you don't need to rely on this property. a webrtc browser will always support trickle ice. ...
...not the remote peer supports trickled ice candidates. example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice. ...
...ice candidates. example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice. ...
RTCPeerConnection.createAnswer() - Web APIs
the createanswer() method on the rtcpeerconnection interface creates an sdp answer to an offer received from a remote peer during the offer/answer negotiation of a webrtc connection. the answer contains information about any media already attached to the session, codecs and options supported by the browser, and any ice candidates already gathered. the answer is delivered to the re
turned promise, and should then be sent to the source of the offer to continue the negotiation process. syntax apromise = rtcpeerconnection.createanswer([options]); rtcpeerconnection.createanswer(successcallback, failurecallback[, options]); parameters options optional an object which contains options which customize the answer; this is based on the rtcansweroptions dictionary. deprecated parameters in o...
...d a single domexception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object providing options requested for the answer. exceptions notreadableerror the identity provider wasn't able to provide an identity assertion. operationerror generation of the sdp failed for some reason; this is a general failure catch-all exception. re
turn value a promise whose fulfillment handler is called with an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp answer to be delivered to the other peer. example here is a segment of code taken from the code that goes with the article signaling and video calling. this code comes from the handler for the message sent to carry an offer to another peer across the ...
...websocket connection is used to send a json message with a type field with the value "video-answer" to the other peer, carrying the answer to the device which sent the offer to connect. the contents of the object being passed to the sendtoserver() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createanswer().then(function(answer) { re
turn pc.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer through the signaling server. }) .catch(handlegetusermediaerror); this asks rtcpeerconnection to create and re
turn a new answer. in our promise handler, the re
turned answer is set as the description of the local end of the connection by calling setlocaldescription(). once that succeeds, the answer is ...
RTCPeerConnection.getSenders() - Web APIs
example in this example, a setmuting() function is shown. ...
... example in this example, a setmuting() function is shown. ...
... example in this example, a setmuting() function is shown. ...
RTCPeerConnection.getStreamById() - Web APIs
the rtcpeerconnection.getstreambyid() method re
turns the mediastream with the given id that is associated with local or remote end of the connection. if no stream matches, it re
turns null. this property has been replaced with the rtcpeerconnection.getlocalstreams and rtcpeerconnection.getremotestreams properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to re
turn. example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not nat...
...ype.getstreambyid() if it's not natively available. ...
...&desc=5#c10 rtcpeerconnection.prototype.getstreambyid = function(id) { try { var localstreams = this.getlocalstreams(); var remotestreams = this.getremotestreams(); var i; for (i = 0; i < localstreams.length; i++) { if (localstreams[i].id == id) re
turn localstreams[i]; } for (i = 0; i < remotestreams.length; i++) { if (remotestreams[i].id == id) re
turn remotestreams[i]; } } catch(e) {} re
turn null; } ...
RTCPeerConnection: icecandidateerror event - Web APIs
the webrtc api event icecandidateerror is sent to an rtcpeerconnection if an error occurs while performing ice negotiations through a stun or
turn server. the event object is of type rtcpeerconnectioniceerrorevent, and contains information describing the error in some amount of detail. bubbles no cancelable no interface rtcpeerconnectioniceerrorevent event handler property rtcpeerconnection.onicecandidateerror description the error object's errorcode property is one of the numeric stun error codes. there is one additional, webrtc-specific, error which lies outside the valid stun error code range: 701. error 701 indicates that none of the ice candidates were able to successfully make contact with the stun or
turn server. the 701 error i...
...escription the error object's errorcode property is one of the numeric stun error codes. there is one additional, webrtc-specific, error which lies outside the valid stun error code range: 701. error 701 indicates that none of the ice candidates were able to successfully make contact with the stun or
turn server. the 701 error is fired only once per server url from the list of available stun or
turn servers provided when creating the rtcpeerconnection. these errors occur only when the connection's ice gathering state is gathering. example the following example establishes a handler for icecandidateerrors that occur on the rtcpeerconnection pc. this handler looks specifically for 701 errors that indicate that candidates couldn't reach the stun or
turn server. when this happens, the server ...
...each provided server is tried until a connection is established. ...
RTCPeerConnection.localDescription - Web APIs
see pending and current descriptions in webrtc connectivity for details on this algorithm and why it's used. example this example looks at the localdescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. ...
...see pending and current descriptions in webrtc connectivity for details on this algorithm and why it's used. example this example looks at the localdescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. ...
...see pending and current descriptions in webrtc connectivity for details on this algorithm and why it's used. ...
RTCRtpSender.replaceTrack() - Web APIs
or each camera and switch between the two as needed. see the example switching cameras below. syntax trackreplacedpromise = sender.replacetrack(newtrack); parameters newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track. the new track's kind must be the same as the current track's, or the replace track request will fail. re
turn value a promise which is fulfilled once the track has been successfully replaced. the promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required i...
...annot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required in this case. when the promise is fulfilled, the fulfillment handler receives a value of undefined. exceptions if the re
turned promise is rejected, one of the following exceptions is provided to the rejection handler: invalidmodificationerror replacing the rtcrtpsender's current track with the new one would require negotiation. invalidstateerror the track on which this method was called is stopped rather than running. typeerror the new track's kind doesn't match the original track. usage notes things that tr...
...cameras // example to change video camera, suppose selected value saved into window.selectedcamera navigator.mediadevices .getusermedia({ video: { deviceid: { exact: window.selectedcamera } } }) .then(function(stream) { let videotrack = stream.getvideotracks()[0]; pcs.foreach(function(pc) { var sender = pc.getsenders().find(function(s) { re
turn s.track.kind == videotrack.kind; }); console.log('found sender:', sender); sender.replacetrack(videotrack); }); }) .catch(function(err) { console.error('error happens:', err); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.replacetrack()' in that specific...
RTCRtpStreamStats.qpSum - Web APIs
is case, it's an index used to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. ...
... candidate recommendation initial definition. ...
... candidate recommendation initial definition. identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats: qpsum' in that specification. ...
ReadableStream.pipeThrough() - Web APIs
to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be closed. ...
...ng will no longer cause the destination writablestream to be closed. the method will re
turn a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventabort: if this is set to true, errors in the source readablestream will no longer abort the destination writablestream. the method will re
turn a promise rejected with the source’s error, or with any error that occurs during aborting the destination. preventcancel: if this is set to true, errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will re
turn a promise rejected with the source’s error, or with any error that occurs during canceling the source. in addition, if th...
...rue, errors in the destination writablestream will no longer cancel the source readablestream. in this case the method will re
turn a promise rejected with the source’s error, or with any error that occurs during canceling the source. in addition, if the destination writable stream starts out closed or closing, the source readable stream will no longer be canceled. in this case the method will re
turn a promise rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. re
turn value the readable side of the transformstream. exceptions typeerror the writable and/or readable property of transfo...
Report.body - Web APIs
these all inherit from the base reportbody class — study their reference pages for more information on what the particular report body types contain. ...
...these all inherit from the base reportbody class — study their reference pages for more information on what the particular report body types contain. ...
...these all inherit from the base reportbody class — study their reference pages for more information on what the particular report body types contain. ...
Response.error() - Web APIs
example tbd (does not yet appear to be supported anywhere). ...
... example tbd (does not yet appear to be supported anywhere). ...
... example tbd (does not yet appear to be supported anywhere). ...
SVGPathSegList - Web APIs
initialize(in svgpathseg newitem) svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. ...
...any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. ...
...any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. ...
SVGPointList - Web APIs
normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. ...
... initialize(in svgpoint newitem) svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the re
turn value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgpoint re
turns the specified item from the list. th...
...ue is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgpoint re
turns the specified item from the list. the re
turned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(...
SVGTextPositioningElement - Web APIs
t x="-114" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextpositioningelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgtextcontentelement. ...
... alignment-baseline="middle">svgtextpositioningelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgtextcontentelement. svgtextpositioningelement.x read only re
turns an svganimatedlengthlist reflecting the x attribute of the given element. svgtextpositioningelement.y read only re
turns an svganimatedlengthlist reflecting the y attribute of the given element. ...
...ts: all;} properties this interface also inherits properties from its parent, svgtextcontentelement. svgtextpositioningelement.x read only re
turns an svganimatedlengthlist reflecting the x attribute of the given element. svgtextpositioningelement.y read only re
turns an svganimatedlengthlist reflecting the y attribute of the given element. svgtextpositioningelement.dx read only re
turns an svganimatedlengthlist reflecting the dx attribute of the given element. svgtextpositioningelement.dy read only re
turns an svganimatedlengthlist reflecting the dy attribute of the given element. svgtextpositioningelement.rotate read only re
turns an svganimatednumberlist reflecting the rotate attribute of the given element. methods this interface doesn't provide any specific methods, b...
SVGTransformList - Web APIs
readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransform newitem) svgtransform c...
...lf is read only. initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the re
turn value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform re
turns the specified item from the list. the re
turned item is the item itself and not a copy. any ch...
...ot adopted as svgtransform::matrix. consolidate() svgtransform consolidates the list of separate svgtransform objects by multiplying the equivalent transformation matrices together to result in a list consisting of a single svgtransform object of type svg_transform_matrix. the consolidation operation creates new svgtransform object as the first and only item in the list. the re
turned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. example using multiple svgtransform objects in this example we create a function that wil...
Sensor APIs - Web APIs
apis are a set of interfaces built to a common design that expose device sensors in a consistent way to the web platform. sensor apis concepts and usage although the generic sensor api specification defines a sensor interface, as a web developer you will never use it. instead you'll use one of its subclasses to retrieve specific kinds of sensor data. for example, the accelerometer interface re
turns the acceleration of the device along all three axes at the time it is read. sensors may or may not correspond exactly to a physical device sensor. for example, the gyroscope interface corresponds exactly to a physical device interface. alternatively, the absoluteorientationsensor interface provides information that is algorithmically agregated from two or more device sensors. these sensor types...
...ensor readings may not be taken unless the user grants permission to a specific sensor type. do this using the permissions api. a brief example, shown below, requests permission before attempting to use the sensor. navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('permission to use accelerometer sensor is denied.'); re
turn; } // use the sensor. }); an alternative approach is to attempt to use the error and listen for the securityerror. const sensor = new absoluteorientationsensor(); sensor.start(); sensor.onerror = event => { if (event.error.name === 'securityerror') console.log("no permissions to use absoluteorientationsensor."); }; the following table describes for each sensor type, the name required...
...tlistener('error', event => { console.log(event.error.name, event.error.message); }) magsensor.start(); interfaces absoluteorientationsensorsecure context describes the device's physical orientation in relation to the earth's reference coordinate system. accelerometersecure context provides the acceleration applied to the device along all three axes. ambientlightsensorsecure context re
turns the current light level or illuminance of the ambient light around the hosting device. gyroscopesecure context provides the angular velocity of the device along all three axes. linearaccelerationsensorsecure context provides the acceleration applied to the device along all three axes, but without the contribution of gravity. magnetometersecure context provides information about the magneti...
ServiceWorkerGlobalScope: notificationclick event - Web APIs
log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) re
turn client.focus(); } if (clients.openwindow) re
turn clients.openwindow('/'); })); }); or use the onnotificationclick event handler property: self.onnotificationclick = function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(cl...
... living standard ...
... living standard ...
SharedWorkerGlobalScope - Web APIs
ce, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.name read only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor. this is mainly useful for debugging purposes. ...
...ead only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor. this is mainly useful for debugging purposes. sharedworkerglobalscope.applicationcache read only this property re
turns the applicationcache object for the worker (see using the application cache). properties inherited from workerglobalscope workerglobalscope.self re
turns an object reference to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only re
turns the console associated with the worker. workerglobalscope.location read only re
turns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navig...
...ce to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only re
turns the console associated with the worker. workerglobalscope.location read only re
turns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navigator read only re
turns the workernavigator associated with the worker. workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.performance read only re
turns the performance object associated with the worker, which is a regular performance object, but with a subset of its properties and methods available. event handlers this...
SourceBuffer - Web APIs
art of the append window. this is a timestamp range that can be used to filter what media data is appended to the sourcebuffer. coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out. sourcebuffer.audiotracks read only a list of the audio tracks currently contained inside the sourcebuffer. sourcebuffer.buffered read only re
turns the time ranges that are currently buffered in the sourcebuffer. sourcebuffer.mode controls how the order of media segments in the sourcebuffer is handled, in terms of whether they can be appended in any order, or they have to be kept in a strict sequence. sourcebuffer.texttracks read only a list of the text tracks currently contained inside the sourcebuffer. sourcebuffer.timestampoffset ...
...ethods 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. re
turns 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. sourcebuffer.remove() removes media segments within a specific time range from the sourcebuffer. s...
...stream 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. re
turns 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 also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag...
SpeechGrammar.src - Web APIs
syntax var mygrammar = speechgrammarinstance.src; value a domstring representing the grammar. ...
... specifications specification status comment web speech apithe definition of 'src' in that specification. draft ...
... specifications specification status comment web speech apithe definition of 'src' in that specification. draft ...
SpeechGrammar.weight - Web APIs
syntax var mygrammarweight = speechgrammarinstance.weight; value a float representing the weight of the grammar, in the range 0.0–1.0. ...
... specifications specification status comment web speech apithe definition of 'weight' in that specification. draft ...
... specifications specification status comment web speech apithe definition of 'weight' in that specification. draft ...
SpeechGrammar - Web APIs
the speechgrammar interface of the web speech api represents a set of words or patterns of words that we want the recognition service to recognize. grammar is defined using jspeech grammar format (jsgf.) other formats may also be supported in the future. constructor speechgrammar.speechgrammar() creates a new speechgrammar object. properties speechgrammar.src sets and re
turns a string containing the grammar from within in the speechgrammar object instance. speechgrammar.weight optional sets and re
turns the weight of the speechgrammar object. examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | k...
... specifications specification status comment web speech apithe definition of 'speechgrammar' in that specification. draft ...
... specifications specification status comment web speech apithe definition of 'speechgrammar' in that specification. draft ...
SpeechRecognition.onresult - Web APIs
the onresult property of the speechrecognition interface represents an event handler that will run when the speech recognition service re
turns a result — a word or phrase has been positively recognized and this has been communicated back to the app (when the result event fires.) syntax myspeechrecognition.onresult = function() { ... }; examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionr...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'onresult' in that specification. draft ...
SpeechRecognitionAlternative.transcript - Web APIs
the transcript read-only property of the speechrecognitionresult interface re
turns a string containing the transcript of the recognised word(s). for continuous recognition, leading or trailing whitespace will be included where necessary so that concatenation of consecutive speechrecognitionresults produces a proper transcript of the session. syntax var mytranscript = speechrecognitionalternativeinstance.transcript; re
turns a domstring. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array //...
...pt; re
turns a domstring. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'transcript' in that specification. draft ...
SpeechRecognitionResult.isFinal - Web APIs
the isfinal read-only property of the speechrecognitionresult interface is a boolean that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be re
turned; if not, then this result is an interim result, and may be updated later on. syntax var myisfinal = speechrecognitionresultinstance.isfinal; re
turns a boolean. examples recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecogn...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results[0].isfinal); } specifications specification status comment web speech apithe definition of 'isfinal' in that specification. draft ...
SpeechRecognitionResult.item() - Web APIs
the item getter of the speechrecognitionresult interface is a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. syntax var myalternative = speechrecognitionresultinstance[0]; re
turns a speechrecognitionalternative object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects ...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'item()' in that specification. draft ...
SpeechRecognitionResult.length - Web APIs
the length read-only property of the speechrecognitionresult interface re
turns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) the number of alternatives contained in the result depends on what the speechrecognition.maxalternatives property was set to when the speech recognition was first initiated. syntax var mylength = speechrecognitionresultinstance.length; re
turns a number. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a gett...
...ength; re
turns a number. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results[0].length); } specifications specification status comment web speech apithe definition of 'length' in that specification. draft ...
SpeechRecognitionResultList.item() - Web APIs
the item getter of the speechrecognitionresultlist interface is a standard getter — it allows speechrecognitionresult objects in the list to be accessed via array syntax. syntax var myresult = speechrecognitionresultlistinstance[0]; re
turns a speechrecognitionresult object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contai...
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'item()' in that specification. draft ...
SpeechRecognitionResultList.length - Web APIs
the length read-only property of the speechrecognitionresultlist interface re
turns the length of the "array" — the number of speechrecognitionresult objects in the list. syntax var mylength = speechrecognitionresultlistinstance.length; re
turns a number. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property re
turns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results.
...itionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. ...
... it has a getter so it can be accessed like an array // the first [0] re
turns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results. // these also have getters so they can be accessed like arrays. // the second [0] re
turns the speechrecognitionalternative at position 0. // we then re
turn the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results.length); } specifications specification status comment web speech apithe definition of 'length' in that specification. draft ...
SpeechSynthesis - Web APIs
the speechsynthesis interface of the web speech api is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides. properties speechsynthesis also inherits properties from its parent interface, eventtarget. speechsynthesis.paused read only a boolean that re
turns true if the speechsynthesis object is in a paused state. speechsynthesis.pending read only a boolean that re
turns true if the utterance queue contains as-yet-unspoken utterances. speechsynthesis.speaking read only a boolean that re
turns true if an utterance is currently in the process of being spoken — even if speechsynthesis is in a paused state. methods speechsynthesis also inher...
... speechsynthesis.pause() puts the speechsynthesis object into a paused state. speechsynthesis.resume() puts the speechsynthesis object into a non-paused state: resumes it if it was already paused. ...
... it if it was already paused. speechsynthesis.speak() adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been spoken. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. voiceschanged fired when the list of speechsynthesisvoice objects that would be re
turned by the speechsynthesis.getvoices() method has changed. also available via the onvoiceschanged property. examples first, a simple example: let utterance = new speechsynthesisutterance("hello world!"); speechsynthesis.speak(utterance); now we'll look at a more fully-fledged example. in our speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.spee...
SpeechSynthesisEvent - Web APIs
the speechsynthesisevent interface of the web speech api contains information about the current state of speechsynthesisutterance objects that have been processed in the speech service. properties the speechsynthesisevent interface also inherits properties from its parent interface, event. ...
...utterance objects that have been processed in the speech service. properties the speechsynthesisevent interface also inherits properties from its parent interface, event. speechsynthesisevent.charindex read only re
turns the index position of the character in the speechsynthesisutterance.text that was being spoken when the event was triggered. speechsynthesisevent.elapsedtime read only re
turns the elapsed time in milliseconds after the speechsynthesisutterance.text started being spoken that the event was triggered at. ...
... speechsynthesisevent.charindex read only re
turns the index position of the character in the speechsynthesisutterance.text that was being spoken when the event was triggered. speechsynthesisevent.elapsedtime read only re
turns the elapsed time in milliseconds after the speechsynthesisutterance.text started being spoken that the event was triggered at. speechsynthesisevent.name read only re
turns the name associated with certain types of events occuring as the speechsynthesisutterance.text is being spoken: the name of the ssml marker reached in the case of a mark event, or the type of boundary reached in the case of a boundary event. speechsynthesisevent.utterance read only re
turns the speechsynthesisutterance instance that the event was triggered on. methods the speechsynthesiseve...
SpeechSynthesisVoice - Web APIs
terface of the web speech api represents a voice that the system supports. every speechsynthesisvoice has its own relative speech service including information about language, name and uri. ...
... examples the following snippet is excerpted from our speech synthesiser demo. ...
... examples the following snippet is excerpted from our speech synthesiser demo. ...
Storage.getItem() - Web APIs
example the following function retrieves three data items from local storage, then uses them to set custom styles on a page. ...
... example the following function retrieves three data items from local storage, then uses them to set custom styles on a page. ...
... example the following function retrieves three data items from local storage, then uses them to set custom styles on a page. ...
Storage Access API - Web APIs
ely. if an embedded page from tracker.example has previously successfully obtained storage access on top-level origin foo.example, all embedded subresources from tracker.example on foo.example (e.g. scripts, images, stylesheets, etc.) will load with access to their first-party storage, which means they may send cookie headers and honor incoming set-cookie headers. in firefox, when the promise re
turned from requeststorageaccess() is resolved, the embedded page will gain access to its entire first-party storage, not just cookies. this includes access to apis such as web storage, indexeddb, dom cache, and so on. in firefox, the storage access grants are phased out after 30 calendar days passing, whereas in safari the storage access grants are phased out after 30 days of browser usage passed w...
...ch we may address in a future version. in safari, successful use of the storage access api resets this counter. documentation for firefox's new storage access policy for blocking tracking cookies includes a detailed description of the scope of storage access grants. ...
...ess policy for blocking tracking cookies includes a detailed description of the scope of storage access grants. storage access api methods the storage api methods are implemented on the document interface: document.hasstorageaccess() re
turns a promise that resolves with a boolean value indicating whether the document has access to its first-party storage. document.requeststorageaccess() re
turns a promise that resolves if the access to first-party storage was granted, and rejects if access was denied. note: user interaction propagates to the promise re
turned by both of these methods, allowing the callers to take actions that require user interaction without requiring a second click from the user. for example, a caller could open a pop-up window from the resolved promise without trigg...
Using writable streams - Web APIs
method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. ...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.lo...
...reates a writablestreamdefaultwriter instance. we also create a new textencoder instance using the relevant constructor to encode the message into chunks to be put into the stream. with the chunks encoded, we then call array/foreach on the resulting array. inside this block we use writablestreamdefaultwriter.ready to check whether the writer is ready to have another chunk written to it. ready re
turns a promise that fulfills when this is the case, inside of which we call writablestreamdefaultwriter.write() to actually write the chunk to the stream. this also triggers the write() method specified inside the writablestream() constructor, as discussed above. after the chunks have all been written, we then perform the ready check once more, to check that the last chunk has finished being written...
Streams API - Web APIs
ilable on the client-side, without needing to generate a buffer, string, or blob. there are more advantages too — you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed of the stream is being read at. the basic usage of streams hinges around making responses available as streams. for example, the response body re
turned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc. more complicated uses involve creating your own stream using the readablestream() constructor, for example to process data inside a service worker. you can also write data to streams using writablestream...
...gy provides a built-in chunk counting queuing strategy that can be used when constructing streams. extensions to other apis request when a new request object is constructed, you can pass it a readablestream in the body property of its requestinit dictionary. this request could then be passed to a windoworworkerglobalscope.fetch() to commence fetching the stream. body the response body re
turned by a successful fetch request is exposed by default as a readablestream, and can have a reader attached to it, etc. bytestream-related interfaces important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this may change over time. readablestreambyobreader represents a by...
...ents a pull into request in a readablebytestreamcontroller. examples we have created a directory of examples to go along with the streams api documentation — see mdn/dom-examples/streams. the examples are as follows: simple stream pump: this example shows how to consume a readablestream and pass its data to another. grayscale a png: this example shows how a readablestream of a png can be
turned into grayscale. simple random stream: this example shows how to use a custom stream to generate random strings, enqueue them as chunks, and then read them back out again. simple tee example: this example extends the simple random stream example, showing how a stream can be teed and both resulting streams can be read independently. simple writer: this example shows how to to write to a writab...
SubtleCrypto.exportKey() - Web APIs
the subtlecrypto.wrapkey() api instead. syntax const result = crypto.subtle.exportkey(format, key); parameters format is a string value describing the data format in which the key should be exported. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to export. re
turn value result is a promise. if format was jwk, then the promise fulfills with a json object containing the key. otherwise the promise fulfills with an arraybuffer containing the key. exceptions the promise is rejected when one of the following exceptions is encountered: invalidaccesserror raised when trying to export a non-extractable key. notsupported raised when trying...
...ddeventlistener("click", () => { exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key 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) { re
turn string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "pkcs8", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin private key--...
...click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export this example exports an rsa public 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) { re
turn string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "spki", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin public key----...
TaskAttributionTiming - Web APIs
the frame context, also called the container, is the iframe, embed or object that is being implicated, on the whole, for a long task. ...
... specifications specification status comment long...
...family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">taskattributiontiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties taskattributiontiming.containertype read only re
turns the type of frame container, one of iframe, embed, or object. taskattributiontiming.containersrc read only re
turns the container's src attribute. taskattributiontiming.containerid read only re
turns the container's id attribute. taskattributiontiming.containername read only re
turns the container's name attribute. specifications specification status comment long tasks api 1the definition of 'taskattributiontiming' in that specification. working draft initial definition. ...
getTrackById() - Web APIs
the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
... the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. ...
...specified string. this lets you find a specified track if you know its id string. syntax var thetrack = texttracklist.gettrackbyid(id); paramters id a domstring indicating the id of the track to locate within the track list. re
turn value a texttrack object indicating the first track found within the texttracklist whose id matches the specified string. if no match is found, this method re
turns null. the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. specifications specification status comment html living standardthe definition of 'texttracklist.gettrackbyid()' in that specificatio...
Touch.radiusX - Web APIs
summary re
turns the x radius of the ellipse that most closely circumscribes the area of contact with the touch surface. the value is in css pixels of the same scale as touch.screenx. this value, in combination with touch.radiusy and touch.rotationangle constructs an ellipse that approximates the size and shape of the area of contact between the user and the screen. this may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. ...
...tively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. syntax var xradius = touchitem.radiusx; re
turn value xradius the x radius of the ellipse that most closely circumscribes the area of contact with the touch surface. example this example illustrates using the touch interface's touch.radiusx, touch.radiusx and touch.rotationangle properties. the touch.radiusx property is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis indi...
...based on the touch point's radiusx and radiusy values and the element will then be rotated using the touch point's rotationangle. <div id="src"> ... </div> var src = document.getelementbyid("src"); src.addeventlistener('touchstart', rotate); src.addeventlistener('touchmove', rotate); src.addeventlistener('touchend', rotate); function rotate (e) { var touch = e.changedtouches.item(0); //
turn off default event handling e.preventdefault(); // rotate element 'src'. src.style.width = touch.radiusx * 2 + 'px'; src.style.height = touch.radiusy * 2 + 'px'; src.style.transform = "rotate(" + touch.rotationangle + "deg)"; }; specifications specification status comment touch events – level 2 draft non-stable version. ...
TouchList.item() - Web APIs
example this code example illustrates the use of the touchlist interface's item method and the length property. ...
... example this code example illustrates the use of the touchlist interface's item method and the length property. ...
... example this code example illustrates the use of the touchlist interface's item method and the length property. ...
TrackDefault - Web APIs
the trackdefault interface provides a sourcebuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. a trackdefault object is provided to a sourcebuffer object by setting its sourcebuffer.trackdefaults property. constructor trackdefault() constructs and re
turns a new trackdefault object. ...
...es a sourcebuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. a trackdefault object is provided to a sourcebuffer object by setting its sourcebuffer.trackdefaults property. constructor trackdefault() constructs and re
turns a new trackdefault object. properties trackdefault.type read only re
turns the type of track that this sourcebuffer's media segment data relates to (i.e. audio, video, or text track.) trackdefault.bytestreamtrackid read only re
turns the id of the specific track that the sourcebuffer should apply to. trackdefault.language read only re
turns the default language to use when an initialization segment does not contain language information for a new track. trackdefaul...
...at this sourcebuffer's media segment data relates to (i.e. audio, video, or text track.) trackdefault.bytestreamtrackid read only re
turns the id of the specific track that the sourcebuffer should apply to. trackdefault.language read only re
turns the default language to use when an initialization segment does not contain language information for a new track. trackdefault.label read only re
turns the default label to use when an initialization segment does not contain label information for a new track. trackdefault.kinds read only re
turns the default kinds used when an initialization segment does not contain kind information for a new track. ...
URLSearchParams.getAll() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.getall('foo')) //prints ["1","4"]. ...
... examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.getall('foo')) //prints ["1","4"]. ...
... examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.getall('foo')) //prints ["1","4"]. ...
USBAlternateInterface - Web APIs
ings which can configure a set of endpoints based on the operating mode of the device. constructor usbalternateinterface.usbalternateinterface creates a new usbalternateinterface object which will be populated with information about the alternate interface of the provided usbinterface with the given alternate setting number. properties usbalternateinterface.alternatesettingread only re
turns the alternate setting number of this interface. this is equal to the balternatesetting field of the interface descriptor defining this interface. usbalternateinterface.interfaceclassread only re
turns the class of this interface. this is equal to the binterfaceclass field of the interface descriptor defining this interface. standardized values for this field are defined by the usb implementers...
...riptor defining this interface. usbalternateinterface.interfaceclassread only re
turns the class of this interface. this is equal to the binterfaceclass field of the interface descriptor defining this interface. standardized values for this field are defined by the usb implementers forum. a value of 0xff indicates a vendor-defined interface. usbalternateinterface.interfacesubclassread only re
turns the subclass of this interface. this is equal to the binterfacesubclass field of the interface descriptor defining this interface. the meaning of this value depends on the interfaceclass field. usbalternateinterface.interfaceprotocolread only re
turns the protocol supported by this interface. this is equal to the binterfaceprotocol field of the interface descriptor defining this interface. the...
...the meaning of this value depends on the interfaceclass field. usbalternateinterface.interfaceprotocolread only re
turns the protocol supported by this interface. this is equal to the binterfaceprotocol field of the interface descriptor defining this interface. the meaning of this value depends on the interfaceclass and interfacesubclass fields. usbalternateinterface.interfacenameread only re
turns the name of the interface, if one is provided by the device. this is the value of the string descriptor with the index specified by the iinterface field of the interface descriptor defining this interface. usbalternateinterface.endpointsread only re
turns an array containing instances of the usbendpoint interface describing each of the endpoints that are part of this interface. specification...
USBEndpoint - Web APIs
tion about an endpoint provided by the usb device. an endpoint represents a unidirectional data stream into or out of a device. constructor usbendpoint.usbendpoint creates a new usbendpoint object which will be populated with information about the endpoint on the provided usbaltenateinterface with the given endpoint number and transfer direction. properties usbendpoint.endpointnumber re
turns this endpoint's "endpoint number" which is a value from 1 to 15 extracted from the bendpointaddress field of the endpoint descriptor defining this endpoint. this value is used to identify the endpoint when calling methods on usbdevice. usbendpoint.direction re
turns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host. "out" - da...
...xtracted from the bendpointaddress field of the endpoint descriptor defining this endpoint. this value is used to identify the endpoint when calling methods on usbdevice. usbendpoint.direction re
turns the direction in which this endpoint transfers data, one of: "in" - data is transferred from device to host. "out" - data is transferred from host to device. usbendpoint.type re
turns the type of this endpoint, one of: "bulk" - provides reliable data transfer for large payloads. data sent through a bulk endpoint is guaranteed to be delivered or generate an error but may be preempted by other data traffic. "interrupt" - provides reliable data transfer for small payloads. data sent through an interrupt endpoint is guaranteed to be delivered or generate an error and i...
... transfer for small payloads. data sent through an interrupt endpoint is guaranteed to be delivered or generate an error and is also given dedicated bus time for transmission. "isochronous" - provides unreliable data transfer for payloads that must be delivered periodically. they are given dedicated bus time but if a deadline is missed the data is dropped. usbendpoint.packetsize re
turns the size of the packets that data sent through this endpoint will be divided into. examples while sometimes the developer knows ahead of time the exact layout of a device's endpoints there are cases where this must be discovered at runtime. for example, a usb serial device must provide bulk input and output endpoints but their endpoint numbers will depend on what other interfaces the device p...
WakeLockSentinel.release() - Web APIs
you should always listen for the onrelease event to check if a wake lock has been released. examples in this example, when a user clicks a button the wakelocksentinel is released. ...
...you should always listen for the onrelease event to check if a wake lock has been released. examples in this example, when a user clicks a button the wakelocksentinel is released. ...
...you should always listen for the onrelease event to check if a wake lock has been released. examples in this example, when a user clicks a button the wakelocksentinel is released. ...
WakeLockSentinel - Web APIs
the wakelocksentinel interface of the screen wake lock api provides a handle to the underlying platform wake lock and can be manually released and reacquired. an object representing the wake lock is re
turned via the navigator.wakelock.request() method. an acquired wakelocksentinel can be released manually via the release() method, or automatically via the platform wake lock. this can happen if the document becomes inactive or looses visibility, if the device is low on power or the user
turns on a power save mode. ...
... or automatically via the platform wake lock. this can happen if the document becomes inactive or looses visibility, if the device is low on power or the user
turns on a power save mode. releasing all wakelocksentinel instances of a given wake lock type will cause the underlying platform wake lock to be released. properties this interface provides the following properties. type read only re
turns a string representation of the currently acquired wakelocksentinel type. re
turn values are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. ...
... 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. ...
WebGL2RenderingContext.getSamplerParameter() - Web APIs
the webgl2renderingcontext.getsamplerparameter() method of the webgl 2 api re
turns parameter information of a webglsampler object. syntax any gl.getsamplerparameter(sampler, pname); parameters sampler a webglsampler object. pname a glenum specifying which information to re
turn. possible values: gl.texture_compare_func: re
turns a glenum indicating the texture comparison function. gl.texture_compare_mode: re
turns a glenum indicating the texture comparison mode. gl.texture_mag_filter: re
turns a glenum indicating the texture magnification filter. gl.texture_max_lod: re
turns a glfloat indicating the maximum level-of-detail value. ...
... re
turn. possible values: gl.texture_compare_func: re
turns a glenum indicating the texture comparison function. gl.texture_compare_mode: re
turns a glenum indicating the texture comparison mode. gl.texture_mag_filter: re
turns a glenum indicating the texture magnification filter. gl.texture_max_lod: re
turns a glfloat indicating the maximum level-of-detail value. gl.texture_min_filter: re
turns a glenum indicating the texture minification filter gl.texture_min_lod: re
turns a glfloat indicating the minimum level-of-detail value. gl.texture_wrap_r: re
turns a glenum indicating the texture wrapping function for the texture coordinate r. gl.texture_wrap_s: re
turns a glenum indicating the texture wrapping function for the texture coordinate s. ...
..._min_filter: re
turns a glenum indicating the texture minification filter gl.texture_min_lod: re
turns a glfloat indicating the minimum level-of-detail value. gl.texture_wrap_r: re
turns a glenum indicating the texture wrapping function for the texture coordinate r. gl.texture_wrap_s: re
turns a glenum indicating the texture wrapping function for the texture coordinate s. gl.texture_wrap_t: re
turns a glenum indicating the texture wrapping function for the texture coordinate t. re
turn value depends on the pname parameter, either a glenum or a glfloat. examples var sampler = gl.createsampler(); gl.getsamplerparameter(sampler, gl.texture_compare_func); specifications specification status comment webgl 2.0the definition of 'getsamplerparameter' in that speci...
WebGLRenderingContext.getAttribLocation() - Web APIs
examples gl.getattriblocation(program, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'getattriblocation' in that specification. recommendation initial definition. ...
... examples gl.getattriblocation(program, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'getattriblocation' in that specification. recommendation initial definition. ...
... examples gl.getattriblocation(program, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'getattriblocation' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetattriblocation' in that specification. ...
WebGLRenderingContext.getBufferParameter() - Web APIs
syntax any gl.getbufferparameter(target, pname); parameters target a glenum specifying the target buffer object. possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data. gl.element_array_buffer: buffer used for element indices. when using a webgl 2 context, the following values are available additionally: gl.copy_read_buffer: buffer for copying from one buffer object to another. gl.copy_write_buffer: buffer for copying from one buffer object to another. ...
...r object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer operations. gl.pixel_unpack_buffer: buffer used for pixel transfer operations. pname a glenum specifying information to query. possible values: gl.buffer_size: re
turns a glint indicating the size of the buffer in bytes. gl.buffer_usage: re
turns a glenum indicating the usage pattern of the buffer. this is either: gl.static_draw, gl.dynamic_draw, gl.stream_draw. when using a webgl 2 context, the following values are available additionally: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, g...
...either a glint or a glenum. examples gl.getbufferparameter(gl.array_buffer, gl.buffer_size); specifications specification status comment webgl 1.0the definition of 'getbufferparameter' in that specification. recommendation initial definition for webgl. ...
WebGLRenderingContext.getTexParameter() - Web APIs
the webglrenderingcontext.gettexparameter() method of the webgl api re
turns information about the given texture. syntax any gl.gettexparameter(target, pname); parameters target a glenum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. pname a glenum specifying the information to query. ...
...e values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. pname a glenum specifying the information to query. possible values: pname re
turn type description possible re
turn values available in a webgl 1 context gl.texture_mag_filter glenum texture magnification filter gl.linear (default value), gl.nearest. gl.texture_min_filter glenum texture minification filter gl.linear, gl.nearest, gl.nearest_mipmap_nearest, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear...
...y int values. gl.texture_max_lod glfloat texture maximum level-of-detail value any float values. gl.texture_min_lod glfloat texture minimum level-of-detail value any float values. gl.texture_wrap_r glenum wrapping function for texture coordinate r gl.repeat (default value), gl.clamp_to_edge, gl.mirrored_repeat. re
turn value re
turns the requested texture information (as specified with pname). if an error occurs, null is re
turned. examples gl.gettexparameter(gl.texture_2d, gl.texture_mag_filter); specifications specification status comment webgl 1.0the definition of 'gettexparameter' in that specification. recommendation initial definition for webgl. opengl es 2.0the ...
Boilerplate 1 - Web APIs
n-trivial css and html will be displayed on the pages of specific examples. in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context. by now, you should be able to understand what the function does. basically, it gets the webgl rendering context from the canvas element, initializes the drawing buffer, clears it black, and re
turns the initialized context. in case of error, it displays an error message and re
turns null. finally, all javascript code will run within an immediate function, which is a common javascript technique (see function). the function declaration and invocation will also be hidden. html <p>[ some descriptive text about the example. ]</p> <button>[ optional button element. ]</button> <canvas>your bro...
... « previousnext » ...
... « previousnext » ...
Clearing with colors - Web APIs
« previousnext » an example showing how to clear a webgl rendering context to a solid color. clearing the webgl context with a solid color the simplest graphical webgl program. set up the rendering context and then just clear it solid green. note that css sets the background color of the canvas to black, so when the canvas
turns green we know that webgl's magic has worked. in addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. first, we set the clear color to green, using the method clearcolor(). this only changes some internal state of webgl, but does not draw anything yet. next, we actually do the drawing by calling the clear() method. this is typical of how drawing is done with webgl. there is only a handful of methods for...
...em). all other methods are for setting and querying webgl state variables (such as the clear color). there are many "dials" and "switches" that affect drawing with webgl. the clear color is just the first of many you will get to know. this is why webgl/opengl is often called a state machine. by tweaking those "dials" and "switches" you can modify the internal state of the webgl machine, which in
turn changes how input (in this case, a clear command) translates into output (in this case, all pixels are set to green). finally, we note that color in webgl is usually in rgba format, that is four numerical components for red, green, blue and alpha (opacity). therefore, clearcolor() takes four arguments. <p>a very simple webgl program that shows some color.</p> <!-- text within a canvas element...
...g the webgl rendering context. var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); // if failed, inform user of failure. otherwise, initialize // the drawing buffer (the viewport) and clear the context // with a solid color. if (!gl) { paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; re
turn; } paragraph.innerhtml = "congratulations! your browser supports webgl. "; gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // set the clear color to darkish green. gl.clearcolor(0.0, 0.5, 0.0, 1.0); // clear the context with the newly set color. this is // the function call that actually does the drawing. gl.clear(gl.color_buffer_bit); }, false); the s...
Animating textures in WebGL - Web APIs
we set it to autoplay, mute the sound, and loop the video. we then set up two events to make sure the video is playing and the time has been updated. we need both of these checks because it will produce an error if you upload a video to webgl that has no data available yet. checking for both of these events guarantees there is data available and it's s...
... immediately. ...
...h, height, border, srcformat, srctype, pixel); //
turn off mips and set wrapping to clamp to edge so it // will work regardless of the dimensions of the video. ...
Using WebGL extensions - Web APIs
e compatible with multiple web browsers. it should also be used for extensions which originated with the opengl es or opengl apis, but whose behavior has been significantly altered. querying available extensions the webgl context supports querying what extensions are available. var available_extensions = gl.getsupportedextensions(); the webglrenderingcontext.getsupportedextensions() method re
turns an array of strings, one for each supported extension. extension list the current extensions are: angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel...
... ...
...ed using webglrenderingcontext.getextension(). for example: var float_texture_ext = gl.getextension('oes_texture_float'); the re
turn value is null if the extension is not supported, or an extension object otherwise. extension objects if an extension defines specific symbols or functions that are not available in the core specification of webgl, they will be available on the extension object re
turned by the call to gl.getextension(). ...
Introduction to WebRTC protocols - Web APIs
nnect with peers. there are many reasons why a straight up connection from peer a to peer b simply won’t work. it needs to bypass firewalls that would prevent opening connections, give you a unique address if like most situations your device doesn’t have a public ip address, and relay data through a server if your router doesn’t allow you to directly connect with peers. ice uses stun and/or
turn servers to accomplish this, as described below. stun session traversal utilities for nat (stun) (acronym within an acronym) is a protocol to discover your public address and determine any restrictions in your router that would prevent a direct connection with a peer. the client will send a request to a stun server on the internet who will reply with the client’s public address and whether or...
...private ip to the router’s public ip with a unique port. that way you don’t need a unique public ip for each device but can still be discovered on the internet. some routers will have restrictions on who can connect to devices on the network. this can mean that even though we have the public ip address found by the stun server, not anyone can create a connection. in this situation we need to
turn to
turn.
turn some routers using nat employ a restriction called ‘symmetric nat’. this means the router will only accept connections from peers you’ve previously connected to. traversal using relays around nat (
turn) is meant to bypass the symmetric nat restriction by opening a connection with a
turn server and relaying all information through that server. you would create a connection w...
...this obviously comes with some overhead so it is only used if there are no other alternatives. sdp session description protocol (sdp) is a standard for describing the multimedia content of the connection such as resolution, formats, codecs, encryption, etc. ...
WebRTC Statistics API - Web APIs
o peer. collecting statistics you can collect statistics at various levels throughout the webrtc hierarchy of objects. most broadly, you can call getstats() on an rtcpeerconnection to get statistics for the connection overall. in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second. that function, in
turn, uses getstats() to obtain statistics for the connection and to make use of that data. try { mypeerconnection = new rtcpeerconnection(pcoptions); statsinterval = window.setinterval(getconnectionstats, 1000); /* add event handlers, etc */ } catch(err) { console.error("error creating rtcpeerconnection: " + err); } function getconnectionstats() { mypeerconnection.getstats(null).then(sta...
...this object contains a map of named dictionaries based on rtcstats and its affiliated types. this example specifically looks for the report whose type is inbound-rtp and whose kind is video. this way, we look only at the video-related statistics for the local rtc...
...hat contributed to one of the connection's inbound rtp streams. rtcrtpcontributingsourcestats rtcstats data-channel statistics related to one rtcdatachannel on the connection. rtcdatachannelstats rtcstats ice-server statistics about the connection to an ice server (stun or
turn. rtciceserverstats rtcstats inbound-rtp statistics describing the state of one of the connection's inbound data streams. rtcinboundrtpstreamstats rtcreceivedrtpstreamstats rtcrtpstreamstats rtcstats ...
Lighting a WebXR setting - Web APIs
of actually calculating the true effect of light scattering. care needs to be taken to try to match the ambient light to what would really be the effect of the scene's lighting when doing this, however. ambient light can also be used to apply a color tint to a scene; for example, in a game in which the player has a special pair of yellow-tinted glasses, you can add a yellow ambient light. sa
turn's fifth-largest moon, tethys, bathed in sunlight, coming from the lower left. diffuse light diffuse light is light which is evenly and directionally emitted from or reflected off a surface. this is the majority of the light we usually see. diffuse light comes from a particular position or direction and casts shadows. due to its directionality, the faces of an object facing a diffuse light ...
...rection from which the light reaches the surface and the surface's normal vector or the vector perpendicular to the surface), the intensity or brightness of the light reflected by an object varies depending on the surface's orientation relative to the light source. a photo taken by nasa's cassini spacecraft showing specular reflection of light from a lake of liquid methane on the surface of sa
turn's moon titan. specular light specular light is the light that makes up the highlights on reflective objects, such as gems, eyes, shiny cups and plates, and the like. specular lights tend to appear as bright spots or squares on a surface at the point where a light source strikes the surface most directly. every light source is represented by some combination of ambient, diffuse, and/or spe...
... w3c. you can learn all about the proposed api and a fair amount about the concept of lighting estimation in the explainer documnent that's included in the specification's github repository. in essence, lighting estimation collects this information about the light sources and the shape and orientation of the objects in the scene, along with information about the materials they're made of, then re
turns data you can use to create virtual light source objects that approximately match the real world's lighting. the specifics of how lighting estimation works, especially in the context of the proposed api, is out of scope for the moment. once the api has stabilized, we'll update this documentation with the details. security and privacy concerns there are a number of potential security issues inv...
WebXR permissions and security - Web APIs
tsession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application. the document is considered trustworthy, in that it is responsible and is both currently active and has focus. the user's intent to enter immersive vr mode is well understood; see user intent below for details. if all of that is true, the promise re
turned by requestsession() is resolved, and the new xrsession object is passed into the fulfillment handler. otherwise, an appropriate exception is thrown, such as securityerror if the document doesn't have permission to enter immersive mode. inline presentation when you request an xrsession with the mode set to inline, and any features are required or requested, the browser will only allow the sess...
...ithin the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler. if the document making the request isn't the one which is responsible for the script, the request is denied. if the document making the request isn't trustworthy, the request is denied and false is re
turned through the promise's fulfillment routine. a trustworthy document is one which is both responsible and active, and which currently has focus. if the user's intent to open an inline xr presentation is not well understood, the request is denied. understanding of the user's intent may be either implicit or explicit. note: additional requirements may be put into effect due to the specific featu...
...to do or not. there are two kinds of user intent: implicit and explicit. explicit user intent (explicit user consent) is granted when the user has specifically and expressly been asked for permission to perform an action. implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: the user has interacted with the document in some way which has in
turn caused your request to occur. for example, if you have an "enter xr mode" button, and the user clicks it, calling requestsession() from the button's click event handler will permitted. if your code is executing during the launch of a web application, the runtime may consider the act of launching your web application to qualify as user intent. ...
Rendering and the WebXR frame animation callback - Web APIs
are vertical refresh rate when the browser is ready to refresh the <canvas> within which your webxr content is displayed, it calls your frame rendering callback, which uses the specified timestamp and any other relevant data, such as models and textures, as well as application state, to render the scene—as it should appear at the specified time—into the webgl backbuffer. when your callback re
turns, the browser transfers that backbuffer to the display or xr device, along with anything else that's changed since the last time the screen was refreshed. historically, displays have refreshed 60 times per second. this is due to early displays using the ac electrical grid's current flow waveform, which cycles 60 times per second in the united states (50 in europe), for timing purposes. this figu...
...s, we pass the xrview representing the eye we're drawing for (in order to perform perspective mapping and the like) and deltatime, so the scene drawing code can accurately represent the elapsed time when determining the positions of objects moving over time. when the loop that's iterating over the views ends, every image required to represent the scene to the viewer has been rendered, and upon re
turn, the framebuffer makes its way through the gpu and eventually to the xr device's display or displays. since we called requestanimationframe() at thee top of the function, our callback will be invoked once again when it's time to render the next frame of the scene's animation. drawbacks to this approach since it's important to minimize how much time you spend in this function as much as possible...
...e another in appropriate ways. for example, a virtual reality or augmented reality game might have enemy non-player characters being controlled by the computer and moving around the scene. not only are their locations in the world changing over time, but each npc likely has body parts or components that are moving in relation to one another. arms and legs swing as a creature walks, heads bob and
turn, hair bounces and sways, torsos expand and contract as the character breathes. in addition, there may be objects and structures in motion. in a sports game, there may be a ball arcing through the air, its movement needing to be simulated. in racing games there may be cars or other vehicles, with moving parts to animate including the wheels. if there's water in the scene, it needs ripples or wave...
WebXR Device API - Web APIs
ve either 3 or 6 degrees of freedom and might or might not have an external positional sensor. the equipment may also include an accelerometer, barometer, or other sensors which are used to sense when the user moves through space, rotates their head, or the like. ...
...r sensors which are used to sense when the user moves through space, rotates their head, or the like. accessing the webxr api to gain access to the webxr api within the context of a given window, use the navigator.xr property, which re
turns an xrsystem object through which the entire webxr device api is then exposed. navigator.xr read only this property, added to the navigator interface, re
turns the xrsystem object through which the webxr api is exposed. if this property is missing or null, webxr is not available. webxr interfaces xr the navigator.xr property re
turns the window's instance of xrsystem, which is the mechanism by which your code accesses the webxr api. using the xrsystem interface, you can create xrsessions to represent actual ar and/or vr sessions. xrframe while p...
...cation to augment the webgl context to allow it to be used to render views for display by a webxr device. webglrenderingcontextbase.makexrcompatibile() configures the webgl context to be compatible with webxr. if the context was not initially created with the xrcompatible property set to true, you must call makexrcompatible() prior to attempting to use the webgl context for webxr rendering. re
turns a promise which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by webxr. guides and tutorials the following guides and tutorials are a great resource to learn how to comprehend webxr and the underlying 3d and vr/ar graphics concepts. foundations and basics fundamentals of webxr before diving into the details of how to create conten...
Web Locks API - Web APIs
lock has been acquired. await do_something(); await do_something_else(); // now the lock will be released. }); while a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. the first queued request will be granted only when the lock is released. the api provides optional functionality that may be used as needed, including: re
turning 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 entr...
...locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins. the main entry point is navigator.locks.request() which requests a lock. it takes a lock name, an optional set of options, and a callback. the callback is invoked when the lock is granted. the lock is automatically released when the callback re
turns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. the request() method itself re
turns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. for example: await do_something_without_lock(); // request the loc...
...gin. this can be useful when debugging, for example, identifying why a lock could not be acquired. the results are a snapshot of the lock manager state, which identifies held and requested locks and some additional data (e.g. mode) about each, at the time the snapshot was taken. advanced use for more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can re
turn a promise explicitly resolved by the script: // capture promise control functions: let resolve, reject; const p = new promise((res, rej) => { resolve = res; reject = rej; }); // request the lock: navigator.locks.request('my_resource', lock => { // lock is acquired. re
turn p; // now lock will be held until either resolve() or reject() is called. }); deadlocks a deadlock occurs when a ...
Window: beforeunload event - Web APIs
the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. according to the specification, to show the confirmation dialog an event handler should call preventdefault() on the event. however note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods: assigning a string to the event's re
turnvalue property re
turning a string from the event handler. some browsers used to display the re
turned string in the confirmation dialog, enabling the event handler to display a custom message to the user. however, this is deprecated and no longer supported in most browsers. to combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has be...
...-memory page navigation caches, like firefox's back-forward cache or webkit's page cache. the html specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. see the html specification for more details. ...
... during this event. see the html specification for more details. examples the html specification states that authors should use the event.preventdefault() method instead of using event.re
turnvalue. however, this is not supported by all browsers. window.addeventlistener('beforeunload', (event) => { // cancel the event as stated by the standard. event.preventdefault(); // chrome requires re
turnvalue to be set. event.re
turnvalue = ''; }); specifications specification status comment html living standardthe definition of 'beforeunload' in that specification. living standard html5the definition of 'beforeunload' in that specification. recommendation initial definition ...
Window.getDefaultComputedStyle() - Web APIs
css properties of an element, ignoring author styling. that is, only user-agent and user styles are taken into account. syntax var style = window.getdefaultcomputedstyle(element [, pseudoelt]); parameters element the element for which to get the computed style. pseudoelt optional a string specifying the pseudo-element to match. must be null (or not specified) for regular elements. re
turn value the re
turned style is a cssstyledeclaration object. the object is of the same type as the object re
turned by window.getcomputedstyle(), but only takes into account user-agent and user rules. example simple example var elem1 = document.getelementbyid("elemid"); var style = window.getdefaultcomputedstyle(elem1); longer example <style> #elem-container { position: absolute; left: ...
...> use with pseudo-elements the getdefaultcomputedstyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). ...
...faultcomputedstyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.queryselector('h3'), result = getdefaultcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // re
turns 'none' </script> notes the re
turned value is, in certain known cases, expressly incorrect by deliberate intent. in particular, to avoid the so called css history leak security issue, browsers may expressly "lie" about the used value for a link and always re
turn values as if a user has never visited the linked site, and/or limit the styles that can be applied using the :visited pseudo-selector. see http://blog.mozilla.com/security...
window.postMessage() - Web APIs
ferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") re
turn; // ... } the properties of the dispatched message are: data the object passed from the other window. origin the origin of the window that sent the message at the time postmessage was called. this string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given prot...
...ecure.example.net"); // this will successfully queue a message to be sent to the popup, assuming // the window hasn't changed its location. popup.postmessage("hello there!", "http://example.com"); function receivemessage(event) { // do we trust the sender of this message? (might be // different from what we originally opened, for example). ...
... event.source.postmessage("hi there yourself! the secret response " + ...
Window.scrollX - Web APIs
the read-only scrollx property of the window interface re
turns the number of pixels that the document is currently scrolled horizontally. this value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. you can get the number of pixels the document is scrolled vertically from the scrolly property. syntax var x = window.scrollx; value in practice, the re
turned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled horizontally from the origin, where a positive value means the content is scrolled to the left. if the document is rendered on a subpixel-precise device, then the re
turned value is also subpixel-precise and may contain a decimal component. if the document isn't scrolled at all left or...
... example this example checks the current horizontal scroll position of the document. ...
... example this example checks the current horizontal scroll position of the document. if it's greater than 400 pixels, the window is scrolled back to the beginning. ...
Window.showModalDialog() - Web APIs
uri is the url of the document to display in the dialog. ...
... uri is the url of the document to display in the dialog. ...
... uri is the url of the document to display in the dialog. ...
WindowClient.focus() - Web APIs
the focus() method of the windowclient interface gives user input focus to the current client and re
turns a promise that resolves to the existing windowclient. syntax windowclient.focus().then(function(windowclient) { // do something with your windowclient once it has been focused }); parameters none. re
turn value a promise that resolves to the existing windowclient. example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; ...
... working draft initial definition. ...
... working draft initial definition. ...
WindowOrWorkerGlobalScope.btoa() - Web APIs
ring is treated as a byte of binary data). you can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again. for example, you can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. re
turn value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the ...
...de text as ascii using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. ...
... specifications specification status comment ...
WindowOrWorkerGlobalScope.fetch() - Web APIs
the promise resolves to the response object representing the response to your request. the promise does not reject on http errors — it only rejects on network errors. you must use then handlers to check for http errors. windoworworkerglobalscope is implemented by both window and workerglobalscope, which means that the fetch() method is available in pretty much any context in which you might want to fetch resources. ...
...value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). keepalive the keepalive option can be used to allow the request to outlive the page. fetch with the keepalive flag is a replacement for the navigator.sendbeacon() api. signal an abortsignal object instance; allows you to communicate with a fetch request and abort it if desired via an abortcontroller. re
turn value a promise that resolves to a response object. exceptions aborterror the request was aborted due to a call to the abortcontroller method abort() method. typeerror the specified url string includes user credentials. this information should instead be provided using an authorization header. examples in our fetch request example (see fetch request live) we create a new request object...
..., we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
this 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. ...
... this 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. ...
...p or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. re
turn value undefined. examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { th...
WorkerGlobalScope.location - Web APIs
it is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. syntax var locationobj = self.location; value a workerlocation object. ...
... specifications specification status comment html living standardthe definition of 'location' in that specification...
...00/worker.js" origin: "http://localhost:8000" pathname: "/worker.js" port: "8000" protocol: "http:" search: "" __proto__: workerlocation you could use this location object to re
turn more information about the document's location, as you might do with a normal location object. note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may re
turn strange results, but this should be fixed soon. specifications specification status comment html living standardthe definition of 'location' in that specification. living standard ...
WorkerGlobalScope.performance - Web APIs
the performance read-only property of the workerglobalscope interface re
turns a performance object to be used on the worker. not all performance properties and methods are available to web workers. this property is read only . syntax var perfobj = self.performance; re
turn value a performance object. example if you called console.log(performance); inside a worker (which would basically be the equivalent of self.console.log(self.performance);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: functi...
... specifications specification status comment high resolution time level 2the definition of 'performance' in that specification. recomme...
...ow: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: function now() { [native code] } __proto__: object you could use this performance object to re
turn performance data, as you might do with a normal performance object. note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may re
turn strange results, but this should be fixed soon. specifications specification status comment high resolution time level 2the definition of 'performance' in that specification. recommendation defines workerglobalscope.performance. ...
WorkerLocation - Web APIs
is available via the workerglobalscope.location property obtained by calling self.location. this interface is only visible from inside a javascript script executed in the context of a web worker. properties the workerlocation interface doesn't inherit any property, but implements properties defined in the urlutilsreadonly interface. urlutilsreadonly.href read only is a stringifier that re
turns a domstring containing the whole url of the script executed in the worker. urlutilsreadonly.protocol read only is a domstring containing the protocol scheme of the url of the script executed in the worker, including the final ':'. urlutilsreadonly.host read only is a domstring containing the host, that is the hostname, a ':', and the port of the url of the script executed in the worker. u...
...of the url of the script executed in the worker, including the final ':'. urlutilsreadonly.host read only is a domstring containing the host, that is the hostname, a ':', and the port of the url of the script executed in the worker. urlutilsreadonly.hostname read only is a domstring containing the domain of the url of the script executed in the worker. urlutilsreadonly.origin read only re
turns a domstring containing the canonical form of the origin of the specific location. urlutilsreadonly.port read only is a domstring containing the port number of the url of the script executed in the worker. urlutilsreadonly.pathname read only is a domstring containing an initial '/' followed by the path of the url of the script executed in the worker. urlutilsreadonly.search read only is ...
...'?' followed by the parameters of the url of the script executed in the worker. urlutilsreadonly.hash read only is a domstring containing a '#' followed by the fragment identifier of the url of the script executed in the worker. methods the workerlocation interface doesn't inherit any method, but implements methods defined in the urlutilsreadonly interface. urlutilsreadonly.tostring() re
turns a domstring containing the whole url of the script executed in the worker. it is a synonym for urlutilsreadonly.href. specifications specification status comment html living standardthe definition of 'workerlocation' in that specification. living standard ...
Sending and Receiving Binary Data - Web APIs
file as a blob by setting the string "blob" to the responsetype property. var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "blob"; oreq.onload = function(oevent) { var blob = oreq.response; // ... ...
...this tells the browser not to parse it, and to let the bytes pass through unprocessed. ...
...this tells the browser not to parse it, and to let the bytes pass through unprocessed. ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the xmlhttprequest method getallresponseheaders() re
turns all the response headers, separated by crlf, as a string, or re
turns null if no response has been received. if a network error happened, an empty string is re
turned. note: for multipart requests, this re
turns the headers from the current part of the request, not from the original channel. syntax var headers = xmlhttprequest.getallresponseheaders(); parameters none. re
turn value a bytestring representing all of the response's headers (except those whose field name is set-cookie or set-cookie2) separated by crlf, or null if no response has been received. if a network error happened, an empty string is re
turned. an example of what a raw header string looks like: date: fri, 08 dec 2017 21:04:30 gmt\r\n content-encoding: gzip\r\n...
... example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange. the code shows how to obtain the raw header string, as well as how to c...
...e: text/html; charset=utf-8\r\n connection: keep-alive\r\n strict-transport-security: max-age=63072000\r\n vary: cookie, accept-encoding\r\n content-length: 6502\r\n x-xss-protection: 1; mode=block\r\n each line is terminated by both carriage re
turn and line feed characters (\r\n). these are essentially delimiters separating each of the headers. note: in modern browsers, the header names are re
turned in all lower case, as per the latest spec. example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange. the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. var request = new xml...
XPathResult.iterateNext() - Web APIs
example the following example shows the use of the iteratenext() method. ...
... example the following example shows the use of the iteratenext() method. ...
... example the following example shows the use of the iteratenext() method. ...
XRInputSourceArray.keys() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
... examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
... examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
XRInputSourceArray.values() - Web APIs
for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. ...
... for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. ...
... for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. each pass through the loop, source is the next xrinputsource in the list. the loop exits once every input has been delivered to checkinput(). ...
XRInputSourceArray - Web APIs
the interface xrinputsourcearray represents a live list of webxr input sources, and is used as the re
turn value of the xrsession property inputsources. each entry is an xrinputsource representing one input device connected to the webxr system. in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets), methods are available to allow the use of iterators and the foreach() method is also available. properties the following properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list. ...
...ets), methods are available to allow the use of iterators and the foreach() method is also available. properties the following properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list. methods the following methods are available on xrinputsourcearray objects. you may also use the features of the symbol type. ...
...available. properties the following properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list. methods the following methods are available on xrinputsourcearray objects. you may also use the features of the symbol type. entries() re
turns an iterator you can use to walk the list of key/value pairs in the list. each item re
turned is an array whose first value is the index and whose second value is the xrinputsource at that index. foreach() iterates over each item in the list, in order from first to last. keys() a list of the keys corresponding to the entries in the input source list. values() re
turns an iterator you can use to go through all the values in the list. each item is a single xrinputsource object. in ...
XRPermissionDescriptor - Web APIs
e. examples the example below demonstrates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment. if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is called, specifying the permission descriptor we've established, xrpermissiondesc. ...
...rates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment. if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is called, specifying the permission descriptor we've established, xrpermissiondesc. when the re
turned promise resolves, we check the re
turned status. ...
... if the permission request promise is rejected, the error is handled (currently by just dumping it to the console using domxref("console.log()")}}). ...
XRReferenceSpace - Web APIs
e none at this time), xrreferencespace also inherits the properties of eventtarget. xrreferencespace defines no additional properties. methods in addition to the methods inherited from its parent interface, xrspace (there are none at this time), xrreferencespace inherits methods from eventtarget. xrreferencespace also provides the following methods. getoffsetreferencespace() creates and re
turns a new reference space object as the same type as the one on which you call the method (so, either xrreferencespace or xrboundedreferencespace). the new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space. this is useful for positioning objects while rendering, and to perform the needed transf...
...'s origin relative to the user's environment or location. this can happen, for example, after the user recalibrates their xr device, or if the device automatically adjusts its origin after losing and regaining tracking. in addition to using addeventlistener(), you can establish a reset event handler by setting the onreset event handler property. reference space types the reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is re
turned for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement t...
... space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
XRRigidTransform() - Web APIs
among other things, xrrigidtransform is used when providing a transform to translate between coordinate systems across spaces. syntax let xrrigidtransform = new xrrigidtransform(position, orientation); parameters position optional an object conforming to dompointinit which specifies the coordinates at which the point or object is located. these dimensions are specified in meters. if this parameter is left out or is not compatible with dompointinit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. ...
...this parameter is left out or is not compatible with dompointinit, the position used is assumed to be {x: 0, y: 0, z: 0, w: 1}. w must always be 1. orientation optional an object conforming to dompointinit which specifies the direction in which the object is facing. the default value for orientation is {x: 0, y: 0, z: 0, w: 1}. the specified orientation gets normalized if it's not already. re
turn value a new xrrigidtransform object which has been initialized to represent a transform matrix that would adjust the position and orientation of an object from the origin to the specified position and facing in the direction indicated by orientation. exceptions typeerror the value of the w coordinate in the specified position is not 1.0. examples in this example, the beginning of the ani...
...questing the first animation frame. let animationframerequestid = 0; xrsession.requestreferencespace("local-floor") .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerposition, viewerorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); after requesting a reference space of type local-floor, the re
turned promise is eventually resolved, at which time we receive a new reference space object, refspace. after creating an xrrigidtransform from the viewer's initial position and orientation, we pass the new transform into getoffsetreferencespace() to create another reference space, now offset so that its origin is located at the same place in space as the coordinates given by viewerposition, with the ...
XRSession.requestReferenceSpace() - Web APIs
the requestreferencespace() method of the xrsession interface re
turns a promise that resolves with an instance of either xrreferencespace or xrboundedreferencespace as appropriate given the type of reference space requested. syntax refspacepromise = xrsession.requestreferencespace(referencespacetype); parameters type a domstring specifying the type of reference space for which an instance is to be re
turned. the string must be one of those found in the xrreferencespacetype enumerated type. the reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is re
turned for each reference space type constant.. reference space descriptors the types of refer...
... space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
...ch the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace re
turn value a promise that resolves with an xrreferencespace object. exceptions rather than throwing true exceptions, requestreferencespace() rejects the re
turned promise with a domexception whose name is found in the list below: notsupportederror the requested reference space is not supported. specifications specification status comment webxr device apithe definition ...
XRSession: selectend event - Web APIs
nt property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() re
turns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the sele...
...h the object being dragged and the final target ray pose's transform. ...
...ectionevent); xrsession.addeventlistener("select", onselectionevent); xrsession.addeventlistener("selectend", onselectionevent); function onselectionevent(event) { let source = event.inputsource; let targetobj = null; if (source.targetraymode != "tracked-pointer") { re
turn; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { re
turn; } switch(event.type) { case "selectstart": targetobj = mybegintracking(targetraypose.matrix); break; case "select": mydropobject(targetobj, targetraypose.matrix); break; case "selectend": mystoptracking(targetobj, targetraypose.matrix); break; } } you can of course also set up a handler for selectend events by setting the xrsession object'...
XRSession: selectstart event - Web APIs
nt property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() re
turns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the sele...
...h the object being dragged and the final target ray pose's transform. ...
...ectionevent); xrsession.addeventlistener("select", onselectionevent); xrsession.addeventlistener("selectend", onselectionevent); function onselectionevent(event) { let source = event.inputsource; let targetobj = null; if (source.targetraymode != "tracked-pointer") { re
turn; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { re
turn; } switch(event.type) { case "selectstart": targetobj = mybegintracking(targetraypose.matrix); break; case "select": mydropobject(targetobj, targetraypose.matrix); break; case "selectend": mystoptracking(targetobj, targetraypose.matrix); break; } } you can of course also set up a handler for selectend events by setting the xrsession object'...
XRSession: squeezeend event - Web APIs
t property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() re
turns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the squ...
...d with the object being dragged and the final target ray pose's transform. ...
... onsqueezeevent); xrsession.addeventlistener("squeeze", onsqueezeevent); xrsession.addeventlistener("squeezeend", onsqueezeevent); function onsqueezeevent(event) { let source = event.inputsource; let targetobj = null; if (source.targetraymode != "tracked-pointer") { re
turn; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { re
turn; } switch(event.type) { case "squeezestart": targetobj = mybegintracking(targetraypose.matrix); break; case "squeeze": mydropobject(targetobj, targetraypose.matrix); break; case "squeezeend": mystoptracking(targetobj, targetraypose.matrix); break; } } you can of course also set up a handler these events by setting the xrsession object's ons...
XRSession: squeezestart event - Web APIs
t property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up. mybegintracking() re
turns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). the squ...
...d with the object being dragged and the final target ray pose's transform. ...
... onsqueezeevent); xrsession.addeventlistener("squeeze", onsqueezeevent); xrsession.addeventlistener("squeezeend", onsqueezeevent); function onsqueezeevent(event) { let source = event.inputsource; let targetobj = null; if (source.targetraymode != "tracked-pointer") { re
turn; } let targetraypose = event.frame.getpose(source.targetrayspace, myrefspace); if (!targetraypose) { re
turn; } switch(event.type) { case "squeezestart": targetobj = mybegintracking(targetraypose.matrix); break; case "squeeze": mydropobject(targetobj, targetraypose.matrix); break; case "squeezeend": mystoptracking(targetobj, targetraypose.matrix); break; } } you can of course also set up a handler these events by setting the xrsession object's ons...
XRSystem: requestSession() - Web APIs
while only one immersive vr session can be active at a time, multiple inline sessions can be in progress at once. syntax var sessionpromise = xr.requestsession(sessionmode, sessioninit) parameters sessionmode a domstring whose value is one of those included in the xrsessionmode enum. the supported modes are: immersive-ar the session's output will be given exclusive access to the immersive device, but the rendered content will be blended with the real-world environment. ...
...ons can be presented in either mono or stereo mode, and may or may not have viewer tracking available. inline sessions don't require special hardware and should be avalable on any user agent offering webxr api support. sessioninit optional a xrsessioninit object providing options to configure the new xrsession. see specifying session options for details on how to configure a webxr session. ...
...port. sessioninit optional a xrsessioninit object providing options to configure the new xrsession. see specifying session options for details on how to configure a webxr session. re
turn value a promise that resolves with an xrsession object if the device and user agent support the requested mode and features. exceptions this method doesn't throw true exceptions; instead, it rejects the re
turned promise, passing into it a domexception whose name is one of the following: invalidstateerror the requested session mode is immersive-vr but there is already an immersive vr session either currently active or in the process of being set up. there can only be one immersive vr session at a time. notsupportederror there is no webxr-compatible device available, or the device does not support ...
XRViewerPose.views - Web APIs
for monoscopic devices, this array contains a single view. important: there is no guarantee that the number of views will remain constant over the lifetime of an xrsession. for each frame, you should always use the current length of this array rather than caching the value. stereo views require two views to render properly, with the left eye's view having its eye set to the string left and the right eye's view a value of right. ...
...urrent viewer pose. this array's length may potentially vary over the lifetime of the xrsession (for example, if the viewer enables or disables stereo mode on their xr output device). examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space. if a valid pose is re
turned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. let pose = frame.getviewerpose(xrreferencespace); if (pose) { let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0, 0, 0, 1); gl.cleardepth(1); gl.clear(gl.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example. you can see more context and see much more on that page. specifications specification status comment ...
XRViewerPose - Web APIs
he xrviewerpose can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing. the viewer's pose for the animation frame represented by xrframe can be obtained by calling the frame's getviewerpose() method, specifying the reference space in which the origin's position should be computed. ...
...n which the origin's position should be computed. the re
turned xrviewerpose tells you where the viewer is and what direction they're facing at the time at which the frame takes place. examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space. if a valid pose is re
turned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. let pose = frame.getviewerpose(xrreferencespace); if (pose) { let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0, 0, 0, 1); gl.cleardepth(1); gl.clear(gl.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example. you can see more context and see much more on that page. specifications specification status comment ...
XRWebGLLayer() - Web APIs
syntax let gllayer = new xrwebgllayer(session, context, layerinit); parameters session an xrsession object specifying the webxr session which will be rendered using the webgl context. context a webglrenderingcontext or webgl2renderingcontext identifying the webgl drawing context to use for rendering the scene for the specified webxr session. layerinit optional an object conforming to the xrwebgllayerinit dictionary, providing configuration options for the new xrwebgllayer. ...
...value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. the default is true. framebufferscalefactor optional a floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. the static xrwebgllayer function xrwebgllayer.getnativeframebufferscalefactor() re
turns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. the default is 1.0. ignoredepthvalues optional a boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. the default is false. stencil optional a boolean value which, if true, requests that the new l...
...at the device's native resolution. the default is 1.0. ignoredepthvalues optional a boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. the default is false. stencil optional a boolean value which, if true, requests that the new layer include a stencil buffer. otherwise, no stencil buffer is allocated. the default is false. re
turn value a newly-created xrwebgllayer which links the specified xrsession to the webgl context given by context, which will be used as the renderer for the session. any options specified in layerinit are used to tailor the rendering system's configuration. exceptions invalidstateerror the new xrwebgllayer could not be created due to one of a number of possible state errors: the xrsessio...
ARIA Test Cases - Accessibility
he new open/closed state should be spoken. markup used: notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 fail. label and current content as well as role are spoken, also when typing in a new value, that gets reflected. but when dropping down the lists of states in either example, after the second or so list item, jaws
turns off forms mode, and the user has to
turn off v cursor to be able to make selections or tab to anything useful. - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - datep...
... it should still be possible to the document/browse/virtual mode back on markup used: role="application" notes: results: at firefox ie opera safari jaws 9 fail fail n/a n/a jaws 10 pass with slight problems in the menu bar (wrong order of events or mi...
...and button-controlled changes expected at behavior: (al) minimal: the screen reader should utilize the politeness level to read changes that occur. (al) optional but desired: the screen reader should announce updates to a live region where the region changes are the result of a user action. this should even if the user does not set aria-live, and for any value other than aria-live="off". it
turns out that using aria-controls is actually not the best way to determine this in all browsers. there is often a way to determine if a change was caused by user input. markup used: aria-controls, aria-live="polite" notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 - - - - voiceover (leopard) n/a ...
ARIA: grid role - Accessibility
s of the grid, the aria-readonly should be set to true. the default value is false. for many use cases, an html table element is sufficient as it and its elements already include many aria roles. keyboard interactions when a keyboard user encounters a grid, they navigate the rows and columns using the left, right, top and down keys. to activate the interactive component, they will use the re
turn and space keys. key action → moves focus one cell to the right. if focus is on the right-most cell in the row, focus does not move. ← moves focus one cell to the left. if focus is on the left-most cell in the row, focus does not move. ↓ moves focus one cell down. if focus is on the bottom cell in the column, focus does not move. ...
...1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); re
turn true; } else { re
turn false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); ...
...1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); re
turn true; } else { re
turn false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); ...
ARIA: listbox role - Accessibility
with descendant <option> elements handles all the needed interactions natively. examples example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code. ...
...all the needed interactions natively. examples example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code. ...
...s example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code. ...
ARIA: textbox role - Accessibility
he input of free-form text. whenever possible, rather than using this role, use an <input> element with type="text", for single-line input, or a <textarea> element for multi-line input. description when an element has the textbox role, the browser sends an accessible textbox event to assistive technologies, which can then notify the user about it. the default is a single line input, in which re
turn or enter submits the form; in this case, it is preferable to use an html <input> with type="text". to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="true". including the html contenteditable attribute ensures the text node is editable. <!-- simple text input field --> <div id="txtboxlabel">enter your five-digit zipcode</div> <div role="text...
... that contains the list of suggested values. additionally, either the textbox or a containing element with role combobox has a value for aria-haspopup that matches the role of the element that contains the list of suggested values. aria-multiline attribute if aria-multiline="true" is set, the at informs the user that the textbox supports multi-line input, with the expectation that enter or re
turn will create a line break rather than submitting the form. aria does not alter the behavior of the element; rather this feature must be controlled by the developer. if false is set, or the the attribute is omitted and defaults to false, the user expectation is that the control is a single line text box, and enter or re
turn submits the form. aria-placeholder attribute represents a hint (word or ...
...a-readonly, use the semantic <input type="text"> or <textarea> with a readonly attribute. aria-required attribute indicates that a value must be provided for the field before it is submitted. instead of using aria-required, use the semantic <input type="text"> or <textarea> with a required attribute. keyboard interactions in a single-line use (when aria-multiline is false or not used), the re
turn or enter key submits the form. in a multi-line use (when aria-multiline is true), re
turn or enter key inserts a line break. javascript features all features associated with any and all properties and states must be maintained, and forms submission on enter or re
turn on a single line textbox needs to be handled. focus event handler and aria-activedescendent attribute if you are implementing ...
Cognitive accessibility - Accessibility
logged out after 30 minutes or having 15 minutes to make a purchase. people with cognitive disabilities may require more time to read content, or to perform functions such as filling out forms. solutions include providing users enough additional time to complete tasks or eliminate time constraints altogether. timers options for adjusting time requirements include: allowing the user to
turn off or adjust the time to at least 10 times the original limit before encountering it. alerting the user and providing a buffer of at least 20 seconds to extend the timeout duration by a factor of 10 with a simple action, such as hitting the space bar. provide a toggle on content that allows users to enable a longer session time limit, or no session time limit at all. examples of timed conten...
... page in order to best understand the site's layout, content, and concepts. ability to bypass blocks of content providing a mechanism, such as a skiplink, to bypass blocks of content that are repeated on multiple web pages. focus order makes sense the order of focus for interactive elements should make sense. to achieve this, the dom order should match the visual order, which in
turn should match the tabbing order. if the tab order jumps around, especially in a way that does not match the visual order when navigating with a keyboard, users can become disoriented. focused elements should be visibly focused when a user navigates using a keyboard, the ui should make it obvious which element currently has focus. don't alter or remove the browser's default :focus styling, unless...
...w a word is pronounced. providing guidance on how to pronounce words helps many different kinds of people, including those who prefer to read aloud, non-native language speakers, and people who may unfamiliar with the meaning of a term in context. another solution is to use glyphs or diacritical marks to illustrate pronunciation. however, if this technique is used, there must be a mechanism to
turn it off. further, it is helpful to link to a guide to the marks being used, as their meaning may not be obvious. predictability wcag guideline 3.2 states "make web pages appear and operate in predictable ways." this is a tenet of good user experience design. consistency is especially important for people with cognitive difficulties. this includes consistency in page layout and predictable intera...
Keyboard-navigable JavaScript widgets - Accessibility
"-1">right</li> <li id="justify" tabindex="-1">justify</li> </ul> </li> </ul> disabled controls when a custom control becomes disabled, remove it from the tab order by setting tabindex="-1". note that disabled items within a grouped widget (such as menu items in a menu) should remain navigable using arrow keys. managing focus inside groups when a user tabs away from a widget and re
turns, focus should re
turn to the specific element that had focus, for example, the tree item or grid cell. there are two techniques for accomplishing this: roving tabindex: programmatically moving focus aria-activedescendant: managing a 'virtual' focus technique 1: roving tabindex setting the tabindex of the focused element to "0" ensures that if the user tabs away from the widget and then ret...
...ce the same changes. ensure that the keyboard can be used to activate element to ensure that the keyboard can be used to activate elements, any handlers bound to mouse events should also be bound to keyboard events. for example, to ensure that the enter key will activate an element, if you have an onclick="dosomething()", you should bind dosomething() to the key down event as well: onkeydown="re
turn event.keycode != 13 || dosomething();". always draw the focus for tabindex="-1" items and elements that receive focus programatically ie will not automatically draw the focus outline for items that programatically receive focus. choose between changing the background color via something like this.style.backgroundcolor = "gray"; or add a dotted border via this.style.border = "1px dotted invert".
... have an invisible 1px border to start with, so that the element doesn't grow when the border style is applied (borders take up space, and ie doesn't implement css outlines). prevent used key events from performing browser functions if your widget handles a key event, prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's re
turn code. if your event handler re
turns false, the event will not be propagated beyond your handler. for example: <span tabindex="-1" onkeydown="re
turn handlekeydown();"> if handlekeydown() re
turns false, the event will be consumed, preventing the browser from performing any action based on the keystroke. don't rely on consistent behavior for key repeat, at this point unfortunately onkeydown may...
Operable - Accessibility
d where possible (e.g. tabbing through form controls), and you should only build in custom functionality where needed. see ui controls and building keyboard accessibility back in 2.1.2 no keyboard trap (a) when entering a section of functionality using the keyboard, you should be able to get out of that section again using *only* the keyboard. for example, if you press enter/re
turn on a focused button to open an options window, you should be able to close that window again and re
turn to the main content using the keyboard. this is very important so that keyboard users do not get trapped on specific sections of your apps. 2.1.3 keyboard — all functionality (aaa) this is a further step beyond criterion 2.1.1. to achieve aaa conformance, all function...
... further step beyond criterion 2.1.1. to achieve aaa conformance, all functionality should be accessible using keyboard controls — with no exceptions. see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be
turned off, remapped or are only active when the relevant user interface component is in focus. understanding character key shortcuts note: also see the wcag description for guideline 2.1 keyboard accessible: make all functionality available from a keyboard. guideline 2.2 — enough time: provide users enough time to read and use content this guideline covers situations in which function...
... example, purchases sometimes need to be completed within a time limit for security reasons. success criteria how to conform to the criteria practical resource 2.2.1 timing is adjustable (a) for functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or
turn off the time limit. exceptions to this are activities with time limits longer than 20 hours, real time events (e.g. live multiplayer games), and any other activity that requires a time limit and would be invalidated if it were
turned off. 2.2.2 pausing, stopping, hiding (a) for moving/blinking content that starts automatically, lasts longer than 5 seconds, and is sho...
OpenType font features guide - CSS: Cascading Style Sheets
will provide sample pages and css just for this very reason). but there are some sites that make it easier to figure out. you can visit wakamaifondue.com, drop your font file on the circle where instructed and in a few moments you'll have a full report on all the capabilities and features of your font. axis-praxis.org also offers a similar capability, with the ability to click on the features to
turn them on or off in a given text block. why you would use them? given that these features take a bit of work to discover and use, it may seem a fair question to ask why one would bother to use them. the answer lies in the specific features that will make a site more useful, readable, and polished: ligatures like 'ff' or 'fi' make letter spacing and reading more even and smooth. fractions can ...
... set as 'oldstyle' sit more comfortably between lower-case letters, and likewise setting them as 'tabular numbers' will make them line up better when setting a list of costs in a table say. 'lining' figures on the other hand sit more uniformly on their own or in front of capitalized words. while none of these features individually will render a site useless due to their absence, each of them in
turn can make a site easier to use and more memorable for its attention to detail. opentype features are like secret compartments in fonts. unlock them and you'll find ways to make fonts look and behave differently in subtle and dramatic ways. not all opentype features are appropriate to use all of the time, but some features are critical for great typography. -- tim brown, head of typography at ado...
...lable for finding more of them. the general syntax looks like this: .small-caps { font-feature-settings: "smcp", "c2sc"; } according to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it. ...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
are setting the two starts, then the two ends. it becomes much more logical once you know! mixed writing modes and grid layout in addition to displaying documents, using the correct writing mode for the language, writing modes can be used creatively within documents that are otherwise ltr. in this next example i have a grid layout with a set of links down one side. ...
...celery potato scallion desert raisin horseradish spinach carrot soko. lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. brussels sprout coriander water chestnut gourd...
...t green bean swiss chard seakale pumpkin onion chickpea gram corn pea. brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p> <p>nori grape silver beet broccoli kombu beet greens fava bean potato quandong celery. bunya nuts black-eyed pea prairie
turnip leek lentil
turnip greens parsnip. sea lettuce lettuce water chestnut eggplant winter purslane fennel azuki bean earthnut pea sierra leone bologi leek soko chicory celtuce parsley jícama salsify.</p> </div> <nav> <ul> <li><a href="">link 1</a></li> <li><a href="">link 2</a></li> <li><a href="">link 3</a></li> ...
Cubic Bezier Generator - CSS: Cascading Style Sheets
<html> <canvas id="bezier" width="336" height="336"> </canvas> <form> <label for="x1">x1 = </label><input onchange="updatecanvas();" type="text" maxlength=6 id="x1" value="0.79" class='field'> <label for="y1">y1 = </label><input onchange="updatecanvas();re
turn true;" type="text" maxlength=6 id="y1" value="0.33" class='field'> <label for="x2">x2 = </label><input onchange="updatecanvas();re
turn true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updatecanvas();re
turn true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">log</output> </form> </html> .field { width: 40px; } function updatecanvas() { var x1 =...
...as.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); scaling = math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mousedown; canvas.onmouseup = mouseup; } else { alert('you need safari or firefox 1.5+ to see this demo.'); } } function cx(x) { re
turn x * scaling + rulers; } function reversex(x) { re
turn (x - rulers) / scaling; } function lx(x) { //used when drawing vertical lines to prevent subpixel blur var result = cx(x); re
turn math.round(result) == result ? result + 0.5 : result; } function cy(y) { re
turn (1 - y) * scaling + margin; } function reversey(y) { re
turn (margin - y) / scaling + 1; } function ly(y) ...
...x) { //used when drawing vertical lines to prevent subpixel blur var result = cx(x); re
turn math.round(result) == result ? result + 0.5 : result; } function cy(y) { re
turn (1 - y) * scaling + margin; } function reversey(y) { re
turn (margin - y) / scaling + 1; } function ly(y) { // used when drawing horizontal lines to prevent subpixel blur var result = cy(y); re
turn math.round(result) == result ? result + 0.5 : result; } function drawbeziercurve(x1, y1, x2, y2) { // get the canvas element using the dom var canvas = document.getelementbyid('bezier'); // make sure we don't execute when canvas isn't supported if (canvas.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); ...
image-orientation - CSS: Cascading Style Sheets
*/ syntax values none default initial value. will not apply any additional image rotation; the image is oriented as encoded or as other css property values dictate. from-image the exif information contained in the image will be used to rotate the image appropriately. <angle> obsolete since gecko 63 the <angle> of rotation to apply to the image. it is rounded to the nearest 90deg (0.25
turn). flip obsolete since gecko 63 the image is flipped horizontally (i.e., reflected) after the rotation given by the <angle> value is applied. if no <angle> is given, 0deg is used. description this property is intended only to be used for the purpose of correcting the orientation of images which were shot with the camera rotated. it should not be used for arbitrary rotations. for any purpose...
...changes to the orientation of the image, or changes required for printing in portrait versus landscape orientation. if used in conjunction with other css properties, such as a <transform-function>, any image-orientation rotation is applied before any other transformations. ...
...r printing in portrait versus landscape orientation. if used in conjunction with other css properties, such as a <transform-function>, any image-orientation rotation is applied before any other transformations. ...
Event reference
as the listener attached or off one of its children. mouseover mouseevent dom l3 a pointing device is moved onto the element that has the listener attached or onto one of its children. mouseup mouseevent dom l3 a pointing device button is released over an element. nomatch speechrecognitionevent web speech api the speech recognition service re
turns a final result with no significant recognition. notificationclick notificationevent notifications apithe definition of 'onnotificationclick' in that specification. a system notification spawned by serviceworkerregistration.shownotification() has been clicked. offline event html5 offline the browser has lost access to the network. online event ...
... svg a smil animation element is repeated. reset event dom l2, html5 a form is reset. resize uievent dom l3 the document view has been resized. resourcetimingbufferfull performance resource timing the browser's resource timing buffer is full. result speechrecognitionevent web speech api the speech recognition service re
turns a result — a word or phrase has been positively recognized and this has been communicated back to the app. resume speechsynthesisevent web speech api a paused utterance is resumed. scroll uievent dom l3 the document view or an element has been scrolled. seeked event html5 media a seek operation completed. seeking event ht...
...ase with a version number higher than its current version. a versionchange transaction has been created. userproximity userproximityevent proximity sensor fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not). voiceschanged event web speech api the list of speechsynthesisvoice objects that would be re
turned by the speechsynthesis.getvoices() method has changed (when the voiceschanged event fires.) versionchange indexeddb a versionchange transaction completed. visibilitychange event page visibility the content of a tab has become visible or has been hidden. volumechange event html5 media the volume has changed. waiting event html...
Cross-browser audio basics - Developer guides
is no stop method — to implement a stop function, you'd have to pause the media then set the currenttime property value to 0. canplaytype the canplaytype() method asks the browser whether a certain audio file type is supported. it takes the mime type of the type to check as a parameter. if (myaudio.canplaytype('audio/mpeg')) { // it's supported. // do something here! } canplaytype() re
turns one of three values: probably maybe "" (an empty string) in practice, we usually check if the result is true or false. non-empty strings are true. note: a very early spec specified that the browser should re
turn no instead of an empty string, but thankfully the number of people using older browsers that implement this version of the spec are few and far between. currenttime the curre...
... //update something related to playback progress }); playing the playing event is initiated when playback is ready to start after having being paused due to lack of media data. waiting the waiting event is triggered when playback has stopped due to lack of media data, although it is expected to resume once data becomes available. play the play event is initiated after the play() method is re
turned or when the autoplay attribute has caused playback to begin. this is when the state of the media switches from paused to playing. pause the pause event is triggered after the pause() method is re
turned. this is when the states switch from playing to paused. ended the ended event is initiated when the end of the media is reached. myaudio.addeventlistener("ended", function() { //do somethi...
... myaudio.currenttime = clicktime; }); buffering ok, we're getting there, but there is another piece of useful information we can display: the amount of audio has been buffered or downloaded in advance. there are a couple of properties we haven't looked at yet, buffered and seekable. buffered this property lets us know which parts of the audio has been buffered (downloaded in advance). it re
turns something called a timeranges object. mybufferedtimeranges = myaudio.buffered; seekable the seekable property informs you of whether you can jump directly to that part of the media without further buffering. myseekabletimeranges = myaudio.seekable; buffering events there are also a couple of events related to buffering: seeking the seeking event is fired when media is being sought. se...
Audio and Video Delivery - Developer guides
points in the media's content. this is done by setting the value of the currenttime property on the element; see htmlmediaelement for further details on the element's properties. simply set the value to the time, in seconds, at which you want playback to continue. you can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. ...
...s. simply set the value to the time, in seconds, at which you want playback to continue. you can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. this re
turns a timeranges object listing the ranges of times that you can seek to. ...
... to continue. you can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. this re
turns a timeranges object listing the ranges of times that you can seek to. var mediaelement = document.queryselector('#mediaelementid'); mediaelement.seekable.start(0); // re
turns the starting time (in seconds) mediaelement.seekable.end(0); // re
turns the ending time (in seconds) mediaelement.currenttime = 122; // seek to 122 seconds mediaelement.played.end(0); // re
turns the number of seconds the browser has played specifying playback range when specifying the uri of media for an <audio> or <video> element, you can optionally include additional information to specify the portion of the media to play. to do this, append a hash mark ("...
Constraint validation - Developer guides
> element itself. the constraint validation is done in the following ways: by a call to the checkvalidity() or reportvalidity() method of a form-associated dom interface, (htmlinputelement, htmlselectelement, htmlbuttonelement, htmloutputelement or htmltextareaelement), which evaluates the constraints only on this element, allowing a script to get this information. the checkvalidity() method re
turns a boolean indicating whether the element's value passes its constraints. (this is typically done by the user-agent when determining which of the css pseudo-classes, :valid or :invalid, applies.) in contrast, the reportvalidity() method reports any constraint failures to the user. by a call to the checkvalidity() or reportvalidity() method on the htmlformelement interface. by submitting the for...
... visual styling of constraint validation apart from setting constraints, web developers want to control what ...
...tting a custom validity message on fieldset elements will not prevent form submission in most browsers. <input> <output> <select> submit buttons (created with either a <button> element with the submit type, or an input element with the submit type. other types of buttons do not participate in constraint validation. <textarea> the validitystate interface describes the object re
turned by the validity property of the element types listed above. it represents various ways that an entered value can be invalid. together, they help explain why an element's value fails to validate, if it's not valid. ...
Parsing and serializing XML - Developer guides
o parse xml content and convert it into a dom tree, or, conversely, serialize an existing dom tree into xml. in this article, we'll look at the objects provided by the web platform to make the common tasks of serializing and parsing xml easy. xmlserializer serializes dom trees, converting them into strings containing xml. domparser constructs a dom tree by parsing a string containing xml, re
turning a xmldocument or document as appropriate based on the input data. xmlhttprequest loads content from a url; xml content is re
turned as an xml document object with a dom tree built from the xml itself. xpath a technology for creating strings that contain addresses for specific portions of an xml document, and locating xml nodes based on those addresses. creating an xml document using one ...
...if the document is xml, the resulting object is actually a xmldocument. the two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well. note: there is in fact an ht...
...if the document is xml, the resulting object is actually a xmldocument. ...
<img>: The Image Embed element - HTML: Hypertext Markup Language
non-visual browsers may omit it from rendering. visual browsers will also hide the broken image icon if the alt is empty and the image failed to display. this attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark. crossorigin indicates if the fetching of the image must be done using a cors request. image data from a cors-enabled image re
turned from a cors request can be reused in the <canvas> element without being marked "tainted". if the crossorigin attribute is not specified, then a non-cors request is sent (without the origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements. if the crossorigin attribute is specified, then a cors reques...
...browser may use its own heuristics to prioritize the image. high: the image is of high priority. low: the image is of low priority. intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute. specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would re
turn the values specified in this attribute. explainer, examples ismap this boolean attribute indicates that the image is part of a server-side map. if so, the coordinates where the user clicked on the image are sent to the server. note: this attribute is allowed only if the <img> element is a descendant of an <a> element with a valid href attribute. this gives users without pointing devices a fa...
...stance, have no intrinsic dimensions if their root <svg> element doesn't have a width or height set on it. examples alternative text the following example embeds an image into the page and includes alternative text for accessibility. <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="mdn logo"> image link this example builds upon the previous one, showing how to
turn the image into a link. to do so, nest the <img> tag inside the <a>. you should made the alternative text describe the resource the link is pointing to, as if you were using a text link instead. <a href="https://developer.mozilla.org"> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="visit the mdn site"> </a> using the srcset attribute in this example we includ...
<input type="search"> - HTML: Hypertext Markup Language
other explanatory text nearby. see the section specifying a pattern for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...llow autocorrect while editing this input field. safari only. incremental whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. webkit and blink only (safari, chrome, opera, etc.). mozactionhint a string indicating the type of action that will be taken when the user presses the enter or re
turn key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. firefox for android only. results the maximum number of items that should be displayed in the drop-down list of previous search queries. safari only. autocorrect a safari extension, the autocorrect attribute is a string which indicates whether or not to activate au...
... input as a live search. as the user edits the value of the field, the user agent sends search events to the htmlinputelement object representing the search box. this allows your code to update the search results in real time as the user edits the search. if incremental is not specified, the search event is only sent when the user explicitly initiates a search (such as by pressing the enter or re
turn key while editing the field). the search event is rate-limited so that it is not sent more more frequently than an implementation-defined interval. mozactionhint a mozilla extension, supported by firefox for android, which provides a hint as to what sort of action will be taken if the user presses the enter or re
turn key while editing the field. this information is used to decide what kind ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
eader), the image will be tainted and its usage restricted. when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. see cors settings attributes for additional information. currenttime reading currenttime re
turns a double-precision floating-point value indicating the current playback position of the media specified in seconds. if the media has not started playing yet, the time offset at which it will begin is re
turned. setting currenttime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. if the media is being streamed, it's possi...
...tached using wired (hdmi, dvi, etc.) and wireless technologies (miracast, chromecast, dlna, airplay, etc). in safari, you can use x-webkit-airplay="deny" as a fallback. duration read only a double-precision floating-point value which indicates the duration (total length) of the media in seconds, on the media's timeline. if no media is present on the element, or the media is not valid, the re
turned value is nan. if the media has no known end (such as for live streams of unknown duration, web radio, media incoming from webrtc, and so forth), this value is +infinity. height the height of the video's display area, in css pixels (absolute values only; no percentages.) intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the s...
...o forth), this value is +infinity. height the height of the video's display area, in css pixels (absolute values only; no percentages.) intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute. specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would re
turn the values specified in this attribute. explainer, examples loop a boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video. muted a boolean attribute that indicates the default setting of the audio contained in the video. if set, the audio will be initially silenced. its default value is false, meaning that the audio will be pl...
HTML documentation index - HTML: Hypertext Markup Language
dy>: the document body element element, html, reference, sectioning root element, sections, web the html <body> element represents the content of an html document. there can be only one <body> element in a document. 74 <br>: the line break element element, html, html text-level semantics, reference, web the html <br> element produces a line break in text (carriage-re
turn). it is useful for writing a poem or an address, where the division of lines is significant. 75 <button>: the button element element, forms, html, html forms, reference, web the html <button> element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality. 76 <canvas>: the graphics canvas element ...
...olete html no frames or frame fallback element, <noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element. 167 <noscript> element, html, html scripting, reference, web the html <noscript> element defines a section of html to be inserted if a script type on the page is unsupported or if scripting is currently
turned off in the browser. 168 <object> element, html, html embedded content, reference, web the html <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. 169 <ol>: the ordered list element element, html, html grouping content, html:flow content, reference the ht...
...for later evaluation. 227 link types: noopener attribute, html, link types, reference the noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it re
turns null). 228 link types: noreferrer attribute, html, link types, reference the noreferrer keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser, when navigating to the target resource, to omit the referer header and otherwise leak no referrer information — and additionally to behave as if the noopener keyword were also specified. ...
Browser detection using the user agent - HTTP
e user is suspected to support look-behind regexps // do not use /(?<=[a-z])/. it will cause a syntax error in // browsers that do not support look-behind expressions // because all browsers parse the entire script, including // sections of the code that are never executed. ...
...ssions // because all browsers parse the entire script, including // sections of the code that are never executed. var camelcaseexpression = new regexp("(?<=[a-z])"); var splitupstring = function(str) { re
turn (""+str).split(camelcaseexpression); }; } else { /*this fallback code is much less performant, but works*/ var splitupstring = function(str){ re
turn str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; } console.log(splitupstring("foobare")); // ["foob", "are"] console.log(splitupstring("jqwhy")); // ["jq", "w", "hy"] the above code would have made several incorrect assumptions: it assumed that all user agent strings that include the substring "chrome" are chrome. ua strings are notoriously misleading. it assumed that the lookbeh...
...r support of the feature itself instead: var islookbehindsupported = false; try { new regexp("(?<=)"); islookbehindsupported = true; } catch (err) { // if the agent doesn't support lookbehinds, the attempted // creation of a regexp object using that syntax throws and // islookbehindsupported remains false. } var splitupstring = islookbehindsupported ? function(str) { re
turn (""+str).split(new regexp("(?<=[a-z])")); } : function(str) { re
turn str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; as the above code demonstrates, there is always a way to test browser support without user agent sniffing. there is never any reason to check the user agent string for this. lastly, the above code snippets bring about a critical issue with cross-browser coding that mu...
Cross-Origin Resource Sharing (CORS) - HTTP
der, instead of specifying the "*" wildcard. because the request headers in the above example include a cookie header, the request would fail if the value of the access-control-allow-origin header was "*". but it does not fail: because the value of the access-control-allow-origin header is "http://foo.example" (an actual origin) rather than the "*" wildcard, the credential-cognizant content is re
turned to the invoking web content. note that the set-cookie response header in the example above also sets a further cookie. in case of failure, an exception—depending on the api used—is raised. third-party cookies note that cookies set in cors responses are subject to normal third-party cookie policies. in the example above, the page is loaded from foo.example, but the cookie on line 20 is se...
...t by bar.other, and would thus not be saved if the user has configured their browser to reject all third-party cookies. the http response headers this section lists the http response headers that servers send back for access control requests as defined by the cross-origin resource sharing specification. the previous section gives an overview of these in action. access-control-allow-origin a re
turned resource may have one access-control-allow-origin header, with the following syntax: access-control-allow-origin: <origin> | * access-control-allow-origin specifies either a single origin, which tells browsers to allow that origin to access the resource; or else — for requests without credentials — the "*" wildcard, to tell browsers to allow any origin to access the resource. for exampl...
...allow-credentials header indicates whether or not the response to the request can be exposed when the credentials flag is true. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. note that simple get requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not re
turned with the resource, the response is ignored by the browser and not re
turned to web content. access-control-allow-credentials: true credentialed requests are discussed above. access-control-allow-methods the access-control-allow-methods header specifies the method or methods allowed when accessing the resource. this is used in response to a preflight request. the conditions under which a req...
HTTP caching - HTTP
web caches reduce latency and network traffic and thus lessen the time needed to display a representation of a resource. by making use of http caching, web sites become more responsive. different kinds of caches caching is a technique that stores a copy of a given resource and serves it back when requested. when a web cache has a requested resource in its store, it intercepts the request and re
turns its copy instead of re-downloading from the originating server. this achieves several goals: it eases the load of the server that doesn’t need to serve all clients itself, and it improves performance by being closer to the client, i.e., it takes less time to transmit the resource back. for a web site, it is a major component in achieving high performance. on the other side, it has to be config...
...esource. before this expiration time, the resource is fresh; after the expiration time, the resource is stale. eviction algorithms often privilege fresh resources over stale resources. note that a stale resource is not evicted or ignored; when the cache receives a request for a stale resource, it forwards this request with a if-none-match to check if it is in fact still fresh. if so, the server re
turns a 304 (not modified) header without sending the body of the requested resource, saving some bandwidth. here is an example of this process with a shared cache proxy: the freshness lifetime is calculated based on several headers. if a "cache-control: max-age=n" header is specified, then the freshness lifetime is equal to n. if this header is not present, which is very often the case, it is che...
...ied response header can be used as a weak validator. it is considered weak because it only has 1-second resolution. if the last-modified header is present in a response, then the client can issue an if-modified-since request header to validate the cached document. when a validation request is made, the server can either ignore the validation request and response with a normal 200 ok, or it can re
turn 304 not modified (with an empty body) to instruct the browser to use its cached copy. the latter response can also include headers that update the expiration time of the cached document. varying responses the vary http response header determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. when a ...
Equality comparisons and sameness - JavaScript
arison you are looking to perform. briefly: double equals (==) will perform a type conversion when comparing two things, and will handle nan, -0, and +0 specially to conform to ieee 754 (so nan != nan, and -0 == +0); triple equals (===) will do the same comparison as double equals (including the special handling for nan, -0, and +0) but without type conversion; if the types differ, false is re
turned. object.is does no type conversion and no special handling for nan, -0, and +0 (giving it the same behavior as === except on those special numeric values). note that the distinction between these all have to do with their handling of primitives; none of them compares whether the parameters are conceptually similar in structure. for any non-primitive objects x and y which have the same struct...
... that might cause a distinction between -0 and +0 to manifest itself in your code: - (unary negation) let stoppingforce = obj.mass * -obj.velocity; if obj.velocity is 0 (or computes to 0), a -0 is introduced at that place and propogates out into stoppingforce. ...
...e.g., math.min(-0, +0) evaluates to -0. refer to the documentation for the individual methods. ~ << >> each of these operators uses the toint32 algorithm internally. ...
Regular expression syntax cheatsheet - JavaScript
80\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches " bar" in "foo bar". \s matches a single character other than white space. equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches "foo" in "foo bar". \t matches a horizontal tab. \r matches a carriage re
turn. \n matches a linefeed. \v matches a vertical tab. \f matches a form-feed. [\b] matches a backspace. if you're looking for the word-boundary character (\b), see boundaries. \0 matches a nul character. do not follow this with another digit. \cx matches a control character using caret notation, where "x" is a letter from a...
...ups themselves. this becomes important when capturing groups are nested. matches are accessed using the index of the the result's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9). capturing groups have a performance penalty. if you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below). string.match() won't re
turn groups if the /.../g flag is set. however, you can still use string.matchall() to get all matches. \n where "n" is a positive integer. a back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses). for example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". \k<name> ...
...last substring matching the named capture group specified by <name>. for example, /(?<title>\w+), yes \k<title>/ matches "sir, yes sir" in "do you copy? sir, yes sir!". \k is used literally here to indicate the beginning of a back reference to a named capture group. (?<name>x) named capturing group: matches "x" and stores it on the groups property of the re
turned matches under the name specified by <name>. the angle brackets (< and >) are required for group name. for example, to extract the united states area code from a phone number, we could use /\((?<area>\d\d\d)\)/. the resulting number would appear under matches.groups.area. (?:x) non-capturing group: matches "x" but does not remember the match. the matched substring cannot be ...
Memory Management - JavaScript
llocations, javascript will automatically allocate memory when values are initially declared. var n = 123; // allocates memory for a number var s = 'azerty'; // allocates memory for a string var o = { a: 1, b: null }; // allocates memory for an object and contained values // (like object) allocates memory for the array and // contained values var a = [1, null, 'abra']; function f(a) { re
turn a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function calls some function calls result in object allocation. var d = new date(); // allocates a date object var e = document.createelement('div'); // allocat...
...med. however, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. circular references are a common cause of memory leaks. function f() { var x = {}; var y = {}; x.a = y; // x references y y.a = x; // y references x re
turn 'azerty'; } f(); real-life example internet explorer 6 and 7 are known to have reference-counting garbage collectors for dom objects. cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getelementbyid('mydivelement'); div.circularreference = div; div.lotsofdata = new array(10000).join('*'); }; in the above example, the dom ...
...avascript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is no longer needed". cycles are no longer a problem in the first example above, after the function call re
turns, the two objects are no longer referenced by any resource that is reachable from the global object. consequently, they will be found unreachable by the garbage collector and have their allocated memory reclaimed. limitation: releasing memory manually there are times when it would be convenient to manually decide when and what memory is released. in order to release the memory of an object, it ...
constructor - JavaScript
ill be supplied for you. ...
...iven. however, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using super. ...
...ive demo). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, `super()` must be called before you // can use `this`. leaving this out will cause a referenceerror. this.name = 'square'; } get area() { re
turn this.height * this.width; } set area(value) { this.height = value**0.5; this.width = value**0.5; } } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a square is created. class polygon { constructor() { this.name = "polygon"; } } class square extends polygon { ...
TypeError: cyclic object value - JavaScript
rary that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. ...
... (or removing) the cyclic references by serializable values. ...
...ble values. ...
SyntaxError: missing formal parameter - JavaScript
umeric characters (or "$" or "_"), and may not start with a digit. an identifier differs from a string in that a string is data, while an identifier is part of the code. examples provide proper function parameters function parameters must be identifiers when setting up a function. ...
...tring in that a string is data, while an identifier is part of the code. examples provide proper function parameters function parameters must be identifiers when setting up a function. ...
... values for their parameters: function square(3) { re
turn number * number; }; // syntaxerror: missing formal parameter function greet("howdy") { re
turn greeting; }; // syntaxerror: missing formal parameter function log({ obj: "value"}) { console.log(arg) }; // syntaxerror: missing formal parameter you will need to use identifiers in function declarations: function square(number) { re
turn number * number; }; function greet(greeting) { re
turn greeting; }; function log(arg) { console.log(arg) }; you can then call these functions with the arguments you like: square(2); // 4 greet("howdy"); // "howdy" log({obj: "value"}); // object { obj: "value" } ...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
rs: default parameters rest parameters destructuring parameters a "use strict" directive is not allowed at the top of such functions per the ecmascript specification. ...
...rameters a=1 and b=2: function sum(a = 1, b = 2) { // syntaxerror: "use strict" not allowed in function with default parameter 'use strict'; re
turn a + b; } if the function should be in strict mode, and the entire script or enclosing function is also okay to be in strict mode, you can move the "use strict" directive outside of the function: 'use strict'; function sum(a = 1, b = 2) { re
turn a + b; } function expression a function expression can use yet another workaround: var sum = function sum([a, b]) { // syntaxerror: "use strict" not allowed in function with destructuring parameter 'use strict'; re
turn a + b; }; this can be converted to the following expression: var sum = (function() { 'use strict'; re
turn function sum([a, b]) { re
turn a + b; }; })(); arr...
... converted to the following expression: var sum = (function() { 'use strict'; re
turn function sum([a, b]) { re
turn a + b; }; })(); arrow function if an arrow function needs to access the this variable, you can use the arrow function as the enclosing function: var callback = (...args) => { // syntaxerror: "use strict" not allowed in function with rest parameter 'use strict'; re
turn this.run(args); }; this can be converted to the following expression: var callback = (() => { 'use strict'; re
turn (...args) => { re
turn this.run(args); }; })(); ...
InternalError: too much recursion - JavaScript
te the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). when there are too many function calls, or a function is missing a base case, javascript will throw this error. examples this recursive function runs 10 times, as per the exit condition. function loop(x) { if (x >= 10) // "x >= 10" is the exit condition re
turn; // do stuff loop(x + 1); // the recursive call } loop(0); setting this condition to an extremely high value, won't work: function loop(x) { if (x >= 1000000000000) re
turn; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion this recursive function is missing a base case. as there is no exit condition, the function will call itself infinitely. function loop...
...ter function is triggered. set name(name){ this.name = name; // recursive call } in this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. this causes the function to call itself, again and again, making it infinitely recursive. this issue also appears if the same variable is used in the getter. ...
...this issue also appears if the same variable is used in the getter. get name(){ re
turn this.name; // recursive call } to avoid this problem, make sure that the property being assigned to inside the setter function is different from the one that initially triggered the setter.the same goes for the getter. ...
SyntaxError: Unexpected token - JavaScript
correct would be putting brackets around the ||: function round(n, upperbound, lowerbound){ if((n > upperbound) || (n < lowerbound)){ throw 'number ' + string(n) + ' is more than ' + string(upperbound) + ' or l...
...correct would be putting brackets around the ||: function round(n, upperbound, lowerbound){ if((n > upperbound) || (n < lowerbound)){ throw 'number ' + string(n) + ' is more than ' + string(upperbound) + ' or less than ' + string(lowerbound);...
..., got '||' the brackets may look correct at first, but note how the || is outside the brackets. correct would be putting brackets around the ||: function round(n, upperbound, lowerbound){ if((n > upperbound) || (n < lowerbound)){ throw 'number ' + string(n) + ' is more than ' + string(upperbound) + ' or less than ' + string(lowerbound); }else if(n < ((upperbound + lowerbound)/2)){ re
turn lowerbound; }else{ re
turn upperbound; } } ...
SyntaxError: function statement requires a name - JavaScript
he code that requires a name. you'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an iife, or if the function code is placed correctly in this context at all. examples statements vs expressions a function statement (or function declaration) requires a name, this won't work: function () { re
turn 'hello world'; } // syntaxerror: function statement requires a name you can use a function expression (assignment) instead: var greet = function() { re
turn 'hello world'; }; or, you function is maybe intended to be an iife (immediately invoked function expression), which is a function that runs as soon as it is defined. you will need a few more braces in this case: (function () { })(); l...
...is maybe intended to be an iife (immediately invoked function expression), which is a function that runs as soon as it is defined. you will need a few more braces in this case: (function () { })(); labeled functions if you are using function labels, you will still need to provide a function name after the function keyword. ...
... braces in this case: (function () { })(); labeled functions if you are using function labels, you will still need to provide a function name after the function keyword. this doesn't work: function greeter() { german: function () { re
turn "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { re
turn "moin"; } } object methods if you intended to create a method of an object, you will need to create an object. the following syntax without a name after the function keyword is valid then. var greeter = { german: function () { re
turn "moin"; } }; callback syntax also, check your syntax when using callbacks. brackets and commas can get difficult easily. promise.then( function() {...
TypeError: 'x' is not iterable - JavaScript
the javascript exception "is not iterable" occurs when the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object. message typeerror: 'x' is not iterable (firefox, chrome) typeerror: 'x' is not a function or its re
turn value is not iterable (chrome) error type typeerror what went wrong? the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object. an iterable can be a built-in iterable type such as array, string or map, a generator result, or an object implementing the iterable protocol. examples iterating over object properties in javascript, objects are not iterable unless they implement the i...
...le. calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator. function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x); iterating over a custom iterable custom iterables can be created by implementing the symbol.iterator method. you must be certain that your iterator method re
turns an object which is an iterator, which is to say it must have a next method. const myemptyiterable = { [symbol.iterator]() { re
turn [] // [] is iterable, but it is not an iterator -- it has no next method. } } array.from(myemptyiterable); // typeerror: myemptyiterable is not iterable here is a correct implementation: const myemptyiterable = { [symbol.iterator]() { ...
... object which is an iterator, which is to say it must have a next method. const myemptyiterable = { [symbol.iterator]() { re
turn [] // [] is iterable, but it is not an iterator -- it has no next method. ...
Array.prototype.copyWithin() - JavaScript
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 arr.copywithin(target[, start[, end]]) parameters target zero-based index at which to copy the sequence to. if negative, target will be counted from the end. if target is at or greater than arr.length, nothing will be copied. if target is positioned after start, the copied sequence will be trimmed to fit arr.length. ...
...hich to start copying elements from. if negative, start will be counted from the end. if start is omitted, copywithin will copy from index 0. end optional zero-based index at which to end copying elements from. copywithin copies up to but not including end. if negative, end will be counted from the end. if end is omitted, copywithin will copy until the last index (default to arr.length). re
turn value the modified array. description the copywithin works like c and c++'s memmove, and is a high-performance method to shift the data of an array. this especially applies to the typedarray method of the same name. the sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap. the copywithin function is intentional...
... - to); // steps 16-17. var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } // step 18. while (count > 0) { if (from in o) { o[to] = o[from]; } else { delete o[to]; } from += direction; to += direction; count--; } // step 19. ...
Array.prototype.fill() - JavaScript
the fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). it re
turns the modified array. 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 arr.fill(value[, start[, end]]) parameters value value to fill the array with. (note all elements in the array will be this exact value.) start optional start index, default 0. end optional end index, default arr.length. re
turn value the modified array, filled with value. description if start is negative, it is treated as array.length + start. if end is negative, it is treat...
... if the first parameter is an object, each slot in the array will reference that object. polyfill if (!array.prototype.fill) { object.defineproperty(array.prototype, 'fill', { value: function(value) { // steps 1-2. ...
...n(relativestart, len); // steps 9-10. var end = arguments[2]; var relativeend = end === undefined ? len : end >> 0; // step 11. var finalvalue = relativeend < 0 ? math.max(len + relativeend, 0) : math.min(relativeend, len); // step 12. while (k < finalvalue) { o[k] = value; k++; } // step 13. re
turn o; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1...
Array.prototype.flat() - JavaScript
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 var newarray = arr.flat([depth]); parameters depth optional the depth level specifying how deep a nested array structure should be flattened. defaults to 1. re
turn value a new array with the sub-array elements concatenated into it. alternatives reduce and concat const arr = [1, 2, [3, 4]]; // to flat single level array arr.flat(); // is equivalent to arr.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4] // or with decomposition syntax const flattened = arr => [].concat(...arr); reduce + concat + isarray + recursivity const arr = [1, 2, [3,...
...arr.reduce((acc, val) => acc.concat(array.isarray(val) ? flatdeep(val, d - 1) : val), []) : arr.slice(); }; flatdeep(arr, infinity); // [1, 2, 3, 4, 5, 6] use a stack // non recursive flatten deep using a stack // note that depth control is hard/inefficient as we will need to tag each value with its own depth // also possible w/o reversing on shift/unshift, but array o...
...array ops on the end tends to be faster function flatten(input) { const stack = [...input]; const res = []; while(stack.length) { // pop value from stack const next = stack.pop(); if(array.isarray(next)) { // push back array items, won't modify the original input stack.push(...next); } else { res.push(next); } } // reverse to restore input order re
turn res.reverse(); } const arr = [1, 2, [3, 4, [5, 6]]]; flatten(arr); // [1, 2, 3, 4, 5, 6] use generator function function* flatten(array, depth) { if(depth === undefined) { depth = 1; } for(const item of array) { if(array.isarray(item) && depth > 0) { yield* flatten(item, depth - 1); } else { yield item; } } } const arr = [1, 2...
Array.prototype.flatMap() - JavaScript
en quite useful, as merging both into one method is slightly more efficient. 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 var new_array = arr.flatmap(function callback(currentvalue[, index[, array]]) { // re
turn element for new_array }[, thisarg]) parameters callback function that produces an element of the new array, taking three arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing ca...
... new_array }[, thisarg]) parameters callback function that produces an element of the new array, taking three arguments: currentvalue the current element being processed in the array. indexoptional the index of the current element being processed in the array. arrayoptional the array map was called upon. thisargoptional value to use as this when executing callback. re
turn value a new array with each element being the result of the callback function and flattened to a depth of 1. description see array.prototype.map() for a detailed description of the callback function. the flatmap method is identical to a map followed by a call to flat of depth 1. alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.
...ut list length can be different from the input list length. for adding and removing items during a map() flatmap can be used as a way to add and remove items (modify the number of items) during a map. in other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. in this sense, it works like the opposite of filter. simply re
turn a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item. // let's say we want to remove all the negative numbers // and split the odd numbers into an even number and a 1 let a = [5, 4, -3, 20, 17, -33, -4, 18] // |\ \ x | | \ x x | // [4,1, 4, 20, 16, 1, 18] a.flatmap( (n) => (n < 0) ? [] : (n % 2 ...
Array.prototype.includes() - JavaScript
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 arr.includes(valuetofind[, fromindex]) parameters valuetofind the value to search for. note: when comparing strings and characters, includes() is case-sensitive. fromindex optional the position in this array at which to begin searching for valuetofind. ...
...nsitive. fromindex optional the position in this array at which to begin searching for valuetofind. the first element to be searched is found at fromindex for positive values of fromindex, or at arr.length + fromindex for negative values of fromindex (using the absolute value of fromindex as the number of elements from the end of the array at which to start the search). defaults to 0. re
turn value a boolean which is true if the value valuetofind is found within the array (or the part of the array indicated by the index fromindex, if specified). values of zero are all considered to be equal, regardless of sign. (that is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0. note: technically speaking, includes() uses the samevaluezero alg...
...he samevaluezero algorithm to determine whether the given element is found. examples [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, 3].includes(3, 3) // false [1, 2, 3].includes(3, -1) // true [1, 2, nan].includes(nan) // true fromindex is greater than or equal to the array length if fromindex is greater than or equal to the length of the array, false is re
turned. the array will not be searched. let arr = ['a', 'b', 'c'] arr.includes('c', 3) // false arr.includes('c', 100) // false computed index is less than 0 if fromindex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for valuetofind. if the computed index is less or equal than -1 * arr.length, the entire array will be searched.
Array.of() - JavaScript
creates an empty array with a length property of 7 (note: this implies an array of 7 empty slots, not slots with actual undefined values). array.of(7); // [7] array.of(1, 2, 3); // [1, 2, 3] array(7); // array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. ...
...ntn elements used to create the array. re
turn value a new array instance. description this function is part of the ecmascript 2015 standard. for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. ...
...ore information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. if (!array.of) { array.of = function() { re
turn array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } re
turn vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specification. ...
Array.prototype.pop() - JavaScript
pop is intentionally generic; this method can be called or applied to objects resembling arrays. ...
... pop is intentionally generic; this method can be called or applied to objects resembling arrays. ...
...ource 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 arrname.pop() re
turn value the removed element from the array; undefined if the array is empty. description the pop method removes the last element from an array and re
turns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. if you call pop() on an empty array, it re
turns undefined. array.prototype.shift() has similar behavior ...
Array.prototype.reverse() - JavaScript
the reverse() method reverses an array in place. the first array element becomes the last, and the last array element becomes the first. 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 a.reverse() re
turn value the reversed array. description the reverse method transposes the elements of the calling array object in place, mutating the array, and re
turning a reference to the array. reverse is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties...
...this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array. ...
...n reverses the array. the call to reverse() re
turns a reference to the reversed array a. const a = [1, 2, 3]; console.log(a); // [1, 2, 3] a.reverse(); console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object. the call to reverse() re
turns a reference to the reversed array-like object a. const a = {0: 1, 1: 2, 2: 3, length: 3}; console.log(a); // {0: 1, 1: 2, 2: 3, length: 3} array.prototype.reverse.call(a); //same syntax for using apply() console.log(a); // {0: 3, 1: 2, 2: 1, length: 3} specifications specification ecmascript (ecma-262)the definition of 'array.prototype.reverse' in that specification. ...
Array.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string representing the elements of the array. the elements are converted to strings using their tolocalestring methods and these strings are separated by a locale-specific string (such as a comma “,”). syntax arr.tolocalestring([locales[, options]]); parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. options optional an object with configuration properties, for numbers see number.prototype.tolocalestring(), and for dates see date.prototype.tolocalestring(). re
turn value a string representing the elements of the array. polyfill // https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring if (!array.p...
...et len be ? tolength(? get(a, "length")). var len = a.length >>> 0; // 3. let separator be the string value for the // list-separator string appropriate for the // host environment's current locale (this is // derived in an implementation-defined way). // note: in this case, we will use a comma var separator = ','; // 4. if len is zero, re
turn the empty string. if (len === 0) { re
turn ''; } // 5. let firstelement be ? get(a, "0"). var firstelement = a[0]; // 6. if firstelement is undefined or null, then // a.let r be the empty string. // 7. else, // a. let r be ? // tostring(? // invoke( // firstelement, // "tolocalestring", ...
... nextelement, // "tolocalestring", // « locales, options » // ) // ) r = nextelement == null ? '' : nextelement.tolocalestring(locales, options); // e. let r be a string value produced by // concatenating s and r. r = s + r; // f. increase k by 1. k++; } // 10. re
turn r. re
turn r; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples using locales and options the elements of the array are converted to strings using their tolocalestring methods. object: object.prototype.tolocalestring...
Atomics.add() - JavaScript
the static atomics.add() method adds a given value at a given position in the array and re
turns the old value at that position. this atomic operation guarantees that no other write happens until the modified value is written back. 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 atomics.add(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. ...
...les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.add(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to add a value to. value the number to add. ...
...dd a value to. value the number to add. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // re
turns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification. ...
Atomics.and() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. 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 atomics.and(typedarray, index, value) parameters typedarray an integer typed array. ...
...github.com/mdn/interactive-examples and send us a pull request. syntax atomics.and(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise and. value the number to compute the bitwise and with. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise and operation only yields 1, if both a and b are 1. the truth table for the and operation is: a b a & b 0 0 0 ...
... ...
Atomics.compareExchange() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. 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. ...
... atomics.compareexchange(typedarray, index, expectedvalue, replacementvalue) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. expectedvalue the value to check for equality. replacementvalue the number to exchange. ...
...ge. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // re
turns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.compareexchange' in that specification. ...
Atomics.exchange() - JavaScript
this atomic operation guarantees that no other write happens between the read of the old value and the write of the new value. 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 atomics.exchange(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. ...
... please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.exchange(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to exchange a value. value the number to exchange. ...
... value the number to exchange. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // re
turns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specification. ...
Atomics.or() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. 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 atomics.or(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. ...
...://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.or(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise or. value the number to compute the bitwise or with. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise or operation yields 1, if either a or b are 1. the truth table for the or operation is: a b a | b 0 0 0 0 ...
... ...
Atomics.sub() - JavaScript
the static atomics.sub() method substracts a given value at a given position in the array and re
turns the old value at that position. this atomic operation guarantees that no other write happens until the modified value is written back. 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 atomics.sub(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. ...
... please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.sub(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to subtract a value from. value the number to subtract. ...
... value the number to subtract. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // re
turns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification. ...
Atomics.xor() - JavaScript
this atomic operation guarantees that no other write happens until the modified value is written back. 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 atomics.xor(typedarray, index, value) parameters typedarray an integer typed array. ...
...github.com/mdn/interactive-examples and send us a pull request. syntax atomics.xor(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to compute the bitwise xor. value the number to compute the bitwise xor with. re
turn value the old value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. description the bitwise xor operation yields 1, if a and b are different. the truth table for the xor operation is: a b a ^ b 0 0 0 ...
... ...
BigInt.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string with a language-sensitive representation of this bigint. 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 bigintobj.tolocalestring([locales [, options]]) parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations that ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent. see the intl.numberformat() constructor for details on these parameters and how to use...
...d options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations that ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation-dependent. see the intl.numberformat() constructor for details on these parameters and how to use them. re
turn value a string with a language-sensitive representation of the given bigint. ...
... var bigint = 3500n; bigint.tolocalestring(); // displays "3,500" if in u.s. english locale using locales this example shows some of the variations in localized number formats. ...
Boolean.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code. ...
... this method is usually called internally by javascript and not explicitly in code. ...
... primitive value of a boolean object. 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 bool.valueof() re
turn value the primitive value of the given boolean object description the valueof() method of boolean re
turns the primitive value of a boolean object or literal boolean as a boolean data type. this method is usually called internally by javascript and not explicitly in code. examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specificatio...
Date.UTC() - JavaScript
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 since ecmascript 2017: date.utc(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]]) ecmascript 2016 and earlier: (month used to be required) date.utc(year, month[, day[, hour[, minute[, second[, millisecond]]]]]) parameters year a full year. ...
...ptional an integer between 0 and 23 representing the hours. if omitted, defaults to 0. minute optional an integer between 0 and 59 representing the minutes. if omitted, defaults to 0. second optional an integer between 0 and 59 representing the seconds. if omitted, defaults to 0. millisecond optional an integer between 0 and 999 representing the milliseconds. if omitted, defaults to 0. re
turn value a number representing the number of milliseconds for the given date since january 1, 1970, 00:00:00, utc. description utc() takes comma-delimited date and time parameters and re
turns the number of milliseconds between january 1, 1970, 00:00:00, universal time and the specified date and time. years between 0 and 99 are converted to a year in the 20th century (1900 + year). for example, 9...
... if a parameter is outside of the expected range, the utc() method updates the other parameters to accommodate the value. for example, if 15 is used for month, the year will be incremented by 1 (year + 1) and 3 will be used for the month. ...
Date.prototype.getFullYear() - JavaScript
use this function to make sure a year is compliant with years after 2000. ...
...use this function to make sure a year is compliant with years after 2000. ...
...the getyear() method. 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 dateobj.getfullyear() re
turn value a number corresponding to the year of the given date, according to local time. description the value re
turned by getfullyear() is an absolute number. for dates between the years 1000 and 9999, getfullyear() re
turns a four-digit number, for example, 1995. use this function to make sure a year is compliant with years after 2000. examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year. var today = new date(); var year = today.getfullyear...
Date.prototype.getTimezoneOffset() - JavaScript
description the time-zone offset is the difference, in minutes, from local time to utc. note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. ...
... description the time-zone offset is the difference, in minutes, from local time to utc. note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. ...
...es, from the date based on current host system settings to utc. description the time-zone offset is the difference, in minutes, from local time to utc. note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. for example, for time zone utc+10:00 (australian eastern standard time, vladivostok time, chamorro standard time), -600 will be re
turned. current locale utc-8 utc utc+3 re
turn value 480 0 -180 the time zone offset re
turned is the one that applies for the date that it's called on. if the host system is configured for daylight saving, the offset will change depending on the date and time that the date represents and that daylight saving applies. examples using gettimezoneoffset() ...
Date.prototype.getUTCFullYear() - JavaScript
examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. ...
... examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. ...
... to universal time. 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 dateobj.getutcfullyear() re
turn value a number representing the year in the given date according to universal time. description the value re
turned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995. examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year. var today = new date(); var year = today.getutcfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcful...
Date.prototype.toJSON() - JavaScript
this method is generally intended to, by default, usefully serialize date objects during json serialization. ...
...this method is generally intended to, by default, usefully serialize date objects during json serialization. ...
...ject. 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 dateobj.tojson() re
turn value a string representation of the given date. description date instances refer to a specific point in time. calling tojson() re
turns a string (using toisostring()) representing the date object's value. this method is generally intended to, by default, usefully serialize date objects during json serialization. examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-...
Intl.DateTimeFormat - JavaScript
itive date and time formatting. 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. constructor intl.datetimeformat() creates a new datetimeformat object. ...
...atetimeformat.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.datetimeformat.prototype.format() getter function that formats a date according to the locale and formatting options of this datetimeformat object. intl.datetimeformat.prototype.formattoparts() re
turns an array of objects representing the date string in parts that can be used for custom locale-aware formatting. intl.datetimeformat.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and formatting options computed during initialization of the object. intl.datetimeformat.prototype.formatrange() this method receives two dates and formats the date range in th...
...ith properties reflecting the locale and formatting options computed during initialization of the object. intl.datetimeformat.prototype.formatrange() this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating datetimeformat. intl.datetimeformat.prototype.formatrangetoparts() this method receives two dates and re
turns an array of objects containing the locale-specific tokens representing each part of the formatted date range. examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options. var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and th...
Intl.ListFormat.prototype.formatToParts() - JavaScript
each element of the resulting array has two properties: type and value. ...
... each element of the resulting array has two properties: type and value. ...
...objects representing the different components that can be used to format a list of values in a locale-aware fashion. syntax intl.listformat.prototype.formattoparts(list) parameters list an array of values to be formatted according to a locale. re
turn value an array of components which contains the formatted parts from the list. description whereas intl.listformat.prototype.format() re
turns a string being the formated version of the list (according to the given locale and style options), formattoparts() re
turns an array of the different components of the formated string. each element of the resulting array has two properties: type and value. the type property may be either "element", which refers to a value from the list, or "literal" which refers to a linguistic construct. the va...
Intl.ListFormat - JavaScript
t enable language-sensitive list formatting. 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. constructor intl.listformat() creates a new listformat object. ...
...one https://github.com/mdn/interactive-examples and send us a pull request. constructor intl.listformat() creates a new listformat object. static methods intl.listformat.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.listformat.prototype.format() re
turns a language-specific formatted string representing the elements of the list. intl.listformat.prototype.formattoparts() re
turns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. examples using format the following example shows how to create a list formatter using the english language. const list = ['motorcycle',...
...ng', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example shows how to create a list formatter re
turning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", and " }, // { "type": "element", "value": "car" } ]; ...
Intl.NumberFormat - JavaScript
language sensitive number formatting. 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. constructor intl.numberformat() creates a new numberformat object. ...
...intl.numberformat.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.numberformat.prototype.format() getter function that formats a number according to the locale and formatting options of this numberformat object. intl.numberformat.prototype.formattoparts() re
turns an array of objects representing the number string in parts that can be used for custom locale-aware formatting. intl.numberformat.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and collation options computed during initialization of the object. examples basic usage in basic use without specifying a locale, a formatted string in the default locale an...
... var number = 3500; console.log(new intl.numberformat().format(number)); // → '3,500' if in us english locale using locales this example shows some of the variations in localized number formats. ...
Intl.RelativeTimeFormat - JavaScript
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. constructor intl.relativetimeformat.relativetimeformat() creates a new intl.relativetimeformat object. ...
....supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.relativetimeformat.prototype.format() formats a value and a unit according to the locale and formatting options of the given intl.relativetimeformat object. intl.relativetimeformat.prototype.formattoparts() re
turns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. intl.relativetimeformat.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples basic format usage the following example shows how to use a relative time formatter...
...r values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1). rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1). rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter re
turning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit. rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" }, // > { type: "literal", value: " days" }] specifications ...
Math.abs() - JavaScript
description because abs() is a static method of math, you always use it as math.abs(), rather than as a method of a math object you created (math is not a constructor). ...
...ratorname{math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases} 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 math.abs(x) parameters x a number. re
turn value the absolute value of the given number. description because abs() is a static method of math, you always use it as math.abs(), rather than as a method of a math object you created (math is not a constructor). examples behavior of math.abs() passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable re
turns nan. passing null, an empty ...
...of the given number. description because abs() is a static method of math, you always use it as math.abs(), rather than as a method of a math object you created (math is not a constructor). examples behavior of math.abs() passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable re
turns nan. passing null, an empty string or an empty array re
turns 0. math.abs('-1'); // 1 math.abs(-2); // 2 math.abs(null); // 0 math.abs(''); // 0 math.abs([]); // 0 math.abs([2]); // 2 math.abs([1,2]); // nan math.abs({}); // nan math.abs('string'); // nan math.abs(); // nan specifications specification ecmascript (ecma-262)the definition of 'math.abs' in that specification. ...
Math.acos() - JavaScript
the math.acos() function re
turns the arccosine (in radians) of a number, that is ∀x∊[-1;1],math.acos(x)=arccos(x)= the unique y∊[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x 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 math.acos(x) parameters x a number representing a cosine, where x is between -1 and 1. re
turn value the arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, nan. ...
...f 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 math.acos(x) parameters x a number representing a cosine, where x is between -1 and 1. re
turn value the arccosine (angle in radians) of the given number if it's between -1 and 1; otherwise, nan. description the math.acos() method re
turns a numeric value between 0 and π radians for x between -1 and 1. if the value of x is outside this range, it re
turns nan. because acos() is a static method of math, you always use it as math.acos(), rather than as a method of a math object you created (math is not a constructor). examples using math.acos() math.acos(-2); // nan math.acos(-1); // 3.141592653589793 math.acos(0); // 1.57079...
...ethod of math, you always use it as math.acos(), rather than as a method of a math object you created (math is not a constructor). examples using math.acos() math.acos(-2); // nan math.acos(-1); // 3.141592653589793 math.acos(0); // 1.5707963267948966 math.acos(0.5); // 1.0471975511965979 math.acos(1); // 0 math.acos(2); // nan for values less than -1 or greater than 1, math.acos() re
turns nan. specifications specification ecmascript (ecma-262)the definition of 'math.acos' in that specification. ...
Math.acosh() - JavaScript
if the number is less than 1, nan. ...
...name{math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ the unique } \; y \geq 0 \; \text{such that} \; \cosh(y) = x 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 math.acosh(x) parameters x a number. re
turn value the hyperbolic arc-cosine of the given number. if the number is less than 1, nan. description because acosh() is a static method of math, you always use it as math.acosh(), rather than as a method of a math object you created (math is no constructor). polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so t...
...ription because acosh() is a static method of math, you always use it as math.acosh(), rather than as a method of a math object you created (math is no constructor). polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: math.acosh = math.acosh || function(x) { re
turn math.log(x + math.sqrt(x * x - 1)); }; examples using math.acosh() math.acosh(-1); // nan math.acosh(0); // nan math.acosh(0.5); // nan math.acosh(1); // 0 math.acosh(2); // 1.3169578969248166 for values less than 1 math.acosh() re
turns nan. specifications specification ecmascript (ecma-262)the definition of 'math.acosh' in that specification. ...
Math.asin() - JavaScript
the math.asin() function re
turns the arcsine (in radians) of a number, that is ∀x∊[-1;1],math.asin(x)=arcsin(x)= the unique y∊[-π2;π2]such thatsin(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{math.asin}(x)} = \arcsin(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \sin(y) = x 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 math.asin(x) parameters x a number. re
turn value the arcsine (in radians) of the given number if it's between -1 and 1; otherwise, nan. ...
...his 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 math.asin(x) parameters x a number. re
turn value the arcsine (in radians) of the given number if it's between -1 and 1; otherwise, nan. description the math.asin() method re
turns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians for x between -1 and 1. if the value of x is outside this range, it re
turns nan. because asin() is a static method of math, you always use it as math.asin(), rather than as a method of a math object you created (math is not a constructor). examples using math.asin() math.asin(-2); // nan math.asin(-1); // -1.5707963267...
...u always use it as math.asin(), rather than as a method of a math object you created (math is not a constructor). examples using math.asin() math.asin(-2); // nan math.asin(-1); // -1.5707963267948966 (-pi/2) math.asin(0); // 0 math.asin(0.5); // 0.5235987755982989 math.asin(1); // 1.5707963267948966 (pi/2) math.asin(2); // nan for values less than -1 or greater than 1, math.asin() re
turns nan. specifications specification ecmascript (ecma-262)the definition of 'math.asin' in that specification. ...
Math.asinh() - JavaScript
description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor). ...
...peratorname{math.asinh}(x)} = \operatorname{arsinh}(x) = \text{ the unique } \; y \; \text{such that} \; \sinh(y) = x 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 math.asinh(x) parameters x a number. re
turn value the hyperbolic arcsine of the given number. description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor). polyfill math.asinh can be emulated with the following function: if (!math.asinh) math.asinh = function(x) { var absx = math.abs(x), w if (absx < 3.72529029846191...
...of the given number. description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor). polyfill math.asinh can be emulated with the following function: if (!math.asinh) math.asinh = function(x) { var absx = math.abs(x), w if (absx < 3.725290298461914e-9) // |x| < 2^-28 re
turn x if (absx > 268435456) // |x| > 2^28 w = math.log(absx) + math.ln2 else if (absx > 2) // 2^28 >= |x| > 2 w = math.log(2 * absx + 1 / (math.sqrt(x * x + 1) + absx)) else var t = x * x, w = math.log1p(absx + t / (1 + math.sqrt(1 + t))) re
turn x > 0 ? w : -w } math.log1p may also have to be polyfilled; see math.log1p for details. examples using math.as...
Math.hypot() - JavaScript
the math.hypot() function re
turns the square root of the sum of squares of its arguments, that is: math.hypot(v1,v2,…,vn)=∑i=1nvi2=v12+v22+…+vn2\mathtt{\operatorname{math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2} 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 math.hypot([value1[, value2[, ...]]]) parameters value1, value2, ... numbers. re
turn value the square root of the sum of squares of the given arguments. if at least one of the arguments cannot be converted to a number, nan is re
turned. description calculating the hypotenuse of a ri...
...is nan. with one argument, math.hypot() is equivalent to math.abs(). ...
...h.hypot) math.hypot = function () { var max = 0; var s = 0; var containsinfinity = false; for (var i = 0; i < arguments.length; ++i) { var arg = math.abs(number(arguments[i])); if (arg === infinity) containsinfinity = true if (arg > max) { s *= (max / arg) * (max / arg); max = arg; } s += arg === 0 && max === 0 ? 0 : (arg / max) * (arg / max); } re
turn containsinfinity ? infinity : (max === 1 / 0 ? 1 / 0 : max * math.sqrt(s)); }; examples using math.hypot() math.hypot(3, 4); // 5 math.hypot(3, 4, 5); // 7.0710678118654755 math.hypot(); // 0 math.hypot(nan); // nan math.hypot(nan, infinity); // infinity math.hypot(3, 4, 'foo'); // nan, since +'foo' => nan math.hypot(3, 4, '5'); // 7.071067811865475...
Math.log() - JavaScript
the math.log() function re
turns the natural logarithm (base e) of a number, that is ∀x>0,math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{math.log}(x)} = \ln(x) = \text{the unique} \; y \; \text{such that} \; e^y = x the javascript math.log() function is equivalent to ln(x) in mathematics. 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 math.log(x) parameters x a number. re
turn value the natural logarithm (base e) of the given number. if the number is negative, nan is re
turned. description if the value of x is 0, the re
turn value is always -infinity. if the value ...
... because log() is a static method of math, you always use it as math.log(), rather than as a method of a math object you created (math is not a constructor). ...
...h.log2() or math.log10() . if you need a logarithm to other bases, use math.log(x) / math.log(otherbase) as in the example below; you might want to precalculate 1 / math.log(otherbase) . examples using math.log() math.log(-1); // nan, out of range math.log(0); // -infinity math.log(1); // 0 math.log(10); // 2.302585092994046 using math.log() with a different base the following function re
turns the logarithm of y with base x (ie. logxy\log_x y): function getbaselog(x, y) { re
turn math.log(y) / math.log(x); } if you run getbaselog(10, 1000) it re
turns 2.9999999999999996 due to floating-point rounding, which is very close to the actual answer of 3. specifications specification ecmascript (ecma-262)the definition of 'math.log' in that specification. ...
Math.log2() - JavaScript
the math.log2() function re
turns the base 2 logarithm of a number, that is ∀x>0,math.log2(x)=log2(x)=the uniqueysuch that2y=x\forall x > 0, \mathtt{\operatorname{math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x 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 math.log2(x) parameters x a number. re
turn value the base 2 logarithm of the given number. if the number is negative, nan is re
turned. description if the value of x is less than 0, the re
turn value is always nan. because log2() is a static method of math, you always use it as math.log2(), rather than as a m...
...an 0, the re
turn value is always nan. because log2() is a static method of math, you always use it as math.log2(), rather than as a method of a math object you created (math is not a constructor). this function is the equivalent of math.log(x) / math.log(2). for log2(e) use the constant math.log2e which is 1 / math.ln2. polyfill this polyfill emulates the math.log2 function. note that it re
turns imprecise values on some inputs (like 1 << 29), wrap into math.round() if working with bit masks. ...
...bject you created (math is not a constructor). this function is the equivalent of math.log(x) / math.log(2). for log2(e) use the constant math.log2e which is 1 / math.ln2. polyfill this polyfill emulates the math.log2 function. note that it re
turns imprecise values on some inputs (like 1 << 29), wrap into math.round() if working with bit masks. if (!math.log2) math.log2 = function(x) { re
turn math.log(x) * math.log2e; }; examples using math.log2() math.log2(3); // 1.584962500721156 math.log2(2); // 1 math.log2(1); // 0 math.log2(0); // -infinity math.log2(-2); // nan math.log2(1024); // 10 specifications specification ecmascript (ecma-262)the definition of 'math.log2' in that specification. ...
Math.sign() - JavaScript
the math.sign() function re
turns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. if the number passed into math.sign() is 0, it will re
turn a +/- 0. note that if the number is positive, an explicit (+) will not be re
turned. 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 math.sign(x) parameters x a number. if this argument is not a number, it is implicitly converted to one. re
turn value a number representing the sign of the given argument: if the argument is positive, re
turns 1. if the argument is negative, re
turns -1. if the argument is positive ze...
...ct, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.sign(x) parameters x a number. if this argument is not a number, it is implicitly converted to one. re
turn value a number representing the sign of the given argument: if the argument is positive, re
turns 1. if the argument is negative, re
turns -1. if the argument is positive zero, re
turns 0. if the argument is negative zero, re
turns -0. otherwise, nan is re
turned. description because sign() is a static method of math, you always use it as math.sign(), rather than as a method of a math object you created (math is not a constructor). polyfill if (!math.sign) { math.sign = function(x) { // if x is nan, the result is nan. // if x is -0, the result is -0. // if x...
...ou always use it as math.sign(), rather than as a method of a math object you created (math is not a constructor). polyfill if (!math.sign) { math.sign = function(x) { // if x is nan, the result is nan. // if x is -0, the result is -0. // if x is +0, the result is +0. // if x is negative and not -0, the result is -1. // if x is positive and not +0, the result is +1. ...
Math.sin() - JavaScript
because sin() is a static method of math, you always use it as math.sin(), rather than as a method of a math object you created (math is not a constructor). ...
... because sin() is a static method of math, you always use it as math.sin(), rather than as a method of a math object you created (math is not a constructor). ...
...he sine of a number. 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 math.sin(x) parameters x a number (given in radians). re
turn value the sine of the given number. description the math.sin() method re
turns a numeric value between -1 and 1, which represents the sine of the angle given in radians. because sin() is a static method of math, you always use it as math.sin(), rather than as a method of a math object you created (math is not a constructor). examples using math.sin() math.sin(0); // 0 math.sin(1); // 0.8414709848078965 math.sin(math.pi / 2); // 1 specifications ...
Math.sinh() - JavaScript
description because sinh() is a static method of math, you always use it as math.sinh(), rather than as a method of a math object you created (math is not a constructor). ...
... be expressed using the constant e: math.sinh(x)=ex-e-x2\mathtt{\operatorname{math.sinh(x)}} = \frac{e^x - e^{-x}}{2} 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 math.sinh(x) parameters x a number. ...
... syntax math.sinh(x) parameters x a number. re
turn value the hyperbolic sine of the given number. description because sinh() is a static method of math, you always use it as math.sinh(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.sinh = math.sinh || function(x) { re
turn (math.exp(x) - math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.sinh = math.sinh || function(x) { var y = math.exp(x); re
turn (y - 1 / y) / 2; } examples using math.sinh() math.sinh(0); // 0 math.sinh(1); // 1.1752011936438014 specifications specification ecmascript (ecma-262)the definition of 'math.sinh' in that specification. ...
NaN - JavaScript
iption nan is a property of the global object. in other words, it is a variable in global scope. the initial value of nan is not-a-number — the same as the value of number.nan. in modern browsers, nan is a non-configurable, non-writable property. even when this is not the case, avoid overriding it. it is rather rare to use nan in a program. there are five different types of operations that re
turn nan: number cannot be parsed (e.g. parseint("blabla") or number(undefined)) math operation where the result is not a real number (e.g. math.sqrt(-1)) operand of an argument is nan (e.g. 7 ** nan) indeterminate form (e.g. 0 * infinity) any operation that involves a string and is not an addition operation (e.g. "foo"/3) examples testing against nan nan compares unequal (via ==, !=, ===, ...
...===, and !==) to any other value -- including to another nan value. use number.isnan() or isnan() to most clearly determine whether a value is nan. or perform a self-comparison: nan, and only nan, will compare unequal to itself. ...
... compare unequal to itself. nan === nan; // false number.nan === nan; // false isnan(nan); // true isnan(number.nan); // true number.isnan(nan); // true function valueisnan(v) { re
turn v !== v; } valueisnan(1); // false valueisnan(nan); // true valueisnan(number.nan); // true however, do note the difference between isnan() and number.isnan(): the former will re
turn true if the value is currently nan, or if it is going to be nan after it is coerced to a number, while the latter will re
turn true only if the value is currently nan: isnan('hello world'); // true number.isnan('hello world'); // false additionally, some array methods cannot find nan, while others can. let arr = [2, 4, nan, 12]; arr.indexof(nan); // -1 (false) arr.i...
Number.isFinite() - JavaScript
r.isfinite() method determines whether the passed value is a finite number. 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 number.isfinite(value) parameters value the value to be tested for finiteness. ...
... send us a pull request. syntax number.isfinite(value) parameters value the value to be tested for finiteness. re
turn value a boolean indicating whether or not the given value is a finite number. description in comparison to the global isfinite() function, this method doesn't forcibly convert the parameter to a number. this means only values of the type number, that are also finite, re
turn true. ...
...d for finiteness. re
turn value a boolean indicating whether or not the given value is a finite number. description in comparison to the global isfinite() function, this method doesn't forcibly convert the parameter to a number. this means only values of the type number, that are also finite, re
turn true. ...
Number.isNaN() - JavaScript
and its type is number. it is a more robust version of the original, global isnan(). 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 number.isnan(value) parameters value the value to be tested for nan. re
turn value true if the given value is nan and its type is number; otherwise, false. description due to both equality operators, == and ===, evaluating to false when checking if nan is nan, the function number.isnan() has become necessary. this situation is unlike all other possible value comparisons in javascript. in comparison to the global isnan() function, number.isnan() doesn't suffer the prob...
...on is unlike all other possible value comparisons in javascript. in comparison to the global isnan() function, number.isnan() doesn't suffer the problem of forcefully converting the parameter to a number. this means it is now safe to pass values that would normally convert to nan, but aren't actually the same value as nan. this also means that only values of the type number, that are also nan, re
turn true. polyfill the following works because nan is the only value in javascript which is not equal to itself. number.isnan = number.isnan || function isnan(input) { re
turn typeof input === 'number' && input !== input; } examples using isnan number.isnan(nan); // true number.isnan(number.nan); // true number.isnan(0 / 0); // true // e.g. these would have been true with globa...
...{ re
turn typeof input === 'number' && input !== input; } examples using isnan number.isnan(nan); // true number.isnan(number.nan); // true number.isnan(0 / 0); // true // e.g. these would have been true with global isnan() number.isnan('nan'); // false number.isnan(undefined); // false number.isnan({}); // false number.isnan('blabla'); // false // these all re
turn false number.isnan(true); number.isnan(null); number.isnan(37); number.isnan('37'); number.isnan('37.37'); number.isnan(''); number.isnan(' '); specifications specification ecmascript (ecma-262)the definition of 'number.isnan' in that specification. ...
Object() constructor - JavaScript
when called in a non-constructor context, object behaves identically to new object(). syntax new object() new object(value) parameters value any value. ...
... when called in a non-constructor context, object behaves identically to new object(). syntax new object() new object(value) parameters value any value. ...
... when called in a non-constructor context, object behaves identically to new object(). syntax new object() new object(value) parameters value any value. ...
Object.prototype.__defineGetter__() - JavaScript
usage. this method should not be used since better alternatives exist. the __definegetter__ method binds an object's property to a function to be called when that property is looked up. syntax obj.__definegetter__(prop, func) parameters prop a string containing the name of the property to bind to the given function. func a function to be bound to a lookup of the specified property. ...
...(prop, func) parameters prop a string containing the name of the property to bind to the given function. func a function to be bound to a lookup of the specified property. re
turn value undefined. description the __definegetter__ allows a getter to be defined on a pre-existing object. ...
...n to be bound to a lookup of the specified property. re
turn value undefined. description the __definegetter__ allows a getter to be defined on a pre-existing object. examples non-standard and deprecated way var o = {}; o.__definegetter__('gimmefive', function() { re
turn 5; }); console.log(o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { re
turn 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmefive', { get: function() { re
turn 5; } }); console.log(o.gimmefive); // 5 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__definegetter__()' in that specification. ...
Object.getOwnPropertyNames() - JavaScript
the object.getownpropertynames() method re
turns an array of all properties (including non-enumerable properties except for those which use symbol) found directly in a given object. syntax object.getownpropertynames(obj) parameters obj the object whose enumerable and non-enumerable properties are to be re
turned. re
turn value an array of strings that corresponds to the properties found directly in the given object. description object.getownpropertynames() re
turns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. the ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in loop (or by object.keys()) over the properties of the object. the ordering of ...
...npropertynames(obj).sort()); // .sort() is an array method. // logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { re
turn this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in loop (note that this will also re
turn enumerable properties found along the prototype chain for the object unless the latter is filtered with hasownproperty()). items on the ...
...)) thus giving only the non-enumerable keys as output. var target = myobject; var enum_and_nonenum = object.getownpropertynames(target); var enum_only = object.keys(target); var nonenum_only = enum_and_nonenum.filter(function(key) { var indexinenum = enum_only.indexof(key); if (indexinenum == -1) { // not found in enum_only keys, // meaning that the key is non-enumerable, // so re
turn true so we keep this in the filter re
turn true; } else { re
turn false; } }); console.log(nonenum_only); specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertynames' in that specification. ...
Object.getOwnPropertySymbols() - JavaScript
description similar to object.getownpropertynames(), you can get all symbol properties of a given object as an array of symbols. ...
...y of all symbol properties found directly upon a given object. 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 object.getownpropertysymbols(obj) parameters obj the object whose symbol properties are to be re
turned. re
turn value an array of all symbol properties found directly upon the given object. description similar to object.getownpropertynames(), you can get all symbol properties of a given object as an array of symbols. note that object.getownpropertynames() itself does not contain the symbol properties of an object and only the string properties. as all objects have no own symbol properties i...
...properties found directly upon the given object. description similar to object.getownpropertynames(), you can get all symbol properties of a given object as an array of symbols. note that object.getownpropertynames() itself does not contain the symbol properties of an object and only the string properties. as all objects have no own symbol properties initially, object.getownpropertysymbols() re
turns an empty array unless you have set symbol properties on your object. examples using getownpropertysymbols var obj = {}; var a = symbol('a'); var b = symbol.for('b'); obj[a] = 'localsymbol'; obj[b] = 'globalsymbol'; var objectsymbols = object.getownpropertysymbols(obj); console.log(objectsymbols.length); // 2 console.log(objectsymbols); // [symbol(a), symbol(b)] console.log(objectsym...
Object.is() - JavaScript
description object.is() determines whether two values are the same value. ...
...esn't coerce either value. this is also not the same as being equal according to the === operator. the === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats number.nan as not equal to nan. ...
...e === operator. the === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats number.nan as not equal to nan. ...
Object.isFrozen() - JavaScript
the object.isfrozen() determines if an object is frozen. 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 object.isfrozen(obj) parameters obj the object which should be checked. re
turn value a boolean indicating whether or not the given object is frozen. description an object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. examples using object.isfrozen // a new object is extensible, so it is not frozen. object.isfrozen({});...
...e, 'release', { configurable: false }); object.isfrozen(nonconfigurable); // === false // changing that property to non-writable // then makes the object frozen. object.defineproperty(nonconfigurable, 'release', { writable: false }); object.isfrozen(nonconfigurable); // === true // a non-extensible object with a configurable // accessor property isn't frozen. var accessor = { get food() { re
turn 'yum'; } }; object.preventextensions(accessor); object.isfrozen(accessor); // === false // ...but make that property non-configurable // and it becomes frozen. object.defineproperty(accessor, 'food', { configurable: false }); object.isfrozen(accessor); // === true // but the easiest way for an object to be frozen // is if object.freeze has been called on it. var frozen = { 1: 81 }; object.isf...
...definition, a frozen object is non-extensible. object.isextensible(frozen); // === false // also by definition, a frozen object is sealed. object.issealed(frozen); // === true non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a frozen ordinary object, simply re
turn true. object.isfrozen(1); // typeerror: 1 is not an object (es5 code) object.isfrozen(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isfrozen' in that specification. ...
Object.preventExtensions() - JavaScript
to an object (i.e. prevents future extensions to the object). 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 object.preventextensions(obj) parameters obj the object which should be made non-extensible. re
turn value the object being made non-extensible. description an object is extensible if new properties can be added to it. object.preventextensions() marks an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. note that the properties of a non-extensible object, in general, may still be deleted. attempting to add...
...method makes the [[prototype]] of the target immutable; any [[prototype]] re-assignment will throw a typeerror. this behavior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable. there is no way to make an object extensible again once it has been made non-extensible. examples using object.preventextensions // object.preventextensions re
turns the object // being made non-extensible. var obj = {}; var obj2 = object.preventextensions(obj); obj === obj2; // true // objects are extensible by default. var empty = {}; object.isextensible(empty); // === true // ...but that can be changed. object.preventextensions(empty); object.isextensible(empty); // === false // object.defineproperty throws when adding // a new property to a non-extens...
...fail'; } fail(); a non-extensible object's prototype is immutable: var fixed = object.preventextensions({}); // throws a 'typeerror'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply re
turn it. object.preventextensions(1); // typeerror: 1 is not an object (es5 code) object.preventextensions(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.preventextensions' in that specification. ...
Object.seal() - JavaScript
urable. values of present properties can still be changed as long as they are writable. 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 object.seal(obj) parameters obj the object which should be sealed. re
turn value the object being sealed. description by default, objects are extensible (new properties can be added to them). sealing an object prevents new properties from being added and marks all existing properties as non-configurable. this has the effect of making the set of properties on the object fixed and immutable. making all properties non-configurable also prevents them from being converted...
... existing properties // may be changed or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = object.seal(obj); o === obj; // true object.issealed(obj); // === true // changing property values on a sealed object // still works. obj.foo = 'quux'; // but you can't convert data properties to accessors, // or vice versa. object.defineproperty(obj, 'foo', { get: function() { re
turn 'g'; } }); // throws a typeerror // now any changes, other than to property values, // will fail. obj.quaxxor = 'the friendly duck'; // silently doesn't add the property delete obj.foo; // silently doesn't delete the property // ...and in strict mode such attempts // will throw typeerrors. function fail() { 'use strict'; delete obj.foo; // throws a typeerror obj.sparky = 'arf'; // throws ...
...so throw. object.defineproperty(obj, 'ohai', { value: 17 }); // throws a typeerror object.defineproperty(obj, 'foo', { value: 'eit' }); // changes existing property value non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object by simply re
turning it. object.seal(1); // typeerror: 1 is not an object (es5 code) object.seal(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.seal' in that specification. ...
Object.prototype.toLocaleString() - JavaScript
this function is provided to give objects a generic tolocalestring method, even though not all may use it. see the list below. ...
... this function is provided to give objects a generic tolocalestring method, even though not all may use it. see the list below. ...
...dden by derived objects for locale-specific purposes. 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 obj.tolocalestring() re
turn value a string representing the object. description object's tolocalestring re
turns the result of calling tostring(). this function is provided to give objects a generic tolocalestring method, even though not all may use it. see the list below. objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype...
Object.values() - JavaScript
the object.values() method re
turns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (the only difference is that a for...in loop enumerates properties in the prototype chain as well.) 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 object.values(obj) parameters obj the object whose enumerable own property values are to be re
turned. re
turn value an array containing the given object's own enumerable property values. description object.values() re
turns an array whose elements are the enumerable property values found on the object. the ...
...-entries or in the es-shims/object.values repositories. ...
... ...
Promise.allSettled() - JavaScript
the promise.allsettled() method re
turns 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. in comparison, the promise re
turned 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. ...
... successfully, or you'd always like to know the result of each promise. in comparison, the promise re
turned 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. re
turn 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 re
turned 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 ...
... for each outcome object, a status string is present. if the status is fulfilled, then a value is present. ...
Promise.prototype.finally() - JavaScript
the finally() method re
turns a promise. when the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. this provides a way for code to be run whether the promise was fulfilled successfully or rejected once the promise has been dealt with. this helps to avoid duplicating code in both the promise's then() and catch() handlers. syntax p.finally(onfinally); p.finally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function called when the promise is settled. re
turn value re
turns a promise whose finally handler is set to the specified function, onfinally. description the finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. the fin...
...ere's no need to provide it. so for example: unlike promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected with 3. ...
...when console = {} */ }) .finally(function() { isloading = false; }); please do not add polyfills on mdn pages. ...
Promise.race() - JavaScript
the promise.race() method re
turns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value 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. re
turn value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject. ...
...e 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. re
turn 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 re
turns 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 re
turned 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 i...
...race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 33 } an empty iterable causes the re
turned promise to be forever pending: var foreverpendingpromise = promise.race([]); console.log(foreverpendingpromise); settimeout(function(){ console.log('the stack is now empty'); console.log(foreverpendingpromise); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "pending" } if the iterable contains one or more non-promise value an...
Promise.reject() - JavaScript
for debugging purposes and selective error catching, it is useful to make reason an instanceof error. ...
...for debugging purposes and selective error catching, it is useful to make reason an instanceof error. ...
... 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 promise.reject(reason); parameters reason reason why this promise rejected. re
turn value a promise that is rejected with the given reason. description the static promise.reject function re
turns a promise that is rejected. for debugging purposes and selective error catching, it is useful to make reason an instanceof error. examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition...
handler.construct() - JavaScript
s and send us a pull request. syntax const p = new proxy(target, { construct: function(target, argumentslist, newtarget) { } }); parameters the following parameters are passed to the construct() method. this is bound to the handler. target the target object. argumentslist the list of arguments for the constructor. newtarget the constructor that was originally called, p above. re
turn value the construct method must re
turn an object. description the handler.construct() method is a trap for the new operator. interceptions this trap can intercept these operations: new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the new operator the foll...
... proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the new operator the following code traps the new operator. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); re
turn { value: argumentslist[0] * 10 }; } }); console.log(new p(1).value); // "called: 1" // 10 the following code violates the invariant. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { re
turn 1; } }); new p(); // typeerror is thrown the following code improperly initializes the proxy. the target in proxy initia...
...invariant. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { re
turn 1; } }); new p(); // typeerror is thrown the following code improperly initializes the proxy. the target in proxy initialization must itself be a valid constructor for the new operator. const p = new proxy({}, { construct: function(target, argumentslist, newtarget) { re
turn {}; } }); new p(); // typeerror is thrown, "p" is not a constructor specifications specification ecmascript (ecma-262)the definition of '[[construct]]' in that specification. ...
handler.deleteProperty() - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { deleteproperty: function(target, property) { } }); parameters the following parameters are passed to the deleteproperty() method. this is bound to the handler. target the target object. property the name or symbol of the property to delete. re
turn value the deleteproperty() method must re
turn a boolean indicating whether or not the property has been successfully deleted. description the handler.deleteproperty() method is a trap for the delete operator. interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants ...
...he proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. ...
...non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. const p = new proxy({}, { deleteproperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('property removed: ' + prop) re
turn true } else { console.log('property not found: ' + prop) re
turn false } } }) let result p.a = 10 console.log('a' in p) // true result = delete p.a // "property removed: a" console.log(result) // true console.log('a' in p) // false result = delete p.a // "property not found: a" console.log(result) // false specifications specification ecmascript (ecma-262)the definition of '[[delete]]' in that specification. ...
handler.get() - JavaScript
ractive-examples and send us a pull request. syntax const p = new proxy(target, { get: function(target, property, receiver) { } }); parameters the following parameters are passed to the get() method. this is bound to the handler. target the target object. property the name or symbol of the property to get. receiver either the proxy or an object that inherits from the proxy. re
turn value the get() method can re
turn any value. description the handler.get() method is a trap for getting a property value. interceptions this trap can intercept these operations: property access: proxy[foo]and proxy.bar inherited property access: object.create(proxy)[foo] reflect.get() invariants if the following invariants are violated, the proxy will throw a typeerror: the value ...
...e value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[get]] attribute. examples trap for getting a property value the following code traps getting a property value. ...
...tion(target, property, receiver) { console.log('called: ' + property); re
turn 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false }); const p = new proxy(obj, { get: function(target, property) { re
turn 20; } }); p.a; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[get]]' in that specification. ...
handler.has() - JavaScript
e to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { has: function(target, prop) { } }); parameters the following parameters are passed to has() method. this is bound to the handler. target the target object. prop the name or symbol of the property to check for existence. re
turn value the has() method must re
turn a boolean value. description the handler.has() method is a trap for the in operator. interceptions this trap can intercept these operations: property query: foo in proxy inherited property query: foo in object.create(proxy) with check: with(proxy) { (foo); } reflect.has() invariants if the following invariants are violated, the proxy will throw a t...
...stent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. examples trapping the in operator the following code traps the in operator. ...
...r the following code traps the in operator. const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); re
turn true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { re
turn false; } }); 'a' in p; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification. ...
handler.ownKeys() - JavaScript
e 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 p = new proxy(target, { ownkeys: function(target) { } }); parameters the following parameter is passed to the ownkeys() method. this is bound to the handler. target the target object. re
turn value the ownkeys() method must re
turn an enumerable object. description the handler.ownkeys() method is a trap for reflect.ownkeys(). interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() invariants if the following invariants are violated, the proxy will throw a typeerror: the result o...
...all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values. examples trapping of getownpropertynames the following code traps object.getownpropertynames(). ...
... console.log('called'); re
turn ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new proxy(obj, { ownkeys: function(target) { re
turn [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // typeerror: proxy [[ownpropertykeys]] must re
turn an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification. ...
handler.set() - JavaScript
originally directed. this is usually the proxy itself. but a set() handler can also be called indirectly, via the prototype chain or various other ways. for example: suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. that proxy's set() handler will be called, and obj will be passed as the receiver. re
turn value the set() method should re
turn a boolean value. re
turn true to indicate that assignment succeeded. if the set() method re
turns false, and the assignment happened in strict-mode code, a typeerror will be thrown. description the handler.set() method is a trap for setting property value. interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar ...
...cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[set]] attribute. ...
...t has undefined as its [[set]] attribute. in strict mode, a false re
turn value from the set() handler will throw a typeerror exception. examples trap setting of a property value the following code traps setting a property value. const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); re
turn true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true console.log(p.a); // 10 specifications specification ecmascript (ecma-262)the definition of '[[set]]' in that specification. ...
handler.setPrototypeOf() - JavaScript
ractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method. this is bound to the handler. target the target object. prototype the object's new prototype or null. re
turn value the setprototypeof() method re
turns true if the [[prototype]] was successfully changed, otherwise false. description the handler.setprototypeof() method is a trap for object.setprototypeof(). interceptions this trap can intercept these operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerro...
...se operations: object.setprototypeof() reflect.setprototypeof() invariants if the following invariants are violated, the proxy will throw a typeerror: if target is not extensible, the prototype parameter must be the same value as object.getprototypeof(target). examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either re
turn false, or it can throw an exception. approach 1: re
turning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as reflect.setprototyp...
...e
turning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself. for example, object.setprototypeof() will create and throw a typeerror itself. if the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as reflect.setprototypeof(), no exception will be thrown. const handlerre
turnsfalse = { setprototypeof(target, newproto) { re
turn false; } }; const newproto = {}, target = {}; const p1 = new proxy(target, handlerre
turnsfalse); object.setprototypeof(p1, newproto); // throws a typeerror reflect.setprototypeof(p1, newproto); // re
turns false approach 2: throwing an exception the latter approach will cause any operation that attempts to mutate, to throw. ...
Reflect.get() - JavaScript
om/mdn/interactive-examples and send us a pull request. syntax reflect.get(target, propertykey[, receiver]) parameters target the target object on which to get the property. propertykey the name of the property to get. receiver optional the value of this provided for the call to target if a getter is encountered. when used with proxy, it can be an object that inherits from target. re
turn value the value of the property. exceptions a typeerror, if target is not an object. description the reflect.get method allows you to get a property on an object. it is like the property accessor syntax as a function. examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler ...
...arget is not an object. description the reflect.get method allows you to get a property on an object. it is like the property accessor syntax as a function. ...
... ...
Reflect.setPrototypeOf() - JavaScript
the static reflect.setprototypeof() method is the same method as object.setprototypeof(), except for its re
turn type. it sets the prototype (i.e., the internal [[prototype]] property) of a specified object to another object or to null, and re
turns true if the operation was successful, or false otherwise. 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 reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. ...
...or 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 reflect.setprototypeof(target, prototype) parameters target the target object of which to set the prototype. prototype the object's new prototype (an object or null). re
turn value a boolean indicating whether or not the prototype was successfully set. exceptions a typeerror, if target is not an object or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setprototypeof() reflect.setprototypeof({},...
...ect or if prototype is neither an object nor null. description the reflect.setprototypeof method changes the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null. reflect.setprototypeof({}, null) // true // re
turns false if target is not extensible. reflect.setprototypeof(object.freeze({}), null) // false // re
turns false if it cause a prototype chain cycle. let target = {} let proto = object.create(target) reflect.setprototypeof(target, proto) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.setprototypeof' in that specification. ...
RegExp.prototype[@@replace]() - JavaScript
the replacement can be a string or a function to be called for each match. 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 regexp[symbol.replace](str, newsubstr|function) parameters str a string that is a target of the replacement. newsubstr (replacement) the string that replaces the substring. ...
...ng that replaces the substring. a number of special replacement patterns are supported; see the specifying a string as a parameter section in string.prototype.replace() page. function (replacement) a function to be invoked to create the new substring. the arguments supplied to this function are described in the specifying a function as a parameter section in string.prototype.replace() page. re
turn value a new string with some or all matches of a pattern replaced by a replacement. description this method is called internally in string.prototype.replace() if the pattern argument is a regexp object. for example, following two examples re
turn same result. 'abc'.replace(/a/, 'a'); /a/[symbol.replace]('abc', 'a'); this method exists for customizing replace behavior in regexp subclass. if...
...hod to modify the default behavior. class myregexp extends regexp { constructor(pattern, flags, count) { super(pattern, flags); this.count = count; } [symbol.replace](str, replacement) { // perform @@replace |count| times. var result = str; for (var i = 0; i < this.count; i++) { result = regexp.prototype[symbol.replace].call(this, result, replacement); } re
turn result; } } var re = new myregexp('\\d', '', 3); var str = '01234567'; var newstr = str.replace(re, '#'); // string.prototype.replace calls re[@@replace]. console.log(newstr); // ###34567 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@replace]' in that specification. ...
RegExp.prototype.test() - JavaScript
the test() method executes a search for a match between a regular expression and a specified string. re
turns true or false. 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 regexobj.test(str) parameters str the string against which to match the regular expression. re
turns true if there is a match between the regular expression and the string str. otherwise, false. description use test() whenever you want to know whether a pattern is found in a string. test() re
turns a boolean, unlike the string.prototype.search() method (which re
turns the index of a match, or -1 if not found). to get more informati...
...t more information (but with slower execution), use the exec() method. (this is similar to the string.prototype.match() method.) as with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. examples using test() simple example that tests if "hello" is contained at the very beginning of a string, re
turning a boolean result. const str = 'hello world!'; const result = /^hello/.test(str); console.log(result); // true the following example logs a message which depends on the success of the test: function testinput(re, str) { let midstring; if (re.test(str)) { midstring = 'contains'; } else { midstring = 'does not contain'; } console.log(`${str} ${midstring} ${re.source}`); } ...
... console.log(`${str} ${midstring} ${re.source}`); } using test() on a regex with the "global" flag when a regex has the global flag set, test() will advance the lastindex of the regex. (regexp.prototype.exec() also advances the lastindex property.) further calls to test(str) will resume searching str starting from lastindex. the lastindex property will continue to increase each time test() re
turns true. note: as long as test() re
turns true, lastindex will not reset—even when testing a different string! when test() re
turns false, the calling regex's lastindex property will reset to 0. the following example demonstrates this behaviour: const regex = /foo/g; // the "global" flag is set // regex.lastindex is at 0 regex.test('foo') // true // regex.lastindex is now at 3 regex.te...
RegExp - JavaScript
r or not the search is sticky. regexp.prototype.unicode whether or not unicode features are enabled. instance methods regexp.prototype.compile() (re-)compiles a regular expression during execution of a script. regexp.prototype.exec() executes a search for a match in its string parameter. regexp.prototype.test() tests for a match in its string parameter. regexp.prototype.tostring() re
turns a string representing the specified object. overrides the object.prototype.tostring() method. regexp.prototype[@@match]() performs match to given string and re
turns match result. regexp.prototype[@@matchall]() re
turns all matches of the regular expression against a string. regexp.prototype[@@replace]() replaces matches in given string with new substring. regexp.prototype[@@search]() sear...
... regexp.prototype[@@split]() splits given string into an array by separating the string into substrings. ...
...e works on all platforms. let text = 'some text\nand some more\r\nand yet\rthis is the end' let lines = text.split(/\r\n|\r|\n/) console.log(lines) // logs [ 'some text', 'and some more', 'and yet', 'this is the end' ] note that the order of the patterns in the regular expression matters. using regular expression on multiple lines let s = 'please yes\nmake my day!' s.match(/yes.*day/); // re
turns null s.match(/yes[^]*day/); // re
turns ["yes\nmake my day"] using a regular expression with the sticky flag the sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at regexp.prototype.lastindex. let str = '#foo#' let regex = /foo/y regex.lastindex = 1 regex.test(str) // true regex.lastindex = 5 regex.test(str)...
Set.prototype.has() - JavaScript
the has() method re
turns a boolean indicating whether an element with the specified value exists in a set object or not. 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 myset.has(value); parameters value the value to test for presence in the set object. re
turn value re
turns true if an element with the specified value exists in the set object; otherwise false. note: technically speaking, has() uses the samevaluezero algorithm to determine whether the given element is found. ...
...parameters value the value to test for presence in the set object. re
turn value re
turns true if an element with the specified value exists in the set object; otherwise false. note: technically speaking, has() uses the samevaluezero algorithm to determine whether the given element is found. ...
...est for presence in the set object. re
turn value re
turns true if an element with the specified value exists in the set object; otherwise false. note: technically speaking, has() uses the samevaluezero algorithm to determine whether the given element is found. examples using the has method var myset = new set(); myset.add('foo'); myset.has('foo'); // re
turns true myset.has('bar'); // re
turns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // re
turns true set1.has({'key1': 1}); // re
turns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications specification ecmascript (ecma-262)the definition of 'set.prototype.has' in that specification. ...
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method re
turns a string created by using the specified sequence of code points. 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 string.fromcodepoint(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. re
turn value a string created by using the specified sequence of code points. exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this method re
turns a string (and not a string object). because fromcodepoint() is a static method of string, you must call...
.../javascript-encoding#surrogate-formulae codepoint -= 0x10000; codelen = codeunits.push( (codepoint >> 10) + 0xd800, // highsurrogate (codepoint % 0x400) + 0xdc00 // lowsurrogate ); } if (codelen >= 0x3fff) { result += stringfromcharcode.apply(null, codeunits); codeunits.length = 0; } } re
turn result + stringfromcharcode.apply(null, codeunits); }; try { // ie 8 only supports `object.defineproperty` on dom elements object.defineproperty(string, "fromcodepoint", { "value": fromcodepoint, "configurable": true, "writable": true }); } catch(e) { string.fromcodepoint = fromcodepoint; } }(string.fromcharcode)); examples using fromcodepoint() valid...
...61, 0x1d307); // "\ud834\udf06a\ud834\udf07" invalid input: string.fromcodepoint('_'); // rangeerror string.fromcodepoint(infinity); // rangeerror string.fromcodepoint(-1); // rangeerror string.fromcodepoint(3.14); // rangeerror string.fromcodepoint(3e-2); // rangeerror string.fromcodepoint(nan); // rangeerror compared to fromcharcode() string.fromcharcode() cannot re
turn supplementary characters (i.e. code points 0x010000 – 0x10ffff) by specifying their code point. instead, it requires the utf-16 surrogate pair in order to re
turn a supplementary character: string.fromcharcode(0xd83c, 0xdf03); // code point u+1f303 "night with string.fromcharcode(55356, 57091); // stars" == "\ud83c\udf03" string.fromcodepoint(), on the other hand, can re
turn 4-byte suppleme...
String.prototype.includes() - JavaScript
the includes() method determines whether one string may be found within another string, re
turning true or false as appropriate. 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 str.includes(searchstring[, position]) parameters searchstring a string to be searched for within str. position optional the position within the string at which to begin searching for searchstring. (defaults to 0.) re
turn value true if the search string is found anywhere within the given string; otherwise, false if not. description this method lets you determine whether or not a string includes another string. case-sensiti...
... the position within the string at which to begin searching for searchstring. (defaults to 0.) re
turn value true if the search string is found anywhere within the given string; otherwise, false if not. description this method lets you determine whether or not a string includes another string. case-sensitivity the includes() method is case sensitive. for example, the following expression re
turns false: 'blue whale'.includes('blue') // re
turns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can easily polyfill this method: if (!string.prototype.includes) { string.prototype.includes = function(search, start) { 'use strict'; if (search instanceof regexp) { thr...
...cript 2015 specification and may not be available in all javascript implementations yet. ...
String.prototype.search() - JavaScript
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 str.search(regexp) parameters regexp a regular expression object. if a non-regexp object regexp is passed, it is implicitly converted to a regexp with new regexp(regexp). ...
...tly converted to a regexp with new regexp(regexp). re
turn value the index of the first match between the regular expression and the given string, or -1 if no match was found. description when you want to know whether a pattern is found, and also know its index within a string, use search(). (if you only want to know if it exists, use the similar test() method on the regexp prototype, which re
turns a boolean.) for more information (but slower execution) use match() (similar to the regular expression exec() method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. ...
...e
turns a boolean.) for more information (but slower execution) use match() (similar to the regular expression exec() method). examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1) let str = "hey jude" let re = /[a-z]/g let redot = /[.]/g console.log(str.search(re)) // re
turns 4, which is the index of the first capital letter "j" console.log(str.search(redot)) // re
turns -1 cannot find '.' dot punctuation specifications specification ecmascript (ecma-262)the definition of 'string.prototype.search' in that specification. ...
String.prototype.toLocaleUpperCase() - JavaScript
the tolocaleuppercase() method re
turns the calling string value converted to upper case, according to any locale-specific case mappings. 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 str.tolocaleuppercase() str.tolocaleuppercase(locale) str.tolocaleuppercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to upper case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. ...
....tolocaleuppercase() str.tolocaleuppercase(locale) str.tolocaleuppercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to upper case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. re
turn value a new string representing the calling string converted to upper case, according to any locale-specific case mappings. exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocaleuppercase() method retu...
...w the default case mappings in unicode, there may be a different result. also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. therefore the length of the result string can differ from the input length. this also implies that the conversion is not stable, so i.e. ...
String.prototype.toLowerCase() - JavaScript
tolowercase() does not affect the value of the string str itself. ...
...tolowercase() does not affect the value of the string str itself. ...
...rted to lower case. 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 str.tolowercase() re
turn value a new string representing the calling string converted to lower case. description the tolowercase() method re
turns the value of the string converted to lower case. tolowercase() does not affect the value of the string str itself. examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification. ...
String.prototype.trimStart() - JavaScript
the trimstart() method removes whitespace from the beginning of a string. trimleft() is an alias of this method. 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 str.trimstart(); str.trimleft(); re
turn value a new string representing the calling string stripped of whitespace from its beginning (left end). description the trimstart() / trimleft() methods re
turn the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, for...
...ft remains as an alias to trimstart. ...
...alse:true:true){ var r=/^\s+/; o[p]=o.trimleft||function(){ re
turn this.replace(r,'') } } })(proto,'trimstart'); })(window); /* es6: (w=>{ const string=w.string, proto=string.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimleft||function(){ re
turn this.replace(r,'') } } })(proto,'trimstart'); })(window); */ examples using trimstart() the following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimstart(); console.log(str.length); // 5 console.log(str); // 'foo ' specifications specification ecmascript (ecma-262)th...
Symbol.toStringTag - JavaScript
e]" // ... and more custom classes default to object tag when creating your own class, javascript defaults to the "object" tag: class validatorclass {} object.prototype.tostring.call(new validatorclass()); // "[object object]" custom tag with tostringtag now, with the help of tostringtag, you are able to set your own custom tag: class validatorclass { get [symbol.tostringtag]() { re
turn 'validator'; } } object.prototype.tostring.call(new validatorclass()); // "[object validator]" tostringtag available on all dom prototype objects due to a webidl spec change in mid-2020, browsers are adding a symbol.tostringtag property to all dom prototype objects. for example, to acccess the symbol.tostringtag property on htmlbuttonelement: let test = document.createelement('button'); te...
... ...
...t validator]" tostringtag available on all dom prototype objects due to a webidl spec change in mid-2020, browsers are adding a symbol.tostringtag property to all dom prototype objects. for example, to acccess the symbol.tostringtag property on htmlbuttonelement: let test = document.createelement('button'); test.tostring(); // re
turns [object htmlbuttonelement] test[symbol.tostringtag]; // re
turns htmlbuttonelement specifications specification ecmascript (ecma-262)the definition of 'symbol.tostringtag' in that specification. ...
TypedArray.from() - JavaScript
darray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters source an array-like or iterable object to convert to a typed array. mapfn optional map function to call on every element of the typed array. thisarg optional value to use as this when executing mapfn. re
turn value a new typedarray instance. description typedarray.from() lets you create typed arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects where you can get its elements, such as map and set). typedarray.from() has the optional parameter mapfn, which allows you to execute a map() function on each element of the typed array (or...
..., func, thisobj) { var typedarrayclass = int8array.__proto__; if(typeof this !== 'function') { throw new typeerror('# is not a constructor'); } if (this.__proto__ !== typedarrayclass) { throw new typeerror('this is not a typed array.'); } func = func || function (elem) { re
turn elem; }; if (typeof func !== 'function') { throw new typeerror('specified argument is not a function'); } obj = object(obj); if (!obj['length']) { re
turn new this(0); } var copy_data = []; for(var i = 0; i < obj.length; i++) { copy_data.push(obj[i])...
...); } var copy_data = []; for(var i = 0; i < obj.length; i++) { copy_data.push(obj[i]); } copy_data = copy_data.map(func, thisobj); var typed_array = new this(copy_data.length); for(var i = 0; i < typed_array.length; i++) { typed_array[i] = copy_data[i]; } re
turn typed_array; } })(); } examples from an iterable object (set) const s = new set([1, 2, 3]); uint8array.from(s); // uint8array [ 1, 2, 3 ] from a string int16array.from('123'); // int16array [ 1, 2, 3 ] use with arrow function and map using an arrow function as the map function to manipulate the elements float32array.from([1, 2, 3], x => x + x); // float32array [ 2, 4, 6 ] ...
TypedArray.prototype.reduceRight() - JavaScript
ue of the typed array (from right-to-left) has to reduce it to a single value. this method has the same algorithm as array.prototype.reduceright(). typedarray is one of the typed array types here. ...
...ly re
turned in the last invocation of the callback, or initialvalue, if supplied (see below). currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array reduce was called upon. initialvalue optional. object to use as the first argument to the first call of the callback. re
turn value the value that results from the reduction. description the reduceright method executes the callback function once for each element present in the typed array, excluding holes in the typed array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the typed array over which iteration is occurring.
...reviousvalue will be equal to the last value in the typed array and currentvalue will be equal to the second-to-last value. if the typed array is empty and no initialvalue was provided, typeerror would be thrown. if the typed array has only one element (regardless of position) and no initialvalue was provided, or if initialvalue is provided but the typed array is empty, the solo value would be re
turned without calling callback. examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { re
turn a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduceright' in that specification. ...
WebAssembly.Global - JavaScript
d importable/exportable across one or more webassembly.module instances. this allows dynamic linking of multiple modules. constructor webassembly.global() creates a new global object. global instances all global instances inherit from the global() constructor's prototype object — this can be modified to affect all global instances. instance properties global.prototype.constructor re
turns the function that created this object's instance. by default this is the webassembly.global() constructor. global.prototype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global". global.prototype.value the value contained inside the global variable — this can be used to directly set and get the global's value. instance methods global.p...
...stance. by default this is the webassembly.global() constructor. global.prototype[@@tostringtag] the initial value of the @@tostringtag property is the string value "webassembly.global". global.prototype.value the value contained inside the global variable — this can be used to directly set and get the global's value. instance methods global.prototype.valueof() old-style method that re
turns the value contained inside the global variable. examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exp...
... the following example shows a new global instance being created using the webassembly.global() constructor. it is being defined as a mutable i32 type, with a value of 0. the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then re
turns the new value). const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "funct...
WebAssembly.Memory - JavaScript
mory object is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance. a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. constructor webassembly.memory() creates a new memory object. instance properties memory.prototype.buffer an accessor property that re
turns the buffer contained in the memory. instance methods memory.prototype.grow() increases the size of the memory instance by a specified number of webassembly pages (each one is 64kb in size). examples creating a new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a new webassembly memory ...
...tance by a specified number of webassembly pages (each one is 64kb in size). examples creating a new memory object there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will re
turn an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created...
... < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new webassembly.memory({initial:10, maximum:100, shared: true}); this memory's buffer property will re
turn a sharedarraybuffer. specifications specification webassembly javascript interfacethe definition of 'memory' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmob...
WebAssembly.Module.customSections() - JavaScript
exceptions if module is not a webassembly.module object instance, a typeerror is thrown. description a wasm module is comprised of a sequence of sections. ...
... exceptions if module is not a webassembly.module object instance, a typeerror is thrown. description a wasm module is comprised of a sequence of sections. ...
...omsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code. we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0. since there is a "name" section in the example, an arraybuffer object is re
turned. webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namesections = webassembly.module.customsections(mod, "name"); if (namesections.length != 0) { console.log("module contains a name section"); console.log(namesections[0]); }; }); specifications specification webassembly javascript interfacethe definition of 'customse...
WebAssembly.instantiate() - JavaScript
the webassembly.instantiate() function allows you to compile and instantiate webassembly code. this function has two overloads: the primary overload takes the webassembly binary code, in the form of a typed array or arraybuffer, and performs both compilation and instantiation in one step. the re
turned promise resolves to both a compiled webassembly.module and its first webassembly.instance. the secondary overload takes an already-compiled webassembly.module and re
turns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fet...
...s buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. 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 the compiled module or else a webassembly.linkerror is thrown. re
turn value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated again, shared via postmessage() or cached in indexeddb. instance: a webassembly.instance object that contains all the exported webassembly functions. exceptions if either of the parameters are not of ...
...stance> webassembly.instantiate(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. re
turn value a promise that resolves to an webassembly.instance object. exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembl...
Comma operator (,) - JavaScript
the comma operator (,) evaluates each of its operands (from left to right) and re
turns the value of the last operand. this lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. this is commonly used to provide multiple parameters to a for 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. syntax expr1, expr2, expr3... parameters expr1, expr2, expr3... one or more expressions, the last of which is re
turned as the value of the compound expression. usage notes you can use the c...
...ements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]); note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. in the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result re
turned to console (i.e., 4). this is due to operator precedence and associativity. var a, b, c; a = b = 3, c = 4; // re
turns 4 in console console.log(a); // 3 (left-most) var x, y, z; x = (y = 5, z = 6); // re
turns 6 in console console.log(x); // 6 (right-most) processing and then re
turning another example that one could make with comma operator is processing before re
turning. as stated, only t...
...his is due to operator precedence and associativity. var a, b, c; a = b = 3, c = 4; // re
turns 4 in console console.log(a); // 3 (left-most) var x, y, z; x = (y = 5, z = 6); // re
turns 6 in console console.log(x); // 6 (right-most) processing and then re
turning another example that one could make with comma operator is processing before re
turning. as stated, only the last element will be re
turned but all others are going to be evaluated as well. so, one could do: function myfunc() { var x = 0; re
turn (x += 1, x); // the same as re
turn ++x; } specifications specification ecmascript (ecma-262)the definition of 'comma operator' in that specification. ...
Logical OR assignment (||=) - JavaScript
ment (x ||= y) operator only assigns if x is falsy. 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 expr1 ||= expr2 description short-circuit evaluation the logical or operator works like this: x || y; // re
turns x when x is truthy // re
turns y when x is not truthy the logical or operator short-circuits: the second operand is only evaluated if the first operand doesn’t already determine the result. logical or assignment short-circuits as well, meaning it only performs an assignment if the logical operation would evaluate the right-hand side. in other words, x ||= y is equivalent to: x || (x = y); ...
... specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification. ...
...o a default value: document.getelementbyid('lyrics').innerhtml ||= '<i>no lyrics.</i>' here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc. note: pay attention to the value re
turned by the api you're checking against. if an empty string is re
turned (a falsy value), ||= must be used, otherwise you want to use the ??= operator (for null or undefined re
turn values). specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification. ...
Optional chaining (?.) - JavaScript
the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. the ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a re
turn value of undefined. when used with function calls, it re
turns undefined if the given function does not exist. this results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. it can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required. the source fo...
...xplicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedprop = obj.first?.second; by using the ?. operator instead of just ., javascript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. if obj.first is null or undefined, the expression automatically short-circuits, re
turning undefined. this is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedprop = ((temp === null || temp === undefined) ? undefined : temp.second); optional chaining with function calls you can use optional chaining when attempting to call a method which may not exist. this can be helpful, for example, when using an api in w...
...ning with function calls you can use optional chaining when attempting to call a method which may not exist. this can be helpful, for example, when using an api in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. using optional chaining with function calls causes the expression to automatically re
turn undefined instead of throwing an exception if the method isn't found: let result = someinterface.custommethod?.(); note: if there is a property with such a name and which is not a function, using ?. will still raise a typeerror exception (someinterface.custommethod is not a function). note: if someinterface itself is null or undefined, a typeerror exception will still be raised (someinterfa...
await - JavaScript
description the await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. when resumed, the value of the await expression is that of the fulfilled promise. ...
...ession following the await operator is not a promise, it's converted to a resolved promise. an await can split execution flow, allowing the caller of the await's function to resume execution before the deferred continuation of the await's function. ...
...he continuation of its function, if this is the first await executed by the function, immediate execution also continues by re
turning to the function's caller a pending promise for the completion of the await's function and resuming execution of that caller. examples awaiting a promise to be fulfilled if a promise is passed to an await expression, it waits for the promise to be fulfilled and re
turns the fulfilled value. function resolveafter2seconds(x) { re
turn new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); console.log(x); // 10 } f1(); thenable objects thenable objects will be fulfilled just the same. async function f2() { const thenable = { then: function(resolve, _rej...
class expression - JavaScript
ou to redefine (re-declare) classes without throwing a syntaxerror. this is not the case with class statements. the constructor method is optional. classes generated with class expressions will always respond to typeof with the value "function". 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // re
turns "function" typeof class {}; // re
turns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo. const foo = class { constructor() {} ba...
... typeof class {}; // re
turns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo. const foo = class { constructor() {} bar() { re
turn 'hello world!'; } }; const instance = new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression. the name is only visible within the scope of the class expression itself. ...
... re
turn 'hello world!'; } }; const instance = new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression. the name is only visible within the scope of the class expression itself. const foo = class namedfoo { constructor() {} whoisthere() { re
turn namedfoo.name; } } const bar = new foo(); bar.whoisthere(); // "namedfoo" namedfoo.name; // referenceerror: namedfoo is not defined foo.name; // "namedfoo" specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
Function expression - JavaScript
() { console.log('bar'); }; named function expression if you want to refer to the current function inside the function body, you need to create a named function expression. this name is then local only to the function body (scope). this also avoids using the non-standard arguments.callee property. let math = { 'factit': function factorial(n) { console.log(n) if (n <= 1) { re
turn 1; } re
turn n * factorial(n - 1); } }; math.factit(3) //3;2;1; the variable the function expression is assigned to will have a name property. the name doesn't change if it's assigned to a different variable. if function name is omitted, it will be the variable name (implicit name). if function name is present, it will be the function name (explicit name). this also applies to arrow f...
...e). var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x. ...
... foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) examples creating an unnamed function the following example defines an unnamed function and assigns it to x. ...
super - JavaScript
this code snippet is taken from the classes sample (live demo). here super() is called to avoid duplicating the constructor parts' that are common between rectangle and square. ...
... // provided for the rectangle's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference error. this.name = 'square'; } } super-calling static methods you are also able to call super on static methods. ...
...per() must be called before you // can use 'this'. leaving this out will cause a reference error. this.name = 'square'; } } super-calling static methods you are also able to call super on static methods. class rectangle { constructor() {} static lognbsides() { re
turn 'i have 4 sides'; } } class square extends rectangle { constructor() {} static logdescription() { re
turn super.lognbsides() + ' which are all equal'; } } square.logdescription(); // 'i have 4 sides which are all equal' deleting super properties will throw an error you cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a referenceerror. class base { constructor() {} foo() {} } class derived extends base { constructor() {} delet...
try...catch - JavaScript
row e; // re-throw the error unchanged } } the exception identifier when an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value. you can use this identifier to get information about the exception that was thrown. this identifier is only available in the catch-block's scope. function isvalidjson(text) { try { json.parse(text); re
turn true; } catch { re
turn false; } } the finally-block the finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. note that the finally-block executes regardless of whether an exception is thrown. also, if an exception is thrown, the statements in the finally-block execute even if no...
...finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" // "outer" "oops" any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block. re
turning from a finally-block if the finally-block re
turns a value, this value becomes the re
turn value of the entire try-catch-finally statement, regardless of any re
turn statements in the try and catch-blocks. this includes exceptions thrown inside of the catch-block: (function() { try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); ...
...alue becomes the re
turn value of the entire try-catch-finally statement, regardless of any re
turn statements in the try and catch-blocks. this includes exceptions thrown inside of the catch-block: (function() { try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); re
turn; } } catch (ex) { console.error('outer', ex.message); } })(); // output: // "inner" "oops" // "finally" the outer "oops" is not thrown because of the re
turn in the finally-block. the same would apply to any value re
turned from the catch-block. specifications specification ecmascript (ecma-262)the definition of 'try statement' in that specification. ...
Critical rendering path - Web Performance
uence of steps the browser goes through to convert the html, css, and javascript into pixels on the screen. optimizing the critical render path improves render performance.the critical rendering path includes the document object model (dom), css object model (cssom), render tree and layout. the document object model is created as the html is parsed. the html may request javascript, which may, in
turn, alter the dom. the html includes or makes requests for styles, which in
turn builds the css object model. the browser engine combines the two to create the render tree. layout determines the size and location of everything on the page. once layout is determined, pixels are painted to the screen. optimizing the critical rendering path improves the time to first render. understanding and optimizi...
... critical rendering path is important to ensure reflows and repaints can happen at 60 frames per second, to ensure performant user interactions and avoid jank. understanding crp web performance includes the server requests and responses, loading, scripting, rendering, layout, and the painting of the pixels to the screen. a request for a web page or app starts with an html request. the server re
turns the html - response headers and data. the browser then begins parsing the html, converting the received bytes to the dom tree. the browser initiates requests every time it finds links to external resources, be they stylesheets, scripts, or embedded image references. some requests are blocking, which means the parsing of the rest of the html is halted until the imported asset is handled. the brow...
...ucts the css object model. with the dom and cssom complete, the browser builds the render tree, computing the styles for all the visible content. after the render tree is complete, layout occurs, defining the location and size of all the render tree elements. once complete, the page is rendered, or 'painted' on the screen. document object model dom construction is incremental. the html response
turns into tokens which
turns into nodes which
turn into the dom tree. a single dom node starts with a starttag token and ends with an endtag token. nodes contain all relevant information about the html element. the information is described using tokens. nodes are connected into a dom tree based on token hierarchy. if another set of starttag and endtag tokens come between a set of starttag and endtags...
Structural overview of progressive web apps - Progressive web apps (PWAs)
amesimages); with the file list prepared, it's time to install the service worker itself. the service worker will actually handle caching all the listed files. ...
...all the listed files. ...
...h that done, we implement the service worker's fetch event handler; its job is to re
turn the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); re
turn r || fetch(e.request).then(function(response) { re
turn caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); re
turn response; }); }); }) ); }); auxiliary javascript file: games.js the games data for this app example is provided in a jav...
document - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the document finds a node-set in an external document, or multiple external documents, and re
turns the resulting node-set. syntax document(uri [,node-set] ) arguments uri an absolute or relative uri of the document to be retrieved. the uri may also include a fragment identifier. node-set (optional) an expression pointing to a node-set in the external document that should be re
turned. re
turns a node-set. notes if the uri contains a fragment identifier and that fragment can be identified in the external document, that fragment will be treated as the root in the node-set argument's expression. if the node-set argument is omitted, the entire fragment will be re
turned. if t...
...contains a fragment identifier and that fragment can be identified in the external document, that fragment will be treated as the root in the node-set argument's expression. if the node-set argument is omitted, the entire fragment will be re
turned. if the uri argument is a node-set, and the second argument is present, each node in the node-set will be evaluated as a separate uri, and the re
turned node-set will be as if the document function has been called multiple times (each time with the same second argument just as given in the function call) and the resulting node-sets had been concatenated into a single node-set. other specific conditions exist with specified behaviors. see the xslt 1.0 documentation for details. since the uri is relative to the xsl document, document("") ...
...set will be as if the document function has been called multiple times (each time with the same second argument just as given in the function call) and the resulting node-sets had been concatenated into a single node-set. other specific conditions exist with specified behaviors. see the xslt 1.0 documentation for details. since the uri is relative to the xsl document, document("") would re
turn the root node of the current document. this function is an xslt-specific addition to xpath. it is not a part of the core xpath function library. defined xslt 1.0 12.1 gecko support supported. ...
key - XPath
notes the xsl:key element defines what attribute on what given elements will be used to match the key. this function is an xslt-specific addition to xpath. ...
... notes the xsl:key element defines what attribute on what given elements will be used to match the key. this function is an xslt-specific addition to xpath. ...
... notes the xsl:key element defines what attribute on what given elements will be used to match the key. this function is an xslt-specific addition to xpath. ...
not - XPath
you can test if an element doesn't have some attribute. ...
... you can test if an element doesn't have some attribute. ...
... you can test if an element doesn't have some attribute. <xsl:for-each match="//a[not(@name and @name = 'badname')]"> <!-- iterates over any <a> element in the document, that either has no 'name' attribute at all, or it has one, but its value is not "badname". --> </xsl:template> defined xpath 1.0 4.3 gecko support supported. ...
substring - XPath
notes as in other xpath functions, the position is not zero-based. ...
... notes as in other xpath functions, the position is not zero-based. ...
... notes as in other xpath functions, the position is not zero-based. the first character in the string has a position of 1, not 0. ...
Exported WebAssembly functions - WebAssembly
functions it references via tbl.get() and log the result of invoking each one to the console. next, we use set() to make the othertable table contain references to the same functions as the tbl table. to prove this, we then retrieve these references back from othertable and print their results to console too, which gives the same results. they are real functions in the previous example, the re
turn value of each table.prototype.get() call is an exported webassembly function — exactly what we have been talking about. it is worth noting that these are real javascript functions, in addition to being wrappers for webassembly functions. if you load the above example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof test...
...l is an exported webassembly function — exactly what we have been talking about. it is worth noting that these are real javascript functions, in addition to being wrappers for webassembly functions. if you load the above example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof testfunc; you'll get the result function re
turned. you can then go on to do pretty much anything to this function that you can do to other functions in javascript — call(), bind(), etc. testfunc.tostring() re
turns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nature. some other particulars to be aware of with exported webassembly functions: their length property is the numb...
... [native code] } this gives you more of an idea of its wrapper-type nature. some other particulars to be aware of with exported webassembly functions: their length property is the number of declared arguments in the wasm function signature. their name property is the tostring() result of the function's index in the wasm module. if you try to call a exported wasm function that takes or re
turns an i64 type value, it currently throws an error because javascript currently has no precise way to represent an i64. this may well change in the future though — a new int64 type is being considered for future standards, which could then be used by wasm. ...
Reddit Example - Archive of obsolete content
.url("jquery-2.1.0.min.js"), data.url("panel.js")] }); reddit_panel.port.on("click", function(url) { require("sdk/tabs").open(url); }); this code supplies two content scripts to the panel's constructor in the contentscriptfile option: the jquery library and the script that intercepts link clicks. ...
...brary and the script that intercepts link clicks. finally, it registers a listener to the user-defined click event which in
turn passes the url into the open function of the tabs module. this is the panel.js content script that intercepts link clicks: $(window).click(function (event) { var t = event.target; // don't intercept the click if it isn't on a link. if (t.nodename != "a") re
turn; // don't intercept the click if it was on one of the links in the header // or next/previous footer, since those links should load in the panel itself. if ($(t).parents('#header').length || $(t).parents('.nextprev').length) re
turn; // intercept the click, passing it to the addon, which will load it in a tab. event.stoppropagation(); event.preventdefault(); self.port.emit('cli...
Content Processes - Archive of obsolete content
ss), whereas each tab and each add-on would run in their own dedicated process (called content and add-on processes, respectively). the project behind this refactor was known as electrolysis, or e10s. although e10s has now been suspended, the sdk was designed with this multiprocess model in mind. afterwards, it was decided to keep the design the way it is: even though it's no longer necessary, it
turns out that from a security point of view there are several important advantages to thinking about content and add-on code as living in different processes. many add-ons have to interact with content. the problem with the multiprocess model is that add-ons and content are now in different processes, and scripts in one process cannot interact directly with scripts in another. we can, however, pass ...
...ed on the other event emitter. suppose we have two event emitters in different processes, and we want them to be able to emit events to each other. in this case, we would replace the emit function passed to the constructor of each emitter with a function that sends a message to the other process. we can then hook up a listener to be called when this message arrives at the other process, which in
turn calls the emit function on the other event emitter. the combination of this function and the corresponding listener is referred to as a pipe. content workers a content worker is an object that is used to inject content scripts into a content process, and to provide a pipe between each content script and the main add-on script. the idea is to use a single content worker for each content process.
Module structure of the SDK - Archive of obsolete content
s add-on places external modules in a "dependencies" directory: my-addon lib main.js dependencies geolocation.js it can then load them in the same way it would load a local module. ...
... dependencies geolocation.js it can then load them in the same way it would load a local module. for example, to load from main: // main.js code var geo = require("./dependencies/geolocation"); freezing the sdk freezes the exports object re
turned by require. ...
base64 - Archive of obsolete content
tes a base-64 encoded ascii string from a string of binary data. parameters data : string the data to encode charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". in order to encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); var encodeddata = base64.encode(unicodestring, "utf-8"); re
turns string : the encoded string decode(data, charset) decodes a string of data which has been encoded using base-64 encoding. parameters data : string the encoded data charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". in order to encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); v...
...codes a string of data which has been encoded using base-64 encoding. parameters data : string the encoded data charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". in order to encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); var decodeddata = base64.decode(encodeddata, "utf-8"); re
turns string : the decoded string ...
private-browsing - Archive of obsolete content
erived from such objects. additionally, add-ons that use low-level modules such as window/utils may see private browser windows with certain functions, even if they have not explicitly opted into private browsing. respecting private browsing the private-browsing module exports a single function isprivate() that takes an object, which may be a browserwindow, tab, or worker, as an argument. it re
turns true only if the object is: a private window, or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (options->privacy->history) add-ons can use this api to decide whether or not to store user data. for example, here's an add-on that stores the...
...ed. to do this with the sdk, you can listen to the system event named "last-pb-context-exited": var events = require("sdk/system/events"); function listener(event) { console.log("last private window closed"); } events.on("last-pb-context-exited", listener); globals functions isprivate(object) function to check whether the given object is private. it takes an object as an argument, and re
turns true only if the object is: a private browserwindow or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window parameters object : any the object to check. this may be a browserwindow, tab, or worker. ...
request - Archive of obsolete content
ry string (content) will be appended to the url. for post and put requests, it will be sent as the body of the request. contenttype string the type of content to send to the server. this explicitly sets the content-type header. the default value is application/x-www-form-urlencoded. overridemimetype string use this string to override the mime type re
turned by the server in the response's content-type header. you can use this to treat the content as a different mime type, or to force text to be interpreted using a specific character. for example, if you're retrieving text content which was encoded as iso-8859-1 (latin 1), it will be given a content type of "utf-8" and certain characters will not display correctly. to force the response to be ...
...uest. properties url headers content contenttype response events complete the request object emits this event when the request has completed and a response has been received. arguments response : listener functions are passed the response to the request as a response object. response the response object contains the response to a network request issued using a request object. it is re
turned by the get(), head(), post(), put() or delete() method of a request object. all members of a response object are read-only. properties url the url of the response content. text the content of the response as plain text. json the content of the response as a javascript object. the value will be null if the document cannot be processed by json.parse. status the http response status code...
selection - Archive of obsolete content
quire("sdk/selection"); selection.on('select', function () { selection.html = "\\\" + selection.html + "///"; }); globals properties text gets or sets the current selection as plain text. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when there is no current selection re
turns null. setting the selection when there is no current selection throws an exception. getting the selection when iscontiguous is true re
turns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when ...
...en there is no current selection throws an exception. getting the selection when iscontiguous is true re
turns the text of the first selection. html gets or sets the current selection as html. setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. getting the selection when there is no current selection re
turns null. setting the selection when there is no current selection throws an exception. getting the selection when iscontiguous is true re
turns the text of the first selection. iscontiguous true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may or may not be spatially adjacent. (discontiguous selections can be crea...
timers - Archive of obsolete content
set one-off and periodic timers. globals constructors functions settimeout(callback, ms) schedules callback to be called in ms milliseconds. any additional arguments are passed straight through to the callback. parameters callback : function function to be called. ms : integer interval in milliseconds after which the function will be called. re
turns integer : an id that can later be used to undo this scheduling, if callback hasn't yet been called. example var { settimeout } = require("sdk/timers"); settimeout(function() { // do something in 0 ms }, 0) cleartimeout(id) given an id re
turned from settimeout(), prevents the callback with the id from being called (if it hasn't yet been called). parameters id : integer an id re
turned from settimeout(). example var { setti...
...ction() { // do something in 1 sec }, 1000); // to stop/cancel this timeout cleartimeout(id); setinterval(callback, ms) schedules callback to be called repeatedly every ms milliseconds. any additional arguments are passed straight through to the callback. parameters callback : function function to be called. ms : integer interval in milliseconds at which the function will be called. re
turns integer : an id that can later be used to unschedule the callback. example var { setinterval } = require("sdk/timers"); setinterval(function() { // do something every 1 sec }, 1000) clearinterval(id) given an id re
turned from setinterval(), prevents the callback with the id from being called again. parameters id : integer an id re
turned from setinterval(). example var { setinterval...
widget - Archive of obsolete content
t. removelistener(type, listener) unregisters an event listener from the widget. parameters type : string the type of event for which listener was registered. listener : function the listener function that was registered. getview(window) retrieve a widgetview instance of this widget relative to a browser window. parameters window : browserwindow the browserwindow instance to match. re
turns widgetview : a widgetview instance associated with the browser window. any changes subsequently applied to this object will only be applied to the widget attached to that window. properties label the widget's label. read-only. content a string containing the widget's content. it can contain html. setting it updates the widget's appearance immediately. however, if the widget was created usi...
... postmessage(data) sends a message to the widget view's content scripts. parameters data : value the message to send. the message can be any json-ser...
windows - Archive of obsolete content
th multiprocess firefox. globals functions open(options) open a new window. var windows = require("sdk/windows").browserwindows; // open a new window. windows.open("http://www.example.com"); // open a new window and set a listener for "open" event. windows.open({ url: "http://www.example.com", onopen: function(window) { // do stuff like listen for content // loading. } }); re
turns the window that was opened: var windows = require("sdk/windows").browserwindows; var example = windows.open("http://www.example.com"); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { example.close(); } }); this example uses the action button api, which is only available from firefox 29 onwards. parameters o...
... a callback function that is called when the window will be called. this is an optional property. onactivate function a callback function that is called when the window is made active. this is an optional property. ondeactivate function a callback function that is called when the window is made inactive. this is an optional property. re
turns browserwindow : properties browserwindows browserwindows provides access to all the currently open browser windows as browserwindow objects. var windows = require("sdk/windows"); for (let window of windows.browserwindows) { console.log(window.title); } console.log(windows.browserwindows.length); the currently active window is given by browserwindows.activewindow: var windows = require(...
event/core - Archive of obsolete content
, listener) removes an event listener for the given event type on the given event target. ...
...tener is passed removes all listeners of the given type. if type is not passed removes all the listeners of the given event target. ...
io/byte-streams - Archive of obsolete content
experimental provides streams for reading and writing bytes. function readbinarydatafromfile (filename) { var fileio = require("sdk/io/file"); var data = null; if (fileio.exists(filename)) { var bytereader = fileio.open(filename, "rb"); if (!bytereader.closed) { data = bytereader.read(); bytereader.close(); } } re
turn data; } function writebinarydatatofile(data, filename) { var fileio = require("sdk/io/file"); var bytewriter = fileio.open(filename, "wb"); if (!bytewriter.closed) { bytewriter.write(data); bytewriter.close(); } } globals constructors bytereader(inputstream) creates a binary input stream that reads bytes from a backing stream. you can also create bytereader objects using io/file's open() function. parameters inputstr...
...eam the backing stream, an nsioutputstream. bytereader methods close() closes both the stream and its backing stream. if the stream is already closed, an exception is thrown. read(numbytes) reads a string from the stream. if the stream is closed, an exception is thrown. parameters numbytes : number the number of bytes to read. if not given, the remainder of the entire stream is read. re
turns string : a string containing the bytes read. if the stream is at the end, re
turns the empty string. properties closed true if the stream is closed. bytewriter methods close() closes both the stream and its backing stream. if the stream is already closed, an exception is thrown. write(str) writes a string to the stream. if the stream is closed, an exception is thrown. parameters str :...
io/text-streams - Archive of obsolete content
experimental provides streams for reading and writing text. function readtextfromfile(filename) { var fileio = require("sdk/io/file"); var text = null; if (fileio.exists(filename)) { var textreader = fileio.open(filename, "r"); if (!textreader.closed) { text = textreader.read(); textreader.close(); } } re
turn text; } function writetexttofile(text, filename) { var fileio = require("sdk/io/file"); var textwriter = fileio.open(filename, "w"); if (!textwriter.closed) { textwriter.write(text); textwriter.close(); } } globals constructors textreader(inputstream, charset) creates a buffered input stream that reads text from a backing stream using a given text encoding. you can also create textreader objects using io/file's open() function. ...
...an nsioutputstream. it must already be opened. charset : string text will be written to outputstream using the character encoding named by this value. if not specified, "utf-8" is assumed. see nsicharsetconvertermanager.idl for documentation on how to determine other valid values for this. textreader methods close() closes both the stream and its backing stream. read(numchars) reads and re
turns a string from the stream. if the stream is closed, an exception is thrown. parameters numchars : number the number of characters to read. if not given, the remainder of the stream is read. re
turns string : the string read. if the stream is at the end, the empty string is re
turned. properties closed true if the stream is closed. textwriter methods close() flushes the backing stream's ...
loader/sandbox - Archive of obsolete content
box that inherits principals from source. parameters source : string|window|null an object that determines the privileges that will be given to the sandbox. this argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges. re
turns sandbox : a sandbox in which you can evaluate and load javascript. evaluate(sandbox, code, uri, line, version) evaluate code in sandbox, and re
turn the result. parameters sandbox : sandbox the sandbox to use. code : string the code to execute. uri : string evaluate the code as if it were being loaded from the given uri. optional. line : number evaluate the code starting at this line.
...valuate code in sandbox, and re
turn the result. parameters sandbox : sandbox the sandbox to use. code : string the code to execute. uri : string evaluate the code as if it were being loaded from the given uri. optional. line : number evaluate the code starting at this line. optional, defaults to 1. version : string evaluate the code using this version of javascript. defaults to 1.8. re
turns result : re
turns whatever the evaluated code re
turns. load(sandbox, uri) evaluate code from uri in sandbox. parameters sandbox : sandbox the sandbox to use. uri : string the url pointing to the script to load. it must be a local chrome:, resource:, file: or data: url. re
turns result : re
turns whatever the evaluated code re
turns. ...
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 re
turns 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 re
turn 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://mo...
... ...
system/xul-app - Archive of obsolete content
rimental information about the application on which your add-on is running. with the exception of ids, each of these properties exposes the attribute of the same name on the nsixulappinfo interface. for more information, see the mdn documentation. globals functions is(name) checks whether the host application is the given application. parameters name : string a host application name. re
turns boolean : true if the host application is name and false otherwise. isoneof(names) checks whether the host application is one of the given applications. parameters names : array an array of host application names. re
turns boolean : true if the host application is one of the names and false otherwise. versioninrange(version, lowinclusive, highexclusive) compares a given version to a ver...
..., highexclusive) compares a given version to a version range. see the mdn documentation for details on version comparisons. parameters version : string the version to compare. lowinclusive : string the lower bound of the version range to compare. the range includes this bound. highexclusive : string the upper bound of the version range to compare. the range does not include this bound. re
turns boolean : true if version falls in the given range and false otherwise. properties id the guid of the host application. for example, for firefox this value is "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}". name the host application name. the possible values here are: "firefox" "fennec" "mozilla" "seamonkey" "sunbird" "thunderbird" "firefox"and"fennec"` are the most commonly used value...
test/assert - Archive of obsolete content
the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected exception. this method takes an optional error argument: to check that the exception thrown is of the expected type, pass a constructor function: the exception thrown must be an instance of the object re
turned by that function. to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thrown must match the regular expression for example, suppose we define two different custom exceptions: function myerror(message) { this.name = "myerror"; this.message = message || "default message"; } myerror.prototype = new er...
... message : string optional message to log, providing extra information about the test. ...
util/object - Archive of obsolete content
= { "type": "addon" }; var d = {}; object.defineproperty(d, "name", { value: "jetpacks", configurable: false }); merge(c, d); var props = object.getownpropertydescriptor(c, "name"); console.log(props.configurable); // true parameters source : object the object that other properties are merged into. arguments : object n amount of additional objects that are merged into source object. re
turns object : the source object. extend(arguments) re
turns an object that inherits from the first argument and contains all of the properties from all following arguments, with precedence from right to left. extend(source1, source2, source3) is the equivalent of merge(object.create(source1), source2, source3). let { extend } = require("sdk/util/object"); var a = { alpha: "a" }; var b = { beta: "...
... ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
ith the content scripts your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. to send a message from one side to the other, sender calls port.emit() and receiver listens using port.on(). in the content script, port is a property of the global self object. in the add-on script, tab.attach() re
turns a worker object containing the port property you use to send messages to the content script. let's rewrite the example above to pass a message from the add-on to the content script. the content script now needs to look like this: // "self" is a global object in content scripts // listen for a "drawborder" self.port.on("drawborder", function(color) { document.body.style.border = "5px solid ...
...the example above to pass a message from the add-on to the content script. ...
Drag & Drop - Archive of obsolete content
rg/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris = new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) re
turn; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("application/x-moz-file"); for (var i=0; i<dragsession.numdropitems; i++) { var uri = null; dragsession.getdata(trans, i); ...
...the _dragdrop function retrieves the file uri data from the drag session and creates an array of file uris that the xul application can use. ...
JS XPCOM - Archive of obsolete content
ows you to use the methods in the nsiprefbranch2 interface. determining which interfaces an xpcom component supports to display a list of all interfaces that an xpcom component supports, do the following: // |c| is the xpcom component instance for each (i in components.interfaces) { if (c instanceof i) { alert(i); } } in this context, instanceof is the same as queryinterface except that it re
turns false instead of throwing an exception when |c| doesn't support interface |i|. another difference is that queryinterface re
turns an object, where as instanceof re
turns a boolean. xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm. components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource...
...resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); const cc = components.classes; const ci = components.interfaces; function abouthandler() {} abouthandler.prototype = { newchannel: function(uri) { var channel = services.io.newchannel("chrome://mystuff/content/mystuff.xul", null, null); channel.originaluri = uri; re
turn channel; }, geturiflags: function(uri) { // do not re
turn ci.nsiaboutmodule.uri_safe_for_untrusted_content unless // you make sure to set a non-system principal in newchannel. re
turn 0; }, classdescription: "about mystuff page", classid: components.id("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), contractid: "@mozilla.org/network/protocol/about;1?what=m...
Windows - Archive of obsolete content
the simplest way to do that is to use nsiwindowmediator. ...
...ses it. if it doesn't, it opens one. var wenum = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher) .getwindowenumerator(); var index = 1; var windowname = "yourwindowname"; while (wenum.hasmoreelements()) { var win = wenum.getnext(); if (win.name == windowname) { win.focus(); re
turn; } index++ } window.open("chrome://to/your/window.xul", windowname, "features"); uniquely identifying dom windows requires gecko 2.0(firefox 4 / thunderbird 3.3 / seamonkey 2.1) in gecko, each dom window has a unique 64-bit id number. you can get a dom window's id using the nsidomwindowutils attribute outerwindowid. each time a new window is created, it gets assigned an id one greater...
xml:base support in old browsers - Archive of obsolete content
s an absolute url, it should be from the host only link = loc.protocol + '//' + loc.host + link; } else { // if link is relative, it should be from full path, minus the file var dirpath = loc.pathname.substring(0, loc.pathname.lastindexof('/')-1); if (link.lastindexof('/') !== link.length-1) { link += '/'; } link = loc.protocol + '//' + loc.host + dirpath + link; } } re
turn link; } function getxmlbase (thisitem) { // fix: need to keep going up the chain if still a relative url!!!!! // var ns = 'http://www.w3.org/xml/1998/namespace'; var att, protocolpos; var xmlbase = ''; var abs = false; // avoid loop if node is not present if (!thisitem || !thisitem.nodename) { re
turn xmlbase; } // check present element and higher up for xml:base // now check for the n...
...he full uri here' break; } else if (att.indexof('/') === 0) { // if absolute (/), need to prepare for next time to strip out after slash xmlbase = att + xmlbase; abs = true; // once the protocol is found on the next round, make sure any extra path is ignored } else { // if relative, just add it xmlbase = att + xmlbase; } } thisitem = thisitem.parentnode; } //re
turn (xmlbase === '') ? null : xmlbase; re
turn xmlbase; } ...
Enhanced Extension Installation - Archive of obsolete content
an item is installed from a file (such as, when an item is installed from the web, via xpinstall, upgraded by xpinstall or dropped into a directory-based install location), the install manifest supplied by the item is expanded into a temporary location and read. the guid and version supplied are validated, and then compatibility is checked for by the new _getinstalldata function. this function re
turns the guid, version, and type of the item, and also an error code listing either success, or the reason for a failure, such as invalid guid, version, or incompatible item. depending on the failure, the install function may take several steps. if the item is found incompatible, a version update check is performed as before. if updated compatibility information is found this is written into the in-...
...pplying this updated install manifest as the source for _getinstalldata. if the item is determined compatible by either of the above processes, a copy of the item's file is staged into the install location directory under a hierarchy like so: <staged-xpis>/guid/foo.xpi (where foo.xpi is the original file name of the file) since xpinstall cleans up the file it supplies when the install function re
turns. if the item is a theme, we perform the installation immediately (thanks to benjamin smedberg's chrome registry changes this operation is now so simple that it can be performed by a function on the extensionmanager, rather than creating a separate object). if the item is an extension, we add it to the extension container and set the same set of initial setup properties on it that we used to, wi...
Extension Versioning, Update and Compatibility - Archive of obsolete content
t * in a version represents any version. the * actually represents an infinitely high number and so is really only sensibly used in the maxversion. using it in a minversion usually doesn't produce the effect you want. valid application versions automatic add-on update checking applications will periodically check for updates to installed add-ons by retrieving the updateurl. the information re
turned can be used to notify the user of an updated version to the add-on as well as inform the application of new application versions that the add-on is compatible with. note: starting in gecko 2.0, the automatic add-on update process properly supports cases in which the add-on's guid changes by uninstalling the old version and then installing the new one. previously, it was possible to wind up wi...
..., and the entry's targetapplication entry specifies a larger maxversion then the application will use this value instead of that specified in the add-on's install.rdf. this can cause add-ons that are disabled for being incompatible to become enabled and add-ons that would normally not install to be installed. update rdf format if you host your add-on's updateurl yourself then you will need to re
turn the add-on version information in an rdf format. below is an example update manifest. it lists information about 2 different versions of the extension with id foobar@developer.mozilla.org. the versions included are 2.2 and 2.5, both of which specify compatibility with firefox versions 1.5 to 2.0.0.*. for version 2.2 an https update link is used while version 2.5 has a regular http link with a has...
Jetpack Processes - Archive of obsolete content
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 re
turns an array whose elements are the re
turn values of each receiver in the chrome process that was triggered by the message. registerreceiver(amessagename, areceiver) similar to nsijetpack.registerreceiver(), this function registers a callback that is triggered when the chrome process sends a message with the given name. unregisterreceiver(amessagename, areceiver) similar to nsijetpack.unregisterrece...
...eiver(amessagename, areceiver) similar to nsijetpack.unregisterreceiver(), this function unregisters a callback previously registered with registerreceiver(). unregisterreceivers(amessagename) similar to nsijetpack.unregisterreceivers(), this function unregisters all callbacks for the given message name. createhandle() similar to nsijetpack.createhandle(), this function creates a new handle and re
turns it. createsandbox() this creates a new javascript sandbox and re
turns its global scope. this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties. evalinsandbox(asandbox, ascript) evaluates the given script contents in the given sandbox's global scope. at...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
use of it, is a “use” in a much weaker sense of the word. as far as the author is concerned, this is an unrelated application of the work. this is what we might call the reader’s use of the work, and it requires no permission from the author. in some situations, such as education or citation, use in the strong, authorial sense is permitted to readers. any discussion of copyright eventually
turns to the fact that some uses are prohibited, so it’s useful to understand what uses are unrestricted. range of uses restricted to author unrestricted book print, publish, revise read music record, perform, revise listen movie distribute, screen, revise watch software copy, distribute, modify execute licenses ar...
...from server to client). distributing software would be selling that cd-r or publishing the software on the internet. modifying software would be changing its functionality or adding new functions. duplication: copying a piece of software distribution: passing a piece of software to another person modification: modifying the software a typical software license will grant these permissions in re
turn for a fee, and will still restrict some normally unrestricted uses. the software that microsoft sells, such as windows, comes with a license that permits only limited duplication in exchange for a fee, so, although customers can install it on their computers, they cannot modify it. and essential freedoms, such as reverse-engineering, are also restricted. this use permit is displayed when you ins...
Appendix D: Loading Scripts - Archive of obsolete content
ific state data that they require. examples the following code will import a module into the current global scope. all variables named in the target script's exported_symbols global array will be copied into the current execution context. ...
...it will also import the symbol services from the standard services.jsm module. ...
Intercepting Page Loads - Archive of obsolete content
entpolicy and register it to the "content-policy" category using the nsicategorymanager. the nsicontentpolicy.shouldload() method is the only one in this interface that is really useful. it actually allows for cleaner-looking code than most of the previously seen solutions, because you get the content uri directly as an argument, and you indicate if the content should be loaded or not with the re
turn value, which has well-defined possible values. the context parameter gives you access to the window loading the content. as with all other solutions, you need to be efficient, and a good way to do this is to filter out unneeded cases right from the start. shouldload is called for every load operation firefox tries to do, including images, scripts and xul documents. a good filter would look like ...
...acontentlocation, arequestorigin, acontext, amimetypeguess, aextra) { let result = components.interfaces.nsicontentpolicy.accept; // we should check for type_subdocument as well if we want frames. if ((components.interfaces.nsicontentpolicy.type_document == acontenttype) && some_regular_expression.test(acontentlocation.spec)) { // do stuff here, possibly changing result. } re
turn result; } the content policy is applied very early in the process, even before the request is made, allowing a very clean cancel operation. this characteristic brings 2 limitations to this approach. the first one is that you can't easily read or modify the content to be loaded. the second one is that shouldload is not invoked for redirects. you only get one call, for the first url requested. if...
Local Storage - Archive of obsolete content
ectory with the name of your project at the root of the profile folder, and keep your files inside. the structure could be something like this: s435l.default (your profile directory) xulschool log.txt somedbfile.sqlite the directory service and the nsifile interface are used to create the local directory. here's what we usually do: we have a function that re
turns a reference to our root directory and creates it if necessary. getlocaldirectory : function() { let directoryservice = cc["@mozilla.org/file/directory_service;1"]. getservice(ci.nsiproperties); // this is a reference to the profile dir (profd) now. let localdir = directoryservice.get("profd", ci.nsifile); localdir.append("xulschool"); if (!localdir.exists() || !localdir.is...
...ctory_service;1"]. getservice(ci.nsiproperties); // this is a reference to the profile dir (profd) now. let localdir = directoryservice.get("profd", ci.nsifile); localdir.append("xulschool"); if (!localdir.exists() || !localdir.isdirectory()) { // read and write permissions to owner and group, read-only for others. localdir.create(ci.nsifile.directory_type, 0774); } re
turn localdir; }, profd is a special identifier for the profile directory that exists so that you don't need to figure out its location. in general this is the only directory flag you'll need, but sometimes you'll need access to other system directories, and you don't want to have to worry about which operating system or system language your extension is running on. a full list of these flags can be...
Search Extension Tutorial (Draft) - Archive of obsolete content
erprefs.clearuserpref(name); } function startup(data, reason) { firstrun = reason == addon_install; // change the default engine name. // an engine with this name must already exist. setpref("browser.search.defaultenginename", "example engine", true); } function shutdown(data, reason) { // no need to do this if this is app shutdown. if (reason == app_shutdown) re
turn; // reset our changes if the values have not been changed // in the meantime. for (let [name, [origvalue, value]] in iterator(savedprefs)) { if (defaultprefs.getcharpref(name) == value) defaultprefs.setcharpref(name, origvalue); } } function install() {} function uninstall() {} changing the default search engine this change comes in two parts: 1) installing ...
...lect the search engine. var selectsearch = false; function removeobserver() { try { services.obs.removeobserver(searchobserver, engine_added); } // if we've already removed this observer, ignore the error. catch (e) {} } // observer called after our engine has been successfully added function searchobserver(engine, topic, data) { if (data != "engine-added") re
turn; engine.queryinterface(ci.nsisearchengine); if (engine.name == engine_details.name) { // remove our observer now that we're done with it. removeobserver(); // if the engine is not hidden and this is the first run, move // it to the first position in the engine list and select it if (selectsearch && !engine.hidden) { services.search.mov...
Creating a Web based tone generator - Archive of obsolete content
setinterval(function() { var written; // check if some data was not written in previous attempts. if(tail) { written = audio.mozwriteaudio(tail); currentwriteposition += written; if(written < tail.length) { // not all the data was written, saving the tail... tail = tail.subarray(written); re
turn; // ... and exit the function. } tail = null; } // check if we need add some data to the audio output. var currentposition = audio.mozcurrentsampleoffset(); var available = currentposition + prebuffersize - currentwriteposition; if(available > 0) { // request some sound data from the callback function. ...
... // not all the data was written, saving the tail. tail = sounddata.slice(written); } currentwriteposition += written; } }, 100); } // control and generate the sound. ...
Drag and Drop - Archive of obsolete content
the item being dragged should be moved to its dropped location. nsidragservice.dragdrop_action_link a link (or shortcut or alias) to the item being dragged should be created in the dropped location. the interface nsidragservice also provides the function getcurrentsession which can be called from within the drag event handlers to get and modify the state of the drag. the function re
turns an object that implements nsidragsession. the interface nsidragsession is used to get and set properties of the drag that is currently occuring. the following properties and methods are available: candrop set this property to true if the element the mouse is currently over can accept the object currently being dragged to be dropped on it. set the value to false if it doesn't make sense to ...
...onstants described earlier. this can be used to provide extra feedback to the user. numdropitems the number of items being dragged. for example, this will be set to 5 if five bookmarks are being dragged. getdata(transfer,index) get the data being dragged. the first argument should be an nsitransferable object to hold the data. the second argument, index, should be the index of the item to re
turn. sourcedocument the document where the drag started. sourcenode the dom node where the drag started. isdataflavorsupported(flavor) re
turns true if the data being dragged contains data of the specified flavor. next » original document information author(s): neil deakin original document: copyright information: copyright (c) neil deakin ...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
in order to commun...
... file = libxulpath; if (aprop.equals("comsd")) { file = new file(file, "components"); } } re
turn file; } public file[] getfiles(string aprop) { file[] files = null; if (aprop.equals("apluginsdl")) { files = new file[1]; files[0] = new file(libxulpath, "plugins"); } re
turn files; } } calling xpcom ui from another thread appstartup.run() enters the main event loop and will stay there until the application exits. in order to communicate with xpcom after this point, you should use an nsiproxyobjectmanager. following on from the above example, to create a new window, we would do the following: // first, get the event queue service. this handles all event que...
Code snippets - Archive of obsolete content
ry[0]; // load the tab via the tabbed browser api. ...
...as the handler. navigate to "downloads", pick correct file. watch live sync logs set services.sync.log.appender.console to trace. ...
Creating a Help Content Pack - Archive of obsolete content
ewer ui may or may not provide a panel for each of these data sources. in firefox 1.0 each data source had a panel. starting with firefox 1.1 and the mozilla 1.8 platform, only the table of contents data source will be displayed. the glossary and index data sources will be hidden - information found only in them will not be displayed unless the user conducts a search of the help pack that would re
turn glossary or index results.xxx this sentence is ugly - a little rewording help here would be nice a data source description is pretty much the same no matter which type you're defining, and the syntax is pretty simple. each panel is specified by one rdf:description element with the following attributes: nc:panelid specifies the name of the panel, which may be any one of glossary, search, toc, ...
....html"/> </rdf:li> nc:panelid should be set to search. nc:datasources should be set as with table of contents, index, and glossary definitions. nc:platform (added in mozilla 1.8b2/firefox 1.1) may be used on search data sources as it's used on table of contents, index, and glossary definitions. nc:emptysearchtext specifies the text that is shown when a search through help re
turns no results. nc:emptysearchlink specifies what uri should be shown when the pseudo-result "no results found" is accessed. this attribute is required. the sample page chrome://help/locale/welcome.xhtml has a section on searching which may be a useful link to use here. note that you can use the nc:datasources attribute to inherit content from other content packs. one common use of this is to inh...
importUserCertificates - Archive of obsolete content
12). the importusercertificates() method is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. ...
...ewly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. the request id in the response being imported must match the request id in the associated certification request or recovery request. if the import operation succeeds, an empty string will be re
turned. ...
Clipboard - Archive of obsolete content
vor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)re
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. flavorre
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var my...
...rns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()re
turns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" );var flavs = jetpack.clipboard.getclipboardflavors();// should equal ["html", "text"]console.log( flavs ); ...
Clipboard - Archive of obsolete content
of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)re
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. flavorre
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var my...
... data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()re
turns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); var flavs = jetpack.clipboard.getclipboardflavors(); // should equal ["html", "text"] console.log( flavs ); ...
Clipboard - Archive of obsolete content
of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)re
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. flavorre
turns data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var my...
... data to jetpack from the clipboard. if flavor is provided, the data is re
turned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()re
turns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); var flavs = jetpack.clipboard.getclipboardflavors(); // should equal ["html", "text"] console.log( flavs ); ...
Mozilla Crypto FAQ - Archive of obsolete content
is form of licensing was chosen to allow the released personal security manager and network security services source code to be used in as many contexts as possible; for example, the psm and nss code can be used in mozilla under mpl terms, and can also be used in gnu and other projects under gpl terms. if you create and distribute modifications to the original psm and nss code, we ask that you in
turn make such modifications available under both the mpl and gpl. (note that mozilla.org will not accept contributed modifications into future psm/nss source releases unless they are so licensed.) for more information see the mozilla public license and the gnu general public license. specific questions about licensing of the psm and nss source code should be directed to the netscape.public.mozilla.l...
...regulations were not yet in effect with respect to encryption software.) bernstein claimed that the u.s. export regulations were in essence a licensing scheme designed to impede or prohibit certain types of speech (e.g., publishing cryptographic source code in electronic form), and were therefore unconstitutional under the first amendment to the u.s. constitution. the u.s. government claimed in re
turn that cryptographic software was regulated based solely on its ability to be used to secure communications and data, and that the national security interest in so regulating it overrode any first amendment protections; as the export regulations put it, "encryption software is controlled because of its functional capacity, and not because of any informational value of such software". the government...
Frequently Asked Questions - Archive of obsolete content
rates the bug. if you have any problems with the bug database feel free to contact contact us. can i use a plugin for svg instead of mozilla's native support? individuals can choose to use a plugin to view svg in mozilla on their own computers, but there is no way for svg content authors to make mozilla use a plugin when people view the svg files on their website. the native svg support must be
turned off before mozilla will look to see if there's an svg plugin installed. this is done by toggling a hidden user configuration preference (pref). to access the pref type about:config into the url bar, then type svg.enabled into the filter field. when you double click on the pref you will see its value change to and from true/false,
turning the native support on/off. how does mozilla's svg implem...
...ou should still feel free to ask us friendly questions and give us constructive feedback. who's currently working on what? other than reviewing patches and fixing the occassional bug, alex is currently taking a break from active svg development to concentrate on 'real work' and cool stuff like xtf and jssh. tim is working on implementing <filter> and working on items that need to be done before
turning on svg by default. after recently implementing gradients, scooter is working on fixing some issues that remain outstanding and fixing <switch>. jonathan is working on various bugs, especially those that need to be fixed before svg can be enabled in the official builds. david continues to create svg enabled nightlies and answer build related questions as he has done for some time. finally, occa...
Space Manager High Level Design - Archive of obsolete content
previous space manager is saved off. the new space manager instance is associated with the blockreflowstate. after the block frame's reflow has completed, the old space manager instance is re-associated with the blockreflowstate the new space manager is destroyed. if the blockreflowstate already had a space manager instance associated with it, it is stored off before being replaced, and the re
turned to the blockreflowstate instance after the new one has been destroyed. thus, space managers are effectively 'nested' during reflow, with each new block introducing its own space manager. use case 2: float is added to the space manager after a space manager is created for a block context's reflow chain, a floated block may be added to it. this happens in the method nsblockreflowstate::recover...
...blockreflowstate calls getavailablespace on its blockbanddata instance (which was setup in the blockreflowstate's constructor based on the space manager passed in and computed content area). blockbanddata then gets the band data from the space manager via a call to the space manager associated with the blockbanddata instance. the blockbanddata then walks the collection of trapezoids that were re
turned by the spacemanager method getbanddata (as nsbanddata wrappers) and determines the right-most edge of the available space. the blockreflowstate then stores this available space rect for use in the rest of the reflow chain. use case 4: propagation of float damage: detecting and handling float damage this process is driven by the block frame. a non-dirty line is encountered by the block fra...
Using gdb on wimpy computers - Archive of obsolete content
ike libc and pthreads are loaded before you tell gdb to stop loading shared libraries. if you don't allow those libraries to be loaded then gdb will not be able to properly debug threads on linux. mozilla uses pthreads for its networking library so you need to be able to work in a threaded environment. the best way to do this is to set a breakpoint in main, let the program run until main and then
turn off automatic library loading. from there you can allow the program to continue running. here's an example: [blizzard@gunhead mozilla]$ cd dist/bin/ [blizzard@gunhead bin]$ ./mozilla -g .//run-mozilla.sh -g ./mozilla-bin mozilla_five_home=/home/blizzard/src/mozilla/mozilla/dist/bin ld_library_path=/home/blizzard/src/mozilla/mozilla/dist/bin shlib_path=/home/blizzard/src/mozilla/mozilla/d...
...stallunixsignalhandlers(argv[0]); (gdb) set auto-solib-add 0 (gdb) c continuing. nsnativecomponentloader: autoregistering begins. [...] it's easy to define a function for gdb to do this for you automatically. you can add this function to the .gdbinit file in your home directory: def prun tbreak main run set auto-solib-add 0 end how do i load shared libraries? if you have
turned off automatic shared library loading, you will have to load them when you need them. gdb has a command to load libraries while the program is running. this is the sharedlibrary command. it can be shortened to shar when used in gdb. the argument to the command is a regular expression for the libraries to be loaded. here's what it looks like in the 4.18 version of the debugger: ^c program receive...
Anonymous Content - Archive of obsolete content
tent is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. the scope of an element can be determined using the getbindingparent method on the documentxbl interface. see section 3 for more information. this method re
turns the bound element in the enclosing scope that is responsible for the anonymous node. if invoked on an element at the document-level scope, it re
turns null. dom methods that can be invoked on elements (e.g., getelementsbytagname) will only see nodes that are in the same scope. methods invoked on the document (e.g., getelementbyid) only see nodes that are at the document-level scope. content gen...
...e event will be stopped before it reaches the bound element. in html4 the tabindex attribute can be used to specify the tab order for focusable elements. this attribute can be specified on anonymous content. each scope has a unique tab order. the tabindex values used in one scope are ignored by other scopes. as an example, consider the html file upload control. it is a focusable element that in
turn is made up of two focusable anonymous elements: a textfield and a button. tab indices can be specified on the textfield and the button to dictate the order in which the components of the file control should be accessed when tabbing. when the user tabs such that the file control should become focused, the user agent determines if any anonymous content should also become focused, using the tab ord...
Binding Implementations - Archive of obsolete content
n the element. a method with parameters specifies those parameters and their names with parameter elements declared underneath the method element. the implementation of the method is contained inside a body element. the parameters specified are bound to their names in the method body. <method name="scrolltoindex"> <parameter name="index"/> <body> <![cdata[ if (index < 0) re
turn; ... ]]> </body> </method> properties properties can also be defined on the bound element using property tags. there are two basic types of properties. the first type of property is a raw value that is set directly on the element itself. the second type of property is one that defines functions that are invoked when the property is either retrieved or set. these functions are calle...
...dingattached handler needs to be able to assume that all properties will be accessible on the binding. properties with getters and setters can define them using onget and onset attributes, or using the more verbose getter and setter elements. if both the attribute form and the element form are used to specify a getter or setter, then the element form is ignored. a getter contains script whose re
turn value is handed back when the property is requested. a setter contains a script that is invoked when a new value is assigned to the property. in script, the word val is used to represent the new value. properties can be designated as constant using the readonly attribute. when set to true, the property's value cannot be altered. if a property is readonly and a setter is defined, then the setter ...
Elements - Archive of obsolete content
access to anonymous nodes generated by the binding is already possible. the constructor tag must be placed inside the implementation tag. id - the id attribute is a document-unique identifier. note: prior to firefox 3, the constructor could be called at a time when reflow of the document layout was locked down, so that attempting to get layout information from within the constructor could re
turn out of date information. in firefox 3 and later, the constructor is called when reflow can take place, which results in up-to-date information being re
turned. see bug 398404 for details. note: all properties of the binding are "imported" as local variables in a constructor's scope. see bug 407314 for more details. destructor the code inside the destructor is called when a binding is being rem...
... attribute is used to designate a property as read-only. if set to true, the value of the property cannot be altered. if this attribute is omitted, the property will be readable and writable. onget - the onget attribute's value is a script that executes when the value of the property is requested. if this attribute is set, any initial value contained underneath the element will be ignored. the re
turn value of the script represents the value of the property that will be re
turned to the requestor. a property getter can also be specified as a child of the property element using the getter tag. onset - the onset attribute's value is a script that executes when the value of the property is being altered. if this attribute is set, any initial value contained underneath the element will be ignored.
dirCreate - Archive of obsolete content
description the input parameter is a filespecobject that you have already created with the install object's getfolder method. ...
...description the input parameter is a filespecobject that you have already created with the install object's getfolder method. ...
dirGetParent - Archive of obsolete content
dirgetparent re
turns an object representing the parent directory of the current directory or file. method of file object syntax filespecobject dirgetparent( filespecobject fileordir ); parameters the dirgetparent method has the following parameters: fileordir a filespecobject representing the pathname of the file or directory whose parent is being requested. re
turns a filespecobject if successful; null if not successful. ...
...tparent( filespecobject fileordir ); parameters the dirgetparent method has the following parameters: fileordir a filespecobject representing the pathname of the file or directory whose parent is being requested. re
turns a filespecobject if successful; null if not successful. example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // re
turns "program" ...
diskSpaceAvailable - Archive of obsolete content
description use this function to make sure there is adequate space on the local disk for extracting and installing your files (see example below). ...
...description use this function to make sure there is adequate space on the local disk for extracting and installing your files (see example below). you can use a string representing any file on the disk you want to check, and xpinstall will resolve the reference to the partition itself. ...
modDate - Archive of obsolete content
example f = getfolder("program"); filesource = getfolder(f, "myfile.txt"); err = file.moddate(filesource); see moddatechanged for an example of comparing the dates of two files. ...
... example f = getfolder("program"); filesource = getfolder(f, "myfile.txt"); err = file.moddate(filesource); see moddatechanged for an example of comparing the dates of two files. ...
compareTo - Archive of obsolete content
; compareto ( int major, int minor, int release, int build); parameters the compareto method has the following parameters: maj the major version number. min minor version number. rev revision number. bld build number. version an installversion object or a string representing version information in the format "4.1.2.1234". re
turns if the versions are the same, this method re
turns 0. if this version object represents a smaller (earlier) version than that represented by the version parameter, this method re
turns a negative number. otherwise, it re
turns a positive number. in particular, this method re
turns one of the following values: -4 this version object has a smaller (earlier) major number than version. ...
...his version object has a larger (newer) build number than version. 2 this version object has a larger (newer) release number than version. 3 this version object has a larger (newer) minor number than version. 4 this version object has a larger (newer) major number than version. ...
getComponentFolder - Archive of obsolete content
getcomponentfolder re
turns an object representing the directory in which a component is installed. method of install object syntax object getcomponentfolder (string registryname); object getcomponentfolder ( string registryname, string subdirectory); parameters the getcomponentfolder method has these parameters: registryname the pathname in the client version registry for the component whose installation directory is to be obtained. subdirectory a string that specifies the name of a subdirectory. if the specified subdirectory doesn't exist, it is created. this parameter is available in netscape 6 and may be case sensitive (depending on the operating system). ...
...e parameters: registryname the pathname in the client version registry for the component whose installation directory is to be obtained. subdirectory a string that specifies the name of a subdirectory. if the specified subdirectory doesn't exist, it is created. this parameter is available in netscape 6 and may be case sensitive (depending on the operating system). re
turns an object representing the directory in which the component is installed, or null if the component could not be found or if subdirectory refers to a file that already exists. description the getcomponentfolder method to find the location of a previously installed software package. typically, you use this method with the addfile method or the adddirectory method. ...
getFolder - Archive of obsolete content
method of install object syntax filespecobject getfolder ( string foldername); filespecobject getfolder ( string foldername, string subdirectory); filespecobject getfolder ( object localdirspec, string subdirectory); parameters the getfolder method has the following parameters: foldername a string representing one of netscape's standard directories. there are two sets of possible values for this parameter. the first set contains platform-independent locations; the second set contains platform-specific locations. you are encouraged to use the platform-independent locations. see the list in the description section for the two sets of locations. ...
...r the two sets of locations. subdirectory a string that specifies the name of a subdirectory. if the specified subdirectory doesn't exist, it is created. this parameter is available in netscape 6 or later and may be case sensitive (depending on the operating system). localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. re
turns a filespecobject representing one of netscape's standard directories, or null in case of error or if subdirectory refers to a file that already exists. description the getfolder method obtains an object representing one of netscape's standard directories, for use with the addfile and getwinprofile methods. the value of foldername must be one of the following (info is based on mozilla 1.7 stabl...
patch - Archive of obsolete content
ect by passing a string representing the directory to the getfolder method. relativelocalpath a pathname relative to the localdirspec parameter that identifies the subcomponent that is to be patched. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. re
turns an integer error code. for a list of possible values, see re
turn codes. description the patch method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum ...
...t of possible values, see re
turn codes. description the patch method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum stored in the gdiff file, patch re
turns an error without applying the patch. after patch applies a patch, it compares a checksum.of the resulting file against a checksum stored in the gdiff file. if the checksums do not match, the original version of the file is preserved, the patched version of the file is discarded, and an error code is re
turned. any single installation process can apply multiple patches to the same file. if perfo...
selectedIndex - Archive of obsolete content
« xul reference selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. ...
... « xul reference selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. ...
Introduction - Archive of obsolete content
some other systems call this databinding. effectively, xul templates are the xul way of doing databinding. each template retrieves its data from a datasource. ...
...some other systems call this databinding. effectively, xul templates are the xul way of doing databinding. each template retrieves its data from a datasource. ...
Rule Compilation - Archive of obsolete content
« previousnext » query a xul template is made up of a query and a series of rules. a query contains instructions for how to retrieve a set of data from the datasource. the exact syntax is dependent on the type of datasource used in the template. for instance, for an sqlite datasource, an sql statement is used as the query. this will re
turn a table of result records which are then used to generate output. for rdf and xml, the query contains a set of instructions for navigating through the rdf graph or xml document tree. a query is declared with the query tag (new to ff3; ff2 only worked with rdf datasources and had no query tag), which you would place directly inside the <template>. the job of the query is to generate a set of output results. rules the template also contains a ...
...u can still do that. changing the hidden state of an element isn't the only way to cause content to be generated. calling a dom api which needs to get at the generated content will cause the template builder to generate output. for example, just calling the code like the following on the hidden vbox above will start off the template builder. var length = vbox.childnodes.length; this request to re
turn the number of children of the vbox will make the template builder process the query and output content. once done, the correct length can be re
turned. all of this is transparent to the xul developer. when the template builder decides to start generation is determined automatically, and you don't need to do anything special to get this to happen. however, there are two cases where content is not g...
SQLite Templates - Archive of obsolete content
ent, as text inside the query element. this simple example shows how to display a listbox containing the values in one column in a database table. <listbox datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name from myfriends </query> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> the query re
turns the list of values from the 'name' column in the table 'myfriends'. the action body, starting at the node with uri="?" is repeated for each result re
turned from the query. if the query re
turns six results, six listitems will be generated. the labels have the special value '?name'. the syntax with the question mark is similar as with the other query types. it means, substitute the attribute value...
...six results, six listitems will be generated. the labels have the special value '?name'. the syntax with the question mark is similar as with the other query types. it means, substitute the attribute value with the value of a column from the result. in this case, '?name' means replace this with the value of the name column. the effect is a listbox containing the names from the database. you can re
turn multiple columns or filtered data by using a more complex query. <vbox datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name, email from myfriends where age >= 30 </query> <action> <hbox uri="?"> <label value="?name"/> <label value="?email"/> </hbox> </action> </template> </vbox> this template disp...
XML Templates - Archive of obsolete content
ame="napoleon bonaparte" gender="male"/> <person name="cleopatra" gender="female"/> <person name="julius caesar" gender="male"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> xml query syntax the query syntax is fairly simple for xml datasources. just place an expr attribute on the query element containing an xpath expression re
turns the set of results to output. here is an example: <listbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> the expr attribute is a very simple xpath expression which simply retrieves the person elements from within the datasource. as there are five in the xml do...
.../> <action> <hbox uri="?" align="center"> <button label="?name"/> <label value="?gender"/> </hbox> </action> </template> </vbox> note how two attributes are substituted here, the label on the button and the value on the label. the query does not have to be as simple as the one used here. any xpath expression may be used. for instance, the following query re
turns only those results for female people. <query expr="person[@gender='female']"/> as long as the expression re
turns one or more nodes, it can be used in an query expression. using inline xml it's also possible to embed the xml data directly within the xul document if desired. instead of using a url for the datasources attribute, you can use an anchor reference to refer to a node within the same d...
Additional Install Features - Archive of obsolete content
ist to move(), rename() and execute() files. thus, you can move files that might conflict with your package out of the way. handling errors you will likely want to handle errors gracefully. this will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlasterror() function to determine whether an error occured. if it re
turns success, no error occured. otherwise, the number will be an error code which indicates the type of error that occured. you can call this function at any point during the installation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort the installation. you may also want to display an error message to the user. for example, you...
...nstallation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort the installation. you may also want to display an error message to the user. for example, you might put the following as the last section of your script: if (getlasterror() == success) { performinstall(); } else { cancelinstall(); } error codes that could be re
turned by getlasterror() are listed in the mozilla source file nsinstall.h. during installation, a log file is created that contains the operations that are performed. it will also show any errors that occured. the log file can be found in the file 'install.log' in the mozilla installation directory. a block of text will be added to this file for each installation that occurs. the logcomment() functio...
More Menu Features - Archive of obsolete content
order to group a set of menu items together, you need to put a name attribute on each one to group. set the value to the same string. ...
... a set of menu items together, you need to put a name attribute on each one to group. set the value to the same string. ...
More Wizards - Archive of obsolete content
r each page. then, to navigate to a page, use one of two methods: set the next attribute on each page to the page id of the next page to go to. you can change these attributes as needed to navigate to different pages. call the wizard's goto() method. it takes one argument, the page id of a page to go to. you might call this method in the onpageadvanced or onwizardnext handlers. remember to re
turn false in this case, because you have already changed the page yourself. note that the goto() method, because it causes a page change, will fire the events again, so you'll have to make sure you handle that case. for example, here are a set of wizard pages (the inner content has been omitted): <wizardpage pageid="type" next="font"> <wizardpage pageid="font" next="done"> <wizardpage pageid="color...
...both properties are adjusted automatically as you switch pages. th...
Property Files - Archive of obsolete content
number of properties. the first is getstring which can be used in a script to read a string from the bundle. var strbundle = document.getelementbyid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file. the function getstring() re
turns the value of the string or null if the string does not exist. finally, the string is displayed in an alert box. text formatting the next method is getformattedstring(). this method also gets a string with the given key name from the bundle. in addition, each occurrence of formatting code (e.g. %s) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; va...
...laced different order in the array. formatting code %n$s is specify the position of corresponding parameter directly. although the word order is not the same in all the languages, by using getformattedstring() the specification of the order can be put out the property files. in case you need to format a string that already contains the percentage character in it (to get something like "50% off" re
turned), escape the percentage character with another percentage character, like this: my.percentage.string = %s%% off not escaping the percentage character will generate an incorrect string that strips the space character between the percentage character and the next word of the string ("50%off"). non-ascii characters, utf-8 and escaping gecko 1.8.x (or later) supports property files encoded in utf-...
Using the Editor from XUL - Archive of obsolete content
er. this only happens for situations where the nseditorshell is used (i.e. not for text widgets): nseditorshellmouselistener (as a nsidommouselistener) note: starting in gecko 12, the editor refuses any events sent by unprivileged content. nstexteditorkeylistener this event listener handles key presses for typing, and other editing operations (backspace, delete, enter/re
turn). cases that it does not handle explicitly it passes on to nshtmleditor::editorkeypress(), which is where normal typing keys end up. note that it only responds to the keypress event; keydown and keyup events are ignored. nstexteditormouselistener the mouse listener is used to do middle-mouse paste (which is a unix copy/paste feature). this happens in response to mouseclick with button 2. it als...
...shtmleditor::editorkeypress(). nshtmleditor::editorkeypress() gets the character code from the key event, puts that into a string, and calls nshtmleditor::typedtext(), which simply calls nshtmleditor::inserttext(). nshtmleditor::inserttext() hides quite a bit of complexity in some stack-based classes. nsautoplaceholderbatch is a utility class that wraps text insertion with calls to
turn off selection and layout updating (to avoid flicker), and the maintenance of a placeholder transaction. this placeholder transaction enables us to batch typing events together, so that an undo undoes the whole series of keystrokes. another stack-based class, nsautorules, ensures that text insertion is wrapped with calls to nshtmleditor::startoperation() / endoperation(). these functions call b...
colorpicker - Archive of obsolete content
this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. el...
...ing the type of accessibility object for the element. color type: color string the currently selected color. this is modified when the user selects a color. you can assign a string of the form #rrggbb to this property to change the selected color. disabled type: boolean gets and sets the value of the disabled attribute. open type: boolean re
turns true if the popup for a button-type colorpicker is open. set this property to true to open the popup or false to close the popup. tabindex type: integer gets and sets the value of the tabindex attribute. value property gets and sets color attribute methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispat...
deck - Archive of obsolete content
selectedpanel type: element holds a reference to the currently selected panel within a deck ele...
...ytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected do not hide panels; the deck element only understands visible panels. selectedpanel type: element holds a reference to the currently selected panel within a deck element. assigning a value to this property will modify the selected panel. inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed...
dialog - Archive of obsolete content
, insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata acceptdialog() re
turn type: no re
turn value accepts the dialog and closes it, similar to pressing the ok button. canceldialog() re
turn type: no re
turn value cancels the dialog and closes it, similar to pressing the cancel button. centerwindowonscreen() re
turn type: no re
turn value centers the dialog on the screen. getbutton( type ) re
turn type: button element re
turns the button element in the dialog...
...ar to pressing the ok button. canceldialog() re
turn type: no re
turn value cancels the dialog and closes it, similar to pressing the cancel button. centerwindowonscreen() re
turn type: no re
turn value centers the dialog on the screen. getbutton( type ) re
turn type: button element re
turns the button element in the dialog corresponding to the given type. movetoalertposition() re
turn type: no re
turn value moves and resizes the dialog to a position and size suitable for an alert box. related elements dialogheader ...
menuitem - Archive of obsolete content
ffect the contents displayed to the user. properties accessibletype type: integer a value indicating the type of accessibility object for the element. accesskey type: character gets and sets the value of the accesskey attribute. command type: element id gets and sets the value of the command attribute. control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu. crop type: string gets and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. image type: image url gets and sets the value of the image attribute. label type: ...
...ibute. label type: string gets and sets the value of the label attribute. labelelement type: label element the label element associated with the control. this is set when a label has a control attribute pointing to this element. this property will be null when no label is associated with the control. parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu. selected type: boolean this property's value is true if this element is selected, or false if it is not. this property is read only. this property is available for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex attr...
menuseparator - Archive of obsolete content
t the contents displayed to the user. properties accessibletype type: integer a value indicating the type of accessibility object for the element. accesskey type: character gets and sets the value of the accesskey attribute. command type: element id gets and sets the value of the command attribute. control type: menu element re
turns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu. crop type: string gets and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. image type: image url gets and sets the value of the image attribute. label ty...
...te. label type: string gets and sets the value of the label attribute. labelelement type: label element the label element associated with the control. this is set when a label has a control attribute pointing to this element. this property will be null when no label is associated with the control. parentcontainer type: menu element read only property that re
turns the containing menu element, or null if there isn't a containing menu. selected type: boolean this property's value is true if this element is selected, or false if it is not. this property is read only. this property is available for menuitem and menuseparator elements in firefox 3. tabindex type: integer gets and sets the value of the tabindex at...
prefpane - Archive of obsolete content
this property's value is true if this element is selected, or false if it is not. this property is read only. this property is available for menuitem and menuseparator elements in firefox 3. src type: url gets and sets the value of the src attribute. methods domelement getpreferenceelement(in domelement startelement) preferenceforelement( uielement ) re
turn type: preference element re
turns the preference element to which a user interface element is attached. void userchangedvalue(in domelement element); the user changed the value in a widget that the preferences system does not automatically track state changes for (1) and the preference element associated with the widget should be updated based on the state held by the widget.
...omatically track state changes for (1) and the preference element associated with the widget should be updated based on the state held by the widget. for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that re
turns the value to be written to the preference element, and then call the userchangedvalue function every time you edit the list in a way that should cause the preference's value to change. (1) an example of a widget that has state changes tracked for it includes the checkbox element, whose state is tracked automatically when the "command" event fires. void writepreferences(in boolean f...
promptBox - Archive of obsolete content
a tab may have multiple prompts on it; the tabmodalpromptshowing attribute on the tabbrowser will tell you how many prompts a given tab has. note: this is largely an implementation detail; if you're developing an add-on, you shouldn't need to tinker with this. you should use the window.alert() method or the nsiprompt interface instead. see using tab-modal prompts for details. ...
...ew nsidomelement appendprompt(args, onclosecallback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a new prompt, adding it to the tab. nsidomelement appendprompt( args, onclosecallback ); parameters args arguments for the prompt. onclosecallback the callback routine to be called when the prompt is closed. re
turn value an nsidomelement object representing the new prompt. removeprompt() removes an existing prompt. void removeprompt( nsidomelement aprompt ); parameters aprompt the prompt to dispose of. listprompts() re
turns a list of all the prompts on the tabbrowser. nodelist listprompts( nsidomelement aprompt ); parameters aprompt this parameter isn't used; i don't know why it's even there. ret...
tab - Archive of obsolete content
cts a menu item or presses a keyboard shortcut attached to the command. pending type: boolean this attribute is set to true if the tab is currently in the process of being restored by the session store service. once the tab is restored, this attribute is removed. you can determine if a tab is being restored by checking to see if hasattribute("pending") is true. if the user has
turned on the "don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. pinned type: boolean this attribute is set to true if the tab has been pinned (that is, if it's an app tab). the tabbrowser element's pintab and unpintab methods handle pinning and unpinning tabs. selected type: boolean this attribute is set to true if the tab is select...
...be loaded from the cache if possible. properties accesskey type: character gets and sets the value of the accesskey attribute. accessibletype type: integer a value indicating the type of accessibility object for the element. command type: element id gets and sets the value of the command attribute. control type: tabs element re
turns the enclosing tabs element. crop type: string gets and sets the value of the crop attribute. disabled type: boolean gets and sets the value of the disabled attribute. image type: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribut...
toolbar - Archive of obsolete content
er be the toolbox's parent (if it's in a toolbox), or, if the toolbar is an external toolbar (that is, one not contained in a toolbox), the id of the toolbox it should be considered to be part of. this makes it possible to have toolbars that are not contained within toolboxes, such as the add-on bar. methods insertitem( id, beforenode, wrapper, beforepermanent ) not in seamonkey 1.x re
turn type: element add an item with the given id to the toolbar. the new item is added just before the item given by the second argument. if the second argument is null, but the beforepermanent argument is true, the item is added to the beginning of the toolbar before the first permanent item. otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar. the th...
...o wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. some special ids may also be used to create special spacing items: separator: a separator, which is drawn as a vertical bar. spacer: a non-flexible space. spring: a flexible space. the method re
turns the dom element for the created item. inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getele...
window - Archive of obsolete content
in pixels for the top, right, bottom, and left edges of the window, respectively. this value may be -1 to use the default margin for that side on the current platform, 0 to have no system border (that is, to extend the client area to the edge of the window), or a value greater than zero to indicate how much less than the default default width you wish the margin on that side to be. ...
... disablefastfindtype: booleanput disablefastfind="true" on the root element of a xul document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. this is used to prevent the find bar from being displayed when it's not supported by the content (such as in the add-ons manager tab). ...
Dialogs in XULRunner - Archive of obsolete content
example xul dialog: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="mydialog" title="my dialog" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="window.sizetocontent();" buttons="accept,cancel" buttonlabelaccept="set favorite" buttonaccesskeyaccept="s" ondialogaccept="re
turn dosave();" buttonlabelcancel="cancel" buttonaccesskeycancel="n" ondialogcancel="re
turn docancel();"> <script> function dosave(){ //dosomething() re
turn true; } function docancel(){ re
turn true; } </script> <dialogheader title="my dialog" description="example dialog"/> <groupbox flex="1"> <caption label="select favorite fruit"/...
...that could change in future releases. firefox and thunderbird both support nearly native page setup and print dialogs. however, xul does support elements to make creating wizards a simple task as well. future articles in this...
Getting started with XULRunner - Archive of obsolete content
elds indicate the range of gecko versions your application is compatible with; make sure that you set them so that the version of xulrunner you're using is in that range, or your application won't work. note: make sure your application name is lowercase and longer than 3 characters step 5: set up the chrome manifest the chrome manifest file is used by xulrunner to define specific uris which in
turn are used to locate application resources. this will become clearer when we see how the “chrome://” uri is used. application chrome can be in a single or a few jar files or uncompressed as folders and files. i am using the uncompressed method for now. here is the chrome/chrome.manifest: content myapp content/ as mentioned in step 3, the default location of the chrome.manifest has changed i...
... this might also be simplified using a very simple shell script (i call mine "run.sh"): #!/bin/sh /library/frameworks/xul.framework/xulrunner-bin `pwd`/application.ini linux on ubuntu, you can run the application from a terminal. first change into the \myapp folder, then start the application by: xulrunner application.ini you should now see a window that looks something like this. thi...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
//ns_unix nsnull }; // component.dll on windows, libcomponent.dll on linux static char krealcomponent[] = moz_dll_prefix "mozldap" moz_dll_suffix; nsresult nsgetmodule(nsicomponentmanager* acompmgr, nsifile* alocation, nsimodule* *aresult) { nsresult rv; nscomptr<nsifile> libraries; rv = alocation->getparent(getter_addrefs(libraries)); if (ns_failed(rv)) re
turn rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) re
turn ns_error_unexpected; library->setnativeleafname(ns_literal_cstring("libraries")); library->appendnative(ns_literal_cstring("dummy")); // loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->set...
...dent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); prlibrary *lib; library->load(&lib); // 1) we don't care if this failed! // 2) we are going to leak this library. we don't care about that either. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) re
turn rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) re
turn ns_error_failure; re
turn getmoduleproc(acompmgr, alocation, aresult); } then change your .mozconfig to add this line: ac_add_options --enable-extensions=ldapstub rebuild xulrunner. this will create a new file in the components subdirectory of the b...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
after some experimentation, the following seems to be the best way to speak soap in xulrunner. several alternatives were considered: soapclient 2.4 - this library contains a few javascript mistakes but nevertheless seems (fairly) widely used, mature and tested. it requires servers to support wsdl which took it out of the running. xulrunner 1.8.* - using an old xulrunner is certainly an option but brings up a host of speed, stability and memory issues. ...
...er("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("soapaction", soapreq.action); < } < }); --- > var xhr = new xmlhttprequest(); > xhr.mozbackgroundrequest = true; > xhr.open('post', soapclient.proxy, true); > xhr.onreadystatechange = function() { > if (4 != xhr.readystate) { re
turn; } > getresponse(xhr); > }; > var headers = { > 'method': 'post', > 'content-type': soapclient.contenttype + '; charset="' + > soapclient.charset + '"', > 'content-length': soapclient.contentlength, > 'soapserver': soapclient.soapserver, > 'soapaction': soapreq.action > }; > for (var h in headers) { xhr.setrequestheader(h, headers[h]); } > xhr.send(cont...
application/http-index-format specification - Archive of obsolete content
mber is at least a three digit number (note that more digits are possible in the future) and data is separated from number by a colon and a space. the syntax of data is defined by the syntax spec for every number type. if a number is encountered that a parser does not understand the parser is required to ignore that line. there is no line length limit. all lines must be terminated by a carriage re
turn followed by a line feed. number codes 100 a human readable comment line. machine parsers should ignore this data. this data is not intended for display to the end user and is only meant as a comment to make the file format clear to a human interpreter. 101 pre formatted human readable information line. this data is intended for the end user of the file format data if there is one. this da...
...38. note that multiple 200 lines override previous 200 lines. 201 data whose definition stems from a prior 200 line. a valid 201 line consists of one or more white space separated tokens that represent data described by a previous 200 line. tokens may be quoted or unquoted. unquoted tokens may not contain white space. quoted tokens are terminated by the next quote but may not contain carrage re
turns or new lines. any illegal characters must be escaped via the url escaping syntax defined by rfc 1738. note that a 201 line encountered before a 200 line should be ignored. 300 a url pointing to the directory represented by the index if there is one. a valid path token must be url escaped. valid 200 tokens note that all tokens are case insensitive. filename the name of file that can be u...
NPEvent - Archive of obsolete content
events: sent to all instances in all windows. in addition to these standard types, the browser provides three additional event types that can be passed in the what field of the eventrecord: getfocusevent: sent when the instance could become the focus of subsequent key events, when the user clicks the instance or presses the tab key to focus the instance. if your instance accepts key events, re
turn true, and key events will be sent to the instance until it receives a losefocusevent. if your plug-in ignores key events, re
turn false, and the key events will be processed by the browser itself. losefocusevent: sent when the instance has lost the text focus, as a result of the user clicking elsewhere on the page or pressing the tab key to move the focus. no key events are sent to the instance ...
...ent when the instance has lost the text focus, as a result of the user clicking elsewhere on the page or pressing the tab key to move the focus. no key events are sent to the instance until the next getfocusevent. adjustcursorevent: sent when the mouse enters or leaves the bounds of the instance. if your plug-in wants to set the cursor when the mouse is within the instance, set the cursor and re
turn true. if you don't want a special cursor, re
turn false and the browser will use the standard arrow cursor. xwindows description the npevent object represents an event passed by npp_handleevent() to a windowless plug-in. the npevent structure is defined as xevent, the definition of the event type used by the xwindows platform. for information about the xevent structure and xwindows events, see t...
NPN_GetStringIdentifiers - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary re
turns an array of opaque identifiers for the names that are passed in. syntax #include <npruntime.h> void npn_getstringidentifiers(const nputf8 **names, int32_t namecount, npidentifier *identifiers); parameters the function has the following parameters: names an array of strings for which opaque identifiers should be re
turned. namecount the number of strings in the names array. identifiers a pointer to the first element of an array to fill with the identifiers for the strings specified by names. re
turns on re
turn, the identifiers array is filled out with the identifiers for each of the strings in the names array. ...
...ecount the number of strings in the names array. identifiers a pointer to the first element of an array to fill with the identifiers for the strings specified by names. re
turns on re
turn, the identifiers array is filled out with the identifiers for each of the strings in the names array. description as is the case with npn_getstringidentifier(), all calls for the same strings are guaranteed to re
turn the same exact identifiers. ...
NPN_Invoke - Archive of obsolete content
he function has the following parameters: npp the npp indicating which plugin wants to call the method on the object. npobj the object on which to invoke a method. methodname a string identifier indicating the name of the method to invoke. args an array of arguments to pass to the method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result re
turned by the method. re
turns true if the method was successfully invoked, otherwise false. if the method was invoked successfully, any re
turn value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the method arguments are passed as an array of npvariants, and the number of arguments is passed...
...was successfully invoked, otherwise false. if the method was invoked successfully, any re
turn value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the method arguments are passed as an array of npvariants, and the number of arguments is passed in. the result of the method invocation is re
turned through an npvariant result parameter. if the method invocation succeeds, npn_invoke() re
turns true, else false. note: early on in the development of the scriptability api this method used to be called npn_call() but was renamed for consistency. ...
NPN_InvokeDefault - Archive of obsolete content
rameters the function has the following parameters: npp the npp indicating which plugin wants to call the default method on the object. npobj the object on which to invoke the default method. args an array of arguments to pass to the default method. argcount the number of arguments in the args array. result a pointer to an npvariant to receive the result re
turned by the default method. re
turns true if the default method was successfully invoked, otherwise false. if the default method was invoked successfully, any re
turn value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the method arguments are passed as an array of npvariants, and the numbe...
...essfully invoked, otherwise false. if the default method was invoked successfully, any re
turn value is stored in the npvariant specified by result. when the caller no longer needs the result, it must call npn_releasevariantvalue() to release it. description the method arguments are passed as an array of npvariants, and the number of arguments is passed in. the result of the method invocation is re
turned through an npvariant result parameter. if the method invocation succeeds, npn_invoke() re
turns true, else false. ...
NPN_PluginThreadAsyncCall - Archive of obsolete content
eadasynccall(npp plugin, 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. re
turns 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 perfor...
...e. 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() re
turns immediately. after control re
turns to the browser, it is free to call the function with its argument from this thread. see also npp out-of-process plugins ...
NPN_PostURL - Archive of obsolete content
ath to local temporary file or data buffer that contains the data to post. temporary file is deleted after use. data in buffer cannot be posted for a protocol that requires a header. file a boolean value that specifies whether to post a file. values: true: post the file whose path is specified in buf, then delete the file. false: post the raw data in buf. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description npn_posturl works similarly to npn_geturl, but in reverse. npn_geturl reads data from the url and either displays it in the target window or delivers it to the plug-in. npn_posturl writes data from a fi...
... (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 re
turns 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
buf path to local temporary file or data buffer that contains the data to post. file whether to post a file. values: true: post the local file whose path is specified in buf, then delete the file. false: post the raw data in buf. notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify call, which re
turns this value (see description below). re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
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. np...
.... 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 re
turns 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 re
turn 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 ...
NPN_UserAgent - Archive of obsolete content
description the user agent is the part of the http header that identifies the browser during transfers. ...
...description the user agent is the part of the http header that identifies the browser during transfers. ...
NPN_Write - Archive of obsolete content
ance, npstream* stream, int32 len, void* buf); parameters the function has the following parameters: instance pointer to the current plug-in instance. stream pointer to the stream into which to push the data. len length in bytes of the data specified by buf. buf a pointer to a buffer of data to deliver to the stream. re
turns if successful, the function re
turns a positive integer representing the number of bytes written (consumed by the browser). this number depends on the size of the browser's memory buffers, the number of active streams, and other factors. if unsuccessful, the plug-in re
turns a negative integer. this indicates that the browser encountered an error while processing the data, so the plug-in should...
...er encountered an error while processing the data, so the plug-in should terminate the stream by calling npn_destroystream(). description npn_write() delivers a buffer from the stream to the instance. a plug-in can call this function multiple times after creating a stream with npn_newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method re
turns, if desired. see "example of sending a stream" for an example that includes npn_write(). example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done. note: you should actually handle errors, which this example doesn't do. npstream* stream; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = strlen(myd...
NPP_Destroy - Archive of obsolete content
pi summary deletes a specific instance of a plug-in. syntax #include <npapi.h> nperror npp_destroy(npp instance, npsaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete. **save state or other information to save for reuse by a new instance of this plug-in at the same url. passed to npp_new. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description npp_destroy releases the instance data and resources associated with a plug-in. the browser calls this function when a plug-in instance is deleted, typically because the user has left the page containing th...
...ic information stored in the plug-in's instance->pdata at this time. if this function is deleting the last instance of a plug-in, np_shutdown is subsequently called. use np_shutdown to delete any data allocated in np_initialize and intended to be shared by all instances of a plug-in. use the optional save parameter if you want to save and reuse some state or other information. upon the user's re
turn to the page, this information is passed to the new plug-in instance when it is created with npp_new. avoid trying to save critical data with this function. ownership of the buf field of the npsaveddata structure passes from the plug-in to the browser when npp_destroy re
turns. the browser can and will discard this data based on arbitrary criteria such as its size and the user's page history. to ...
NPP_New - Archive of obsolete content
-in from the embed tag. argv[] array of attribute values passed to the plug-in from the embed tag. saved pointer to data saved by npp_destroy for a previous instance of this plug-in at the same url. if non-null, the browser passes ownership of the npsaveddata object back to the plug-in. the plug-in is responsible for freeing the memory for the npsaveddata and the buffer it contains. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description npp_new creates a new instance of a plug-in. it is called after np_initialize and is passed the mime type, embedded or full-screen display mode, and, for embedded plug-ins, information about html embed arguments. a new instance pointer...
...s called after np_initialize and is passed the mime type, embedded or full-screen display mode, and, for embedded plug-ins, information about html embed arguments. a new instance pointer (npp instance) is created by the plug-in, which is valid until the instance is destroyed with npp_destroy. if instance data was saved from a previous instance of the plug-in by the npp_destroy function, it is re
turned in the saved parameter for the current instance to use. all attributes in the embed tag (standard and private) are passed in npp_new in the argn and argv arrays. the browser ignores any non-standard attributes within an embed tag. this gives developers a chance to use private attributes to communicate instance-specific options or other information to the plug-in. place private options at the e...
NPP_Write - Archive of obsolete content
eam. offset offset in bytes of buf from the beginning of the data in the stream. can be used to check stream progress or by range requests from npn_requestread. len length in bytes of buf; number of bytes accepted. buf buffer of data, delivered by the stream, that contains len bytes of data offset bytes from the start of the stream. the buffer is allocated by the browser and is deleted after re
turning from the function, so the plug-in should make a copy of the data it needs to keep. re
turns the plug-in should re
turn the number of bytes written (consumed by the instance). if the re
turn value is smaller than the size of the buffer, the browser sends the remaining data to the plug-in through subsequent calls to npp_writeready and npp_write. if unsuccessful, the function signals an error by r...
...the browser will destroy the stream by calling npp_destroystream. description the browser calls the npp_write function to deliver the data specified in a previous npp_writeready call to the plug-in. a plug-in must consume at least as many bytes as indicated in the npp_writeready call. ...
NPP_WriteReady - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary determines maximum number of bytes that the plug-in can consume. syntax #include <npapi.h> int32 npp_writeready(npp instance, npstream* stream); parameters the function has the following parameters: instance pointer to the current plug-in instance. stream pointer to the current stream. re
turns re
turns the maximum number of bytes that an instance is prepared to accept from the stream. description the browser calls npp_writeready before each call to npp_write to determine whether a plug-in can receive data and how many bytes it can receive. this function allows the browser to send only as much data to the instance as it can handle at one time, making resource use more efficient for both the browser and plug-in. th...
...efore each call to npp_write to determine whether a plug-in can receive data and how many bytes it can receive. this function allows the browser to send only as much data to the instance as it can handle at one time, making resource use more efficient for both the browser and plug-in. the npp_write function may pass a larger buffer, but the plug-in is required to consume only the amount of data re
turned by npp_writeready. the browser can write a smaller amount of data if desired or necessary; for example, if only 8k of data is available in a network buffer. if the plug-in is allocating memory for the entire stream at once (an as_file stream), it can re
turn a very large number. because it is not processing streaming data, the browser can pass as much data to the instance as necessary in a singl...
NPStream - Archive of obsolete content
ciated with the instance; not modified by the browser. ndata browser-private value that can store data associated with the instance; should not be modified by the plug-in. url the url that the data in the stream is read from or written to. end offset in bytes of the end of the stream (equivalent to the length of the stream in bytes). can be zero for streams of unknown length, such as streams re
turned from older ftp servers or generated "on the fly" by cgi scripts. lastmodified time the data in the url was last modified (if applicable), measured in seconds since 12:00 midnight gmt, january 1, 1970. notifydata used only for streams generated in response to a npn_geturlnotify or npn_posturlnotify request. for these streams, notifydata is set to the value of the notifydata parameter to npn_g...
...it to the plug-in initially as a parameter to npp_newstream. all api calls that operate on the stream (such as npp_writeready and npp_write) use a pointer to this stream. the browser informs the plug-in when the stream is about to be deleted through npp_destroystream, after which the npstream object is no longer valid. streams produced by the plug-in: the browser creates the npstream object and re
turns it as an output parameter when the plug-in calls npp_newstream. the plug-in must pass a pointer to the npstream to all api calls that operate on the stream, such as npn_write and npn_destroystream. see also npp_newstream, npp_destroystream, npp_destroystream ...
NP_GetMIMEDescription - Archive of obsolete content
np_getmimedescription re
turns a supported mime type list for your plugin. it works on unix (linux) and macos. on windows you have to define supported mimetypes in the dll resource file. each mime type description should be separated by a semicolon (;). each mime type description contains the mime type, an extensions list and a short description. ...
... be separated by a semicolon (;). each mime type description contains the mime type, an extensions list and a short description. one mime type // example inside http://mxr.mozilla.org/mozilla-central/source/modules/plugin/sdk/samples/basic/unix/plugin.cpp #define mime_type_description "application/basic-plugin:bsp:basic example plug-in for mozilla" const char* np_getmimedescription(void) { re
turn(mime_types_description); } two mime types const char* np_getmimedescription(void) { re
turn "application/basic-example-plugin:xmp1:example 1;application/basic-example2-plugin:xmp2, xm2p:example 2"; } gnome integration if you use gnome vfs (gnome-vfs-2.0), you can get the mime type description with a function. #include <libgnomevfs/gnome-vfs-mime-handlers.h> #include <libgnomevfs/gnome-vfs-m...
Sunbird Theme Tutorial - Archive of obsolete content
p much more disk space than it really needs. you might prefer to use this method only while you are developing your theme, and to use the normal method for public releases. in sunbird, use the default theme or some other theme. move your theme directory to a temporary location. this uninstalls it from sunbird. use a jar tool or zip tool to pack the contents of your theme directory. it is usual to
turn off compression so that your theme's speed is maximized. make sure that the tool packs all the directories and files that make up your theme. name the packed file with the <tt>.jar</tt> extension. for example, when i wrote this article i used this command in my theme directory: zip -0r testing-0.1.jar . make this jar file available to users. normal packaging in sunbird, use the default theme...
...mand in my theme directory: zip -0r testing-0.1.jar . make this jar file available to users. normal packaging in sunbird, use the default theme or some other theme. move your theme directory to a temporary location. this uninstalls it from sunbird. go to your <tt>chrome</tt> directory. use a jar tool or zip tool to pack everything in your <tt>chrome</tt> directory into a file. it is usual to
turn off compression so that your theme's speed is maximized. make sure that the tool packs all the directories and files that make up your theme. name the packed file with the <tt>.jar</tt> extension. for example, when i wrote this article i used this command in my <tt>chrome</tt> directory: zip -0r testing.jar . go back to your theme directory and edit the file <tt>chrome.manifest</tt>. change the...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
ad exits. in this memo we explain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an error. if the io operation cannot complete before the specified timeout, the io function re
turns with <tt>pr_io_timeout_error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function re
turns 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>prthrea...
... may work is to use a lock to ensure only one thread can be using that socket at all times. once there is a timeout or interrupt error, the file descriptor is no longer usable. suppose the file descriptor is intended to be used for the life time of the process, for example, the logging file, this is really not acceptable. a possible solution is to add a <tt>pr_disableinterrupt()</tt> function to
turn off interrupts when accessing such file descriptors. a related known bug is that timeout and interrupt don't work for <tt>pr_connect()</tt> on nt. this bug is due to a different limitation in our nt implementation. conclusions as long as we need to support nt 3.51, we need to program under the guideline that after an io timeout or interrupt error, the thread must make sure the file descriptor ...
Browser Feature Detection - Archive of obsolete content
document.createtextnode() true true true document.createcomment() true true true document.createcdatasection() true false true document.createprocessinginstruction() true false true document.createattribute() true true true document.createentityreference()obsolete since gecko 7 (method present but only re
turns null: bug 9850) false false document.getelementsbytagname() true true true dom core level 2 support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.doctype true true true document.implementation true true true document.documentelement true true true ...
...rted': false}, {name: 'unicodebidi', 'supported': false}, {name: 'visibility', 'supported': false}, {name: 'voicefamily', 'supported': false}, {name: 'volume', 'supported': false}, {name: 'widows', 'supported': false}, {name: 'zindex', 'supported': false} ] }; function supports(object, featureset) { var i; var features = _features[featureset]; var level = 0; if (!features) re
turn level; for (i = 0; i < features.length; i++) if (typeof(object[features[i].name]) != 'undefined') { features[i].supported = true; ++level; } re
turn math.floor( (100 * level) / features.length ); } function generatereport(object, featureset, description) { var i; var features = _features[featureset]; document.write('<p><b>' + featureset + ' support for properties/methods in...
Descendants and Filters - Archive of obsolete content
<dogs> <fido color="red"/> <spike color="blue"/> </dogs> </pets>; element..fido.@color = "green"; element..spike.@color = "purple"; changes the colors of both of our pet dogs. the same rules that apply to the . operator apply to the .. operator. that is, if there are multiple descendants of the requested type, an xml list is re
turned, instead of the normal element. the * selector re
turns all descendants in an xml list. filters in many cases, especially with the * selector, you don't want to work with all of the nodes that would be re
turned by the . or .. operator. to work with only a specific subset, place a conditional in parentheses after the operator. consider var element = <dogs> <fido color="brown"/> ...
...however, only fido and killer have their color attributes as brown. the filtering conditional therefore creates a list with just fido and killer as members. ...
Introduction - Archive of obsolete content
o>. you can also use brace notation on attributes of elements (their names or values). for example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different xml document: <foo bar="2">"hi"</foo>. note, however, that xml elements can only have text as their value. what really happens with the {} notation is that the variables' tostring method is called, and the re
turned value is placed in the element. for instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object object]</bar>. use of inline functions in content although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline: var a = 'foo'; var b = <bar>{function () {var c ...
...or instance var a = {foo: 1}; var b = <bar>{a}</bar>; actually produces a document that reads <bar>[object object]</bar>. use of inline functions in content although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline: var a = 'foo'; var b = <bar>{function () {var c = a.touppercase(); var d = 5 * 5; re
turn c + d;}()}</bar>; where the above produces: <bar>foo25</bar>. see e4x for templating for more discussion on this usage. serializing one of the most powerful tools of e4x is its ability to serialize an entire xml document (or portion thereof) into a string with one simple call to .toxmlstring() var element1 = <foo/>; var element2 = <bar/>; element1.appendchild(element2); element1.toxmlstring()...
Namespaces - Archive of obsolete content
info.u...
...es <p xmlns="http://www.w3.org/1999/xhtml"> some text <label xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul">more text</label> </p> name() using name() on an xml object re
turns a qname object (qualified name). qname is a global constructor available in javascript implementations supporting e4x. qname objects have two properties of particular relevance. the localname property re
turns the name of the element, without any namespace prefix. the uri property re
turns the uri of the namespace that the element is in. var info = a.name(); info.localname; // re
turns 'p'. info.uri; // re
turns "http://www.w3.org/1999/xhtml" elements in no namespace re
turn the empty string as their uri. the namespace global constructor is very similar to qname. namespace differs in its tostring method,...
Generator comprehensions - Archive of obsolete content
yields 2006 generator comprehensions compared to generator function an easy way to understand generator comprehension syntax, is to compare it with the generator function. example 1: simple generator. ...
...yield i * i; } })(); // generator comprehension (for (i of numbers) i * i ); // result: both re
turn a generator which yields [1, 4, 9] example 2: using if in generator. var numbers = [1, 2, 3]; // generator function (function*() { for (let i of numbers) { if (i < 3) { yield i * 1; } } })(); // generator comprehension (for (i of numbers) if (i < 3) i); // result: both re
turn a generator which yields [1, 2] specifications generator comprehensions were initially in the ecmascript 2015 draft, but got removed in revision 27 (august 2014). please see older revisions of es2015 for specification semantics. ...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
ing(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 re
turned 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); d...
...oncompleted(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() { re
turn 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). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 st...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
pleted. 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 re
turned 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. f...
...oncompleted(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() { re
turn 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). not supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 st...
Enumerator.atEnd - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the enumerator.atend method re
turns a boolean value indicating if the enumerator is at the end of the collection. syntax myenum.atend() remarks the required myenum reference is any enumerator object. the atend method re
turns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. otherwise, it re
turns false. example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefi...
...not supported in windows 8.x store apps. applies to: enumerator object ...
Enumerator.item - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the enumerator.item method re
turns the current item in the collection. syntax enumobj.item() remarks the required enumobj reference is any enumerator object. the item method re
turns the current item. if the collection is empty or the current item is undefined, it re
turns undefined. example function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; ...
...not supported in windows 8.x store apps. applies to: enumerator object ...
VBArray.dimensions - Archive of obsolete content
syntax array.dimensions( ) remarks the required array is a vbarray object. example the dimensions method provides a way to retrieve the number of dimensions in a specified vbarray. the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. ...
...not supported in windows 8.x store app...
VBArray.lbound - Archive of obsolete content
if dimension is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. ...
...not supported in windows 8.x store a...
New in JavaScript 1.3 - Archive of obsolete content
r date(year, month, day, [,hours [, minutes [, seconds [, milliseconds ]]]]) additional method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) the length of an array (property length) is now an unsigned, 32-bit integer. ...
...]]]) additional method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) the length of an array (property length) is now an unsigned, 32-bit integer. array.prototype.push(): in javascript 1.2, the push method re
turned the last element added to an array. under javascript 1.3, push re
turns the new length of the array. array.prototype.slice(): in javascript 1.2, the splice method re
turned the element removed, if only one element was removed (howmany parameter is 1). in javascript 1.3, splice always re
turns an array containing the removed elements. if one element is removed, an array of one element is re
turned. changes to string.prototype.replace(). changes to the boolean object.
Object.observe() - Archive of obsolete content
string indicating the type of change taking place. one of "add", "update", or "delete". oldvalue: only for "update" and "delete" types. the value before the change. acceptlist the list of types of changes to be observed on the given object for the given callback. if omitted, the array ["add", "update", "delete", "reconfigure", "setprototype", "preventextensions"] will be used. re
turn value the object to be observed. description callback is called each time a change is made to obj, with an array of all changes in the order in which they occurred. examples logging all six different types var obj = { foo: 0, bar: 1 }; object.observe(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}] obj.foo = 'hello'; // ...
...strawman proposal specification. ...
handler.enumerate() - Archive of obsolete content
the handler.enumerate() method used to be a trap for for...in statements, but has been removed from the ecmascript standard in es2016 and is deprecated in browsers. syntax var p = new proxy(target, { enumerate(target) { } }); parameters the following parameter is passed to the enumerate method. this is bound to the handler. target the target object. re
turn value an iterator object. description the handler.enumerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must re
turn an object. examples the following code t...
... trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must re
turn an object. examples the following code traps for...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); re
turn ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p = new proxy({}, { enumerate(target) { re
turn 1; } }); for (var x in p) {} // typeerror is thrown note: both examples make use of the shorthand syntax for method definitions. specifi...
Archived JavaScript Reference - Archive of obsolete content
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() method was used to remove observers set by array.observe(), but has been deprecated and removed from browsers. you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method re
turns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength. if newbytelength is undefined, the bytelength of the oldbuffer is used. this operation leaves oldbuffer in a detached state.date.prototype.tolocaleformat()the non-standard tolocaleformat() method converts a date to a string using the specified formatting. int...
...hod.object.prototype.watch()the watch() method watches for a property to be assigned a value and runs a function when that occurs.object.unobserve()the object.unobserve() method was used to remove observers set by object.observe(), but has been deprecated and removed from browsers. you can use the more general proxy object instead.reflect.enumerate()the static reflect.enumerate() method used to re
turn an iterator with the enumerable own and inherited properties of the target object, but has been removed in ecmascript 2016 and is deprecated in browsers.string.prototype.quote()the non-standard quote() method re
turns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
summary: a classic reborn! the amazing netscape fish cam page has been restructured and restyled for the new millennium, ditching tables for strong and accessible markup. take a cruise through one aspect of the redesign with master styler eric meyer. it's a well-known maxim that if you stick around long enough, you get a chance to see the tides of history
turn. if you're lucky, you get to ride the surf that second time around without being knocked over by the waves. i was privileged enough to have that chance recently: i was asked to redesign the amazing netscape fish cam page for a new millennium. to put that in perspective, i remember when the fish cam page first appeared and word of it circulated around the internet. you could see the actual fish in the mythical netscape headquarters, any ...
...o the heading containing the name of the fish created three problems: the double border was completely covered up by the image. the text of the h3 was basically touching the right side of the floated image... ...or it would have been, except in some browsers the heading was drawn over the floated image, in contradiction to the css specification. getting the image back on top of the heading
turned out to be a matter of relatively positioning the floated image, and then giving it a z-index value. in order to create visual appeal, i decided to offset the top let corners of the fish image and fish name. with just a few simple margin and padding changes, this was possible. div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; position: relative; z-index: 10; ...
Implementation Status - Archive of obsolete content
334333; 7.8.3 digest() unsupported 7.8.4 hmac() unsupported 7.9.1 local-date() supported 7.9.2 local-datetime() ...
... working 292333; 7.7.6 power() supported 7.7.7 random() supported 7.7.8 compare() supported 7.8.1 if() supported 7.8.2 property() partial re
turns basic for conformance-level, should re
turn full. version will re
turn as "1.0" for now, until more 1.1 work is completed. 334333; 7.8.3 digest() unsupported 7.8.4 hmac() unsupported 7.9.1 local-date() supported 7.9.2 local-datetime() supported 7...
Mozilla XForms Specials - Archive of obsolete content
icitly use the third parameter (the results are equal): digest('abc', 'sha-1', 'base64') (limitation tracked in bug 477857) extensions enumerating instances the standardized nsixformsmodelelement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name. in the mozilla xforms extension we added a getinstancedocuments() function to the model which re
turns all the model's instance documents. this is documented in nsixformsnsmodelelement. getting to instance element from a data node in the xforms 1.0 specification there is no way to get to the instance element from an instance data node. we have added a function via the getfeature() call on each node, that allows the form author to do that. that is, if instancenode is a node in an instance document...
.... getting to instance element from a data node in the xforms 1.0 specification there is no way to get to the instance element from an instance data node. we have added a function via the getfeature() call on each node, that allows the form author to do that. that is, if instancenode is a node in an instance document, then: instancenode.getfeature("org.mozilla.xforms.instanceowner", "1.0") will re
turn the <instance> element (in the main document) that the node belongs to. getting to the instance document from the instance element in the xforms 1.0 specification you have to go through the model element to get to the instance document. it seems a bit awkward if you have the instance element, so we have added a getinstancedocument() function directly on the instance element as a shortcut. this is...
The Business Benefits of Web Standards - Archive of obsolete content
ng data), svg (animated graphics), mathml (describing mathematic expressions)... such technologies have been designed to be interoperable, are the base of web services. this goes much further than just web authoring. reduce costs of maintenance and site operations what is maintenance anyway? one of the most important features of a successful site is constantly evolving relevant content which in
turn can act as fuel for social media dialogue with the user community. from this it follows that there needs to be a framework and a process for content contributors to post articles, to upload videos, sound or any other media. a web site is only a vehicle for carrying, navigating and displaying that content. content management systems attempt with some success to supply that level of functionality. ...
...lower cost to produce new content, and becoming compliant with accessibility requirements. for tomorrow, it means reducing vendor lock-in, reducing cost of maintenance, and having a more flexible web site in terms of presentation. last but not least, use of standards opens the door to xml technologies. all these factors also contribute to easier site management, a larger audience and a better re
turn on investment. geeks, marketers and bean-counters can all benefit from a standard-based web site. this is more than one could even dream of. ...
Windows Media in Netscape - Archive of obsolete content
-b153-00c04f79faa6 windows media player 6.4 and windows media player 7 and up are not backwards compatible in terms of apis (and thus have different classids). here is a snippet of code that illustrates the use of classids with geckoactivexobject: function creategeckowmpobject(clid) { var player = null; try { player = new geckoactivexobject(clid); } catch(e) { ; } re
turn player; } // instantiate players wmp7or9 = creategeckowmpobject("{6bf52a52-394a-11d3-b153-00c04f79faa6}"); if (!wmp7or9) { wmp64 = creategeckowmpobject("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); } ..... note that the classids must be passed in curly braces "{}". the name geckoactivexobject rather than activexobject was introduced for two reasons: geckoactivexobject is limited to crea...
...chanism to to this. <object id="playerex2" classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" height="200" width="200"> <param name="uimode" value="full" /> <param name="autostart" value="true" /> <param name="url" value="preludesteel.wma" /> </object> <script type="text/javascript"> if(!document.playerex2.versioninfo) { // control not installed -- the versioninfo property re
turns null // redirect users to http://www.microsoft.com/windows/windowsmedia/download/default.asp } else { //control was correctly created //proceed with scripting calls, etc. } </script> note that if the control is correctly instantiated, you will know that it is a version of windows media player 7 and up, since the clsid used with the object element reflects the unique component in this ver...
Unconventional controls - Game development
a working leap motion example in javascript is here already. you can explore the hand's properties and implement any behaviour you like right inside your game. doppler effect there's a very interesting article available on motion sensing using the doppler effect, which mixes together waving your hand and using the microphone. this time it's about detecting sound waves bouncing off objects and re
turning to the microphone. if the frequency of the bounced sound is shifted from the original one, then we can detect that the movement of that object occured. that way we can detect a hand movement by using only a built-in microphone! this can be accomplished using a small library created by daniel rapp — it can be as simple as calculating the difference between two frequencies: doppler.init(f...
...ax = event.max; var proximity = event.value; }); the min and max values are the minimum and the maximum distances respectively between which the sensor can detect the exact proximity value. all three are calculated in centimetres. note: see the deviceproximityevent reference page for more details. makey makey if you want to go completely bananas you can use makey makey, a board that can
turn anything into a controller — it's all about connecting real-world, conductive objects to a computer and using them as touch interfaces. check out the banana piano video, and be sure to visit the quick start guide for all the needed info. there's even a cylon.js-supported makey button functionality inspired by the makey makey board, so you can use the popular cylon robotics framework for you...
Square tilemaps implementation: Static maps - Game development
er, we must account for empty tiles, since they are crucial for implementing layers — empty tiles are usually assigned a negative index value, 0, or a null value. in these examples, empty tiles will be represented by index 0, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index 1, the second index 2, etc.) the gettile() helper method re
turns the tile contained at the specified column and row. if tiles were a 2d matrix, then the re
turned value would just be tiles[column][row]. however, it's usually more common to represent the grid with a 1-dimensional array. in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the followi...
...e following. this features an 8 x 8 map with tiles 64 x 64 pixels in size: var map = { cols: 8, rows: 8, tsize: 64, tiles: [ 1, 3, 3, 3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ], gettile: function(col, row) { re
turn this.tiles[row * map.cols + col] } }; rendering the map we can render the map by iterating over its columns and rows. this snippets assumes the following definitions: context: a 2d canvas context. tileatlas: an image object containing the tile atlas. map: the tilemap object discussed above. for (var c = 0; c < map.cols; c++) { for (var r = 0; r < map.rows; r++) { var tile = map.g...
Tiles and tilemaps overview - Game development
n the game. to be able to transform world coordinates into screen coordinates, we need the coordinates of the camera, since they determine which section of the world is being displayed. ...
...we need the coordinates of the camera, since they determine which section of the world is being displayed. here are examples showing how to translate from world coordinates to screen coordinates and back again: // these functions assume that the camera points to the top left corner function worldtoscreen(x, y) { re
turn {x: x - camera.x, y: y - camera.y}; } function screentoworld(x,y) { re
turn {x: x + camera.x, y: y + camera.y}; } rendering a trivial method for rendering would just be to iterate over all the tiles (like in static tilemaps) and draw them, substracting the camera coordinates (like in the worldtoscreen() example shown above) and letting the parts that fall outside the view window sit there, hidden. drawing all the tiles that can not be seen is wasteful, however, and can...
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
cr and lf are control characters or bytecode that can be used to mark a line break in a text file. cr = carriage re
turn (\r, 0x0d in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. lf = line feed (\n, 0x0a in hexadecimal, 10 in decimal) — moves the cursor down to the next line without re
turning to the beginning of the line. ...
...e line without advancing to the next line. lf = line feed (\n, 0x0a in hexadecimal, 10 in decimal) — moves the cursor down to the next line without re
turning to the beginning of the line. ...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
here their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { re
turn "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this: ignore all functions, until it reaches the greeting() function invocation. add the greeting() function to the call stack list. call stack list: - greeting execute all lines of code inside the greeting() function. get to the sayhi() function invocation. ...
... function invocation. add the greeting() function to the call stack list. call stack list: - greeting execute all lines of code inside the greeting() function. get to the sayhi() function invocation. add the sayhi() function to the call stack list. call stack list: - sayhi - greeting execute all lines of code inside the sayhi() function, until reaches its end. re
turn execution to the line that invoked sayhi() and continue executing the rest of the greeting() function. delete the sayhi() function from our call stack list. call stack list: - greeting when everything inside the greeting() function has been executed, re
turn to its invoking line to continue executing the rest of the js code. delete the greeting() function from the call stack list. ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element. the idl attribute is also known as a javascript property. these are the attributes you can read or set using javascript properties like element.foo. the idl attribute is always going to use (but might transform) the underlying content attribute to re
turn a value when you get it and is going to save something in the content attribute when you set it. in other words, the idl attributes, in essence, reflect the content attributes. most of the time, idl attributes will re
turn their values as they are really used. for example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text ...
...n essence, reflect the content attributes. most of the time, idl attributes will re
turn their values as they are really used. for example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". however, the type idl attribute will re
turn the string "text". idl attributes are not always strings; for example, input.maxlength is a number (a signed long). when using idl attributes, you read or set values of the desired type, so input.maxlength is always going to re
turn a number and when you set input.maxlength ,it wants a number. if you pass another type, it is automatically converted to a number as specified by the standard javascr...
Parameter - MDN Web Docs Glossary: Definitions of Web-related terms
n's definition. function arguments are the real values passed to the function. parameters are initialized to the values of the arguments supplied. two kinds of parameters: input parameters the most common kind; they pass values into functions. ...
...uments are the real values passed to the function. parameters are initialized to the values of the arguments supplied. two kinds of parameters: input parameters the most common kind; they pass values into functions. ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
in depth signatures in javascript javascript is a loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. ...
...e. java is strictly typed and will check any parameters at compilation time if they are correct. public static void main(string[] args) the public keyword is an access modifier and indicates that this method can be called by any object. the static keyword indicates that this method is a class method as opposed to being an instance method. the void keyword indicates that this method has no re
turn value. the name of the method is main. the method accepts one parameter of type string array. it is named args. learn more general knowledge java internal type signatures on wikipedia ...
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
plicit. ...
...nst value2 = 9; let sum = value1 + value2; console.log(sum); in the above example, javascript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59. javascript had a choice between a string or a number and decided to use a string. the compiler could have coerced the 5 into a number and re
turned a sum of 14, but it did not. to re
turn this result, you'd have to explicitly convert the 5 to a number using the number() method: sum = number(value1) + value2; ...
Assessment: Accessibility troubleshooting - Learn web development
d javascript into one of these online editors. if the online editor you are using doesn't have a separate css/js panel, feel free to put them in appropriate <style> / <script> elements. the finished assessment site should look like so: you will see some differences/issues with the display of the starting state of the assessment — this is mainly due to the differences in the markup, which in
turn cause some styling issues as the css is not applied properly. don't worry — you'll be fixing these problems in the upcoming sections! note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief for this project, you are presented with a fictional nature site displaying a "factual" article about bears. as it stands, i...
...m have visible text labels, but they are not unambiguously associated with their labels — how do you achieve this? note that you'll need to update some of the css rule as well. the show/hide comment control the show/hide comment control button is not current keyboard-accessible. can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the re
turn key? the table the data table is not currently very accessible — it is hard for screenreader users to associate data rows and columns together, and the table also has no kind of summary to make it clear what it shows. can you add some features to your html to fix this problem? other considerations? can you list two more ideas for improvements that would make the website more accessible? as...
Debugging CSS - Learn web development
the css will stop applying. you can use this to do an a/b comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example if a layout is going wrong and you are trying to work out which property is causing the problem. the following video provides some useful tips on debugging css using the firefox devtools: editing values in addition to
turning properties on and off, you can edit their values. perhaps you want to see if another color looks better, or wish to tweak the size of something? devtools can save you a lot of time editing a stylesheet and reloading the page. with box1 selected, click on the swatch (the small colored circle) that shows the color applied to the border. a color picker will open up and you can try out some diffe...
...vascript as you can, leaving in whatever causes the issue. remove any html that does not contribute to the issue. remove components or even main elements of the layout. again, try to get down to the smallest amount of code that still shows the issue. remove any css that doesn't impact the issue. in the process of doing this, you may discover what is causing the problem, or at least be able to
turn it on and off by removing something specific. it is worth adding some comments to your code as you discover things. if you need to ask for help, they will show the person helping you what you have already tried. this may well give you enough information to be able to search for likely sounding problems and workarounds. if you are still struggling to fix the problem then having a reduced test cas...
The box model - Learn web development
had an alternative box model introduced some time after the standard box model. using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border. the same css as used above would give the below result (width = 350px, height = 150px). by default, browsers use the standard box model. if you want to
turn on the alternative model for an element you do so by setting box-sizing: border-box on it. by doing this you are telling the browser to take the border box as the area defined by any size you set. .box { box-sizing: border-box; } if you want all of your elements to use the alternative box model, and this is a common choice among developers, set the box-sizing property on the <html> element, ...
...using the padding to be respected by other elements. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: the box model. summary that's most of what you need to understand about the box model. you may want to re
turn to this lesson in the future if you ever find yourself confused about how big boxes are in your layout. in the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting. previous overview: building blocks next in this module cascade and inheritance css selectors type, class, and id selectors attribute selecto...
Flexbox - Learn web development
that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse. flex-flow shorthand at this point it is worth noting that a shorthand exists for flex-direction and flex-wrap — flex-flow. so for example, you can replace flex-direction: row; flex-wrap: wrap; with flex-flow: row wrap; flexible sizing of flex items let's now re
turn to our first example, and look at how we can control what proportion of space flex items take up compared to the other flex items. fire up your local copy of flexbox0.html, or take a copy of flexbox1.html as a new starting point (see it live). first, add the following rule to the bottom of your css: article { flex: 1; } this is a unitless proportion value that dictates how much of the availa...
...ies unless you really have to (for example, to override something previously set). they lead to a lot of extra code being written, and they can be somewhat confusing. horizontal and vertical alignment you can also use flexbox features to align flex items along the main or cross axis. let's explore this by looking at a new example — flex-align0.html (see it live also) — which we are going to
turn into a neat, flexible button/toolbar. at the moment you'll see a horizontal menu bar, with some buttons jammed into the top left hand corner. first, take a local copy of this example. now, add the following to the bottom of the example's css: div { display: flex; align-items: center; justify-content: space-around; } refresh the page and you'll see that the buttons are now nicely cen...
Introduction to CSS layout - Learn web development
ge the display value to inline they now display next to each other, as words would do in a sentence. the fact that you can change the value of display for any element means that you can pick html elements for their semantic meaning, without being concerned about how they will look. the way they look is something that you can change. in addition to being able to change the default presentation by
turning an item from block to inline and vice versa, there are some bigger layout methods that start out as a value of display. however, when using these, you will generally need to invoke additional properties. the two values most important for our purposes when discussing layout are display: flex and display: grid. flexbox flexbox is the short name for the flexible box layout module, designed to m...
... this example live at css-tables-example.html (see the source code too.) multi-column layout the multi-column layout module gives us a way to lay out content in columns, similar to how text flows in a newspaper. while reading up and down columns is less useful in a web context as you don’t want to force users to scroll up and down, arranging content into columns can be a useful technique. to
turn a block into a multicol container we use either the column-count property, which tells the browser how many columns we would like to have, or the column-width property, which tells the browser to fill the container with as many columns of at least that width. in the below example we start with a block of html inside a containing <div> element with a class of container. <div class="container"> ...
Supporting older browsers - Learn web development
sing the legacy techniques we have already covered, which are then overwritten by your grid layout in modern browsers that understand it. in the below example, we have floated three <div>s so they display in a row. any browser that does not support css grid layout will see the row of boxes as a floated layout. a floated item that becomes a grid item loses the float behaviour, which means that by
turning the wrapper into a grid container, the floated items become grid items. if the browser supports grid layout it will display the grid view, if not it ignores the display: grid and related properties and the floated layout is used. * {box-sizing: border-box;} .wrapper { background-color: rgb(79,185,227); padding: 10px; max-width: 400px; display: grid; grid-template-columns: 1fr 1fr ...
... fallback methods there are a number of layout methods which can be used in a similar way to this float example. you can choose the one that makes the most sense for the layout pattern you need to create. float and clear as shown above, the float and clear properties cease to affect the layout if floated or cleared items become flex or grid items. display: inline-bloc...
What is CSS? - Learn web development
. browsers are the main type of user agent we think of when talking about css, however, it is not the only one. there are other user agents available — such as those which convert html and css documents into pdfs to be printed. css can be used for very basic document text styling — for example changing the color and size of headings and links. it can be used to create layout — for example
turning a single column of text into a layout with a main content area and a sidebar for related information. it can even be used for effects such as animation. have a look at the links in this paragraph for specific examples. css syntax css is a rule-based language — you define rules specifying groups of styles that should be applied to particular elements or groups of elements on your web page. ...
...much rather refer to mdn documentation or other tutorials. it is however worth knowing that they exist, understanding the relationship between the css you are using, browser support (see below), and the specs. browser support once css has been specified then it is only useful for us in developing web pages if one or more browsers have implemented it. this means that the code has been written to
turn the instruction in our css file into something that can be output to the screen. we'll look at this process more in the lesson how css works. it is unusual for all browsers to implement a feature at the same time, and so there is usually a gap where you can use some part of css in some browsers and not in others. for this reason, being able to check implementation status is useful. on each proper...
How does the Internet work? - Learn web development
s, with nine plugs per computer! to solve this problem, each computer on a network is connected to a special tiny computer called a router. this router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. to send a message to computer b, computer a must send the message to the router, which in
turn forwards the message to computer b and makes sure the message is not delivered to computer c. once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs. a network of networks so far so good. but what about connecting hundreds, thousands, billions of computers? of course a single router can't scale that ...
... your house and the rest of the world, so how can you handle this? well, there are already cables linked to your house, for example, electric power and telephone. the telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. to connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. this modem
turns the information from our network into information manageable by the telephone infrastructure and vice versa. so we are connected to the telephone infrastructure. the next step is to send the messages from our network to the network we want to reach. to do that, we will connect our network to an internet service provider (isp). an isp is a company that manages some special routers that are all...
How do I use GitHub Pages? - Learn web development
line to your test-site directory (or whatever you called the directory containing your website). for this, use the cd command (i.e. "change directory"). here's what you'd type if you've put your website in a directory called test-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to
turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface. it will look something like this: note: you could also consider using a git graphical user inter...
...the code for uploading to github, and ask git to manage these files. git add --all git commit -m 'adding my files to my repository' finally, push the code up to github by going to the github web page you're on and entering into the terminal the second of the two commands we saw the …or push an existing repository from the command line section: git push -u origin master now you need to
turn github pages on for your repository. to do this, from the homepage of your repository choose settings, then scroll down until you get to the github pages section. underneath source, choose master branch. the page should refresh. go to the github pages section again, and you should see a line of the form "your site is ready to be published at https://xxxxxx." if you click on this url, you shoul...
What is a web server? - Learn web development
e end user's device. at the most basic level, whenever a browser needs a file that is hosted on a web server, the browser requests the file via http. when the request reaches the correct (hardware) web server, the (software) http server accepts the request, finds the requested document, and sends it back to the browser, also through http. (if the server doesn't find the requested document, it re
turns a 404 response instead.) to publish a website, you need either a static or a dynamic web server. a static web server, or stack, consists of a computer (hardware) with an http server (software). we call it "static" because the server sends its hosted files as-is to your browser. a dynamic web server consists of a static web server plus extra software, most commonly an application server and ...
... with an error message. on a web server, the http server is responsible for processing and answering incoming requests. upon receiving a request, an http server first checks if the requested url matches an existing file. if so, the web server sends the file content back to the browser. if not, an application server builds the necessary file. if neither process is possible, the web server re
turns an error message to the browser, most commonly 404 not found. (the 404 error is so common that some web designers devote considerable time and effort to designing 404 error pages.) static vs. dynamic content roughly speaking, a server can serve either static or dynamic content. remember that the term static means "served as-is". static websites are the easiest to set up, so we suggest you mak...
How do you set up a local testing server? - Learn web development
on the first installer page, make sure you check the "add python 3.xxx to path" checkbox. click install, then click close when the installation has finished. open your command prompt (windows)/ terminal (macos/ linux). ...
... available, # in which case try py -v this should re
turn a version number. if this is ok, navigate to the directory that your example is inside, using the cd command. # include the directory name to enter it, for example cd desktop # use two dots to jump up one directory level if you need to cd .. enter the command to start up the server in that directory: # if python version re
turned above is 3.x python3 -m http.server # on windows try "python" instead of "python3", or "py -3" # if python version re
turned above is 2.x python -m simplehttpserver by default, this will run the contents of the directory on a local web server, on port 8000. you can go to this server by going to the url localhost:8000 in your web browser. here you'll see the contents of the directory listed...
Example 4 - Learn web development
.3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) re
turn; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) re
turn; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optli...
...evalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.queryselector('.value'); var optionlist = select.queryselectorall('.option'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; function getindex(select) { var nativewidget = select.previouselementsibling; re
turn nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); selectlist.foreach(function (sele...
Example 5 - Learn web development
.3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) re
turn; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) re
turn; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optli...
...ctorall('.option'); optionlist.foreach(function (other) { other.setattribute('aria-selected', 'false'); }); optionlist[index].setattribute('aria-selected', 'true'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; function getindex(select) { var nativewidget = select.previouselementsibling; re
turn nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); selectlist.foreach(function (sele...
Sending form data - Learn web development
installed). example: python this example shows how you would use python to do the same thing — display the submitted data on a web page. this uses the flask framework for rendering the templates, handling the form data submission, etc. (see python-example.py). ...
...display the submitted data on a web page. this uses the flask framework for rendering the templates, handling the form data submission, etc. (see python-example.py). ...
Sending forms through JavaScript - Learn web development
httprequest, prepare the data by url-encoding it, and obey the specifics of form data requests. let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; //
turn the data object into an array of url-encoded key/value pairs. for( name in data ) { urlencodeddatapairs.push( encodeuricomponent( name ) + '=' + encodeuricomponent( data[name] ) ); } // combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. urlencodeddata = urlencodeddatapairs.join( '&' ).r...
... let data = ""; // so, if the user has selected a file if ( file.dom.files[0] ) { // start a new part in...
UI pseudo-classes - Learn web development
ave available? the original pseudo-classes available to us (as of css 2.1) that are relevant to forms are: :hover: selects an element only when it is being hovered over by a mouse pointer. :focus: selects an element only when it is focused (i.e. by being tabbed to via the keyboard). :active: selects an element only when it is being activated (i.e. while it is being clicked on, or when the re
turn/enter key is being pressed down in the case of a keyboard activation). these basic pseudo-classes should be familiar to you now. more recently, the css selector level 3 and css basic ui level 3 added more pseudo-classes related to html forms that provide several other useful targetting conditions that you can take advantage of. we'll discuss these in more detail in the sections below, but brief...
...ut-of-range at the same time, so what happens then? because the :out-of-range rule appears later in the source code than the :required rule, the cascade rules come into play, and the out of range message is shown. this works quite nicely — when the page first loads, "required" is shown, along with a red cross and border. when you've typed in a valid age (i.e. in the range of 12-120), the input
turns valid. if however, you then change the age entry to one that is out of range, the "outside allowable value range" message then pops up in place of "required". note: to enter an invalid/out-of-range value, you'll have to actually focus the form and type it in using the keyboard. the spinner buttons won't let you increment/decrement the value outside the allowable range. styling enabled and di...
HTML basics - Learn web development
s the title of your page, which is the title that appears in the browser tab the page is loaded in. it is also used to describe the page when you bookmark/favourite it. <body></body> — the <body> element. this contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks or whatever else. images let's
turn our attention to the <img> element again: <img src="images/firefox-icon.png" alt="my test image"> as we said before, it embeds an image into our page in the position it appears. it does this via the src (source) attribute, which contains the path to our image file. we have also included an alt (alternative) attribute. in this attribute, you specify descriptive text for users who cannot see the...
...e ordered and unordered lists: unordered lists are for lists where the order of the items doesn't matter, such as a shopping list. these are wrapped in a <ul> element. ordered lists are for lists where the order of the items does matter, such as a recipe. these are wrapped in an <ol> element. each item inside the lists is put inside an <li> (list item) element. for example, if we wanted to
turn the part of the following paragraph fragment into a list <p>at mozilla, we’re a global community of technologists, thinkers, and builders working together ... </p> we could modify the markup to this <p>at mozilla, we’re a global community of</p> <ul> <li>technologists</li> <li>thinkers</li> <li>builders</li> </ul> <p>working together ... </p> try adding an ordered or unordered lis...
Advanced text formatting - Learn web development
ld wrap it inside a <blockquote> element to signify this, and include a url pointing to the source of the quote inside a cite attribute. ...
...> <p>the quote element — <code><q></code> — is <q cite="/docs/web/html/element/q">intended for short quotations that don't require paragraph breaks.</q> -- <a href="/docs/web/html/element/q"> <cite>mdn q page</cite></a>.</p> citations are styled in italic font by default. active learning: who said that? time for another active learning example! in this example we'd like you to:
turn the middle paragraph into a blockquote, which includes a cite attribute.
turn "the need to eliminate negative self talk" in the third paragraph into an inline quote, and include a cite attribute. wrap the title of each source in <cite> tags and
turn each one into a link to that source. the citation sources you need are: http://www.brainyquote.com/quotes/authors/c/confucius.html for the con...
Creating hyperlinks - Learn web development
also note the use of the question mark (?) to separate the main url from the field values, and ampersands (&) to separate each field in the mailto: url. this is standard url query notation. read the get method to understand what url query notation is more commonly used for. here are a few other sample mailto urls: mailto: mailto:nowhere@mozilla...
...y@mozilla.org mailto:nowhere@mozilla.org?cc=nobody@mozilla.org&subject=this%20is%20the%20subject test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: links. summary that's it for links, for now anyway! you'll re
turn to links later on in the course when you start to look at styling them. next up for html, we'll re
turn to text semantics and look at some more advanced/unusual features that you'll find useful — advanced text formatting is your next stop. previous overview: introduction to html next in this module getting started with html what’s in the head? metadata in html html text fundamen...
Getting started with HTML - Learn web development
nked to. for example, title="the mozilla homepage". this appears as a tooltip when a cursor hovers over the element. target: the target attribute specifies the browsing context used to display the link. for example, target="_blank" will display the link in a new tab. if you want to display the linked content in the current tab, just omit this attribute. edit the line below in the input area to
turn it into a link to your favorite website. add the <a> element. add the href attribute and the title attribute. specify the target attribute to open the link in the new tab. you'll be able to see your changes update live in the output area. you should see a link—that when hovered over—displays the value of the title attribute, and when clicked, navigates to the web address in the href at...
..., as modern browsers will handle the actual symbols just fine as long, as your html's character encoding is set to utf-8. html comments html has a mechanism to write comments in the code. browsers ignore comments, effectively making comments invisible to the user. the purpose of comments is to allow you to include notes in the code to explain your logic or coding. this is very useful if you re
turn to a code base after being away for long enough that you don't completely remember it. likewise, comments are invaluable as different people are making changes and updates. to write an html comment, wrap it in the special markers <!-- and -->. for example: <p>i'm not inside a comment</p> <!-- <p>i am!</p> --> as you can see below, only the first paragraph displays in the live output. summa...
Test your skills: Advanced HTML text - Learn web development
advanced text formatting article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... semantically mark up "html" and "css" as acronyms, providing expansions as tooltips. semantically associate machine-readable dates with the dates in the text. ...
HTML table basics - Learn web development
s 4.87 12,104 5243 8.9 2802.0 108.2 464 0 earth 5.97 12,756 5514 9.8 24.0 149.6 15 1 our world mars 0.642 6,792 3933 3.7 24.7 227.9 -65 2 the red planet jovian planets gas giants jupiter 1898 142,984 1326 23.1 9.9 778.6 -110 67 the largest planet sa
turn 568 120,536 687 9.0 10.7 1433.5 -140 62 ice giants uranus 86.8 51,118 1271 8.7 17.2 2872.5 -195 27 neptune 102 49,528 1638 11.0 16.1 4495.1 -200 14 dwarf planets pluto 0.0146 2,370 2095 0.7 153.3 5906.4 -225 5 declassified as a planet in 2006, but this re...
...ained in a <td>. this should result in a table that looks something like the following: hi, i'm your first cell. i'm your second cell. i'm your third cell. i'm your fourth cell. second row, first cell. cell 2. cell 3. cell 4. note: you can also find this on github as simple-table.html (see it live also). adding headers with <th> elements now let's
turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "person" and "age" cells in the first example shown in this article). to illustrate why they are useful, have a look at the following table example. first the source code: <table> <tr> <td> </td> <td>knocky</td> ...
Assessment: Structuring planet data - Learn web development
ls, feel free to put them inline <script>/<style> elements inside the html page. project brief you are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. an html data table would be ideal — you need to take the raw data you have available and
turn it into a table, following the steps below. the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example. all the data you'll need is contained in the planets-data.txt file. if you have trouble visualising the data, look at ...
... column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for. add a black border just around the column that contains all the planet name row headers. hints and tips the first cell of the header row needs to be blank, and span two columns. the group row headings (e.g. jovian planets) that sit to the left of the planet name row headings (e.g. sa
turn) are a little tricky to sort out — you need to make sure each one spans the correct number of rows and columns. one way of associating headers with their rows/columns is a lot easier than the other way. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
Build your own function - Learn web development
are covered in the next article, so you might want to read those first before trying it. ...
... function, which with a bit more work could be transplanted into a real project. in the next article we'll wrap up functions by explaining another essential related concept — re
turn values. ...
Image gallery - Learn web development
sn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief you have been provided with some html, css and image assets and a few lines of javascript code; you need to write the necessary javascript to
turn this into a working program. the html body looks like this: <h1>image gallery example</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1.jpg"> <div class="overlay"></div> <button class="dark">darken</button> </div> <div class="thumb-bar"> </div> the example looks like this: the most interesting parts of the example's css file: it absolutely positions the t...
... to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: building blocks in this module making decisions in your code — conditionals looping code functions — reusable blocks of code build your own function function re
turn values introduction to events image gallery ...
JavaScript building blocks - Learn web development
you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have some familiarity with the basics of html and css, and you should have also worked through our previous module, javascript first steps. ...
...ehind functions such as basic syntax, how to invoke and define functions, scope, and parameters. build your own function with most of the essential theory dealt with previously, this article provides a practical experience. here you'll get some practice with building up your own custom function. along the way, we'll also explain some further useful details of dealing with functions. function re
turn values the last essential concept you must know about a function is re
turn values. some functions don't re
turn a significant value after completion, but others do. it's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions re
turn useful values. introduction to events events are actions or occurrences that happen in the s...
Solve common problems in your JavaScript code - Learn web development
re. for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or re
turn the value from the function. running code after a re
turn statement remember also that when you re
turn from a function, the javascript interpreter exits the function — no code after the re
turn statement will run. in fact, some browsers (like firefox) will give you an error message in the developer console if you have code after a re
turn statement. firefox gives you "unreachable code after ret...
... object nested inside an array? intermediate use cases functions how do you find functions in the browser? what is the difference between a function and a method? how do you create your own functions? how do you run (call, or invoke) a function? what is an anonymous function? how do you specify parameters (or arguments) when invoking a function? what is function scope? what are re
turn values, and how do you use them? objects how do you create an object? what is dot notation? what is bracket notation? how do you get and set the methods and properties of an object? what is this, in the context of an object? what is object-oriented programming? what are constructors and instances, and how do you create them? what different ways are there to create objects in javascrip...
JavaScript object basics - Learn web development
er tools javascript console open and ready to type in some commands. as with many things in javascript, creating an object often begins with defining and initializing a variable. try entering the following line below the javascript code that's already in your file, then saving and refreshing: const person = {}; now open your browser's javascript console, enter person into it, and press enter/re
turn. you should get a result similar to one of the below lines: [object object] object { } { } congratulations, you've just created your first object. job done! but this is an empty object, so we can't really do much with it. let's update the javascript object in our file to look like this: const person = { name: ['bob', 'smith'], age: 32, gender: 'male', interests: ['music', 'skiing'], ...
...your javascript console: const mynotification = new notification('hello!'); again, we'll look at constructors in a later article. note: it is useful to think about the way objects communicate as message passing — when an object needs another object to perform some kind of action often it sends a message to another object via one of its methods, and waits for a response, which we know as a re
turn value. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: object basics. summary congratulations, you've reached the end of our first js objects article — you should now have a good idea of how to work with ...
Measuring performance - Learn web development
ary looks similar to the following: a performance report contains information about things like how long a user has to wait before anything is displayed on the page, how many bytes need to be downloaded to display a page, and much more. it also lets you know it the measured values are considered good or bad. ...
... you can also use the performance monitor to measure the performance of a web app or site's user interface as you perform different actions. ...
Perceived performance - Learn web development
ng the mouse, thinking, being entertainted, they are in an active phase. the passive phase occurs when the user is passively waiting, like staring at a monochrome screen. if both the passive and active waits time were objectively equal, users would estimate that the passive waiting period was longer than the active. if a load, render, or response time can not be objectively minimized any further,
turning the wait into an active wait instead of a passive wait can make it feel faster. there are tips and tricks to follow. some of these quick tips have full articles if you want to dive deeper. displaying content, or at least some part of the page with an indication that content is loading, as quickly as possible, is essential to improving perceived performance. for example, because page render i...
... making a content request on keydown rather than waiting for keyup can shave 200ms off the perceived load of the content. adding an interesting but unobtrusive 200ms animation to that keyup even can reduce another 200ms of the perceived load. you're not saving 400ms of time, but the user doesn't feel like they're waiting for content until, well, until they're waiting for content. conclusion by
turning as much of the download, render and wait time into active phases and reducing any passive waiting, even if the objective measurements stay the same, the user will feel like the content downloaded, rendered, and responded more quickly. now that we know what we should be speeding up, let's take a look at some metrics and learn how we can measure these events. previous overview: performance...
Ember interactivity: Events, classes and state - Learn web development
odos; } one issue here is that our service is called todos, but the list of todos is also called todos, so currently we would access the data using this.todos.todos. this is not intuitive, so we'll add a getter to the todos service called all, which will represent all todos. to do this, go back to your todo-data.js file and add the following below the @tracked todos = []; line: get all() { re
turn this.todos; } now we can access the data using this.todos.all, which is much more intuitive. to put this in action, go to your todo-list.hbs component, and replace the static component calls: <todo /> <todo /> with a dynamic #each block (which is basically syntactic sugar over the top of javascript's foreach()) that creates a <todo /> component for each todo available in the list of todos retu...
...o|}} <todo @todo={{todo}} /> {{/each}} another way to look at this: this — the rendering context / component instance. todos — a property on this, which we defined in the todo-list.js component using @service('todo-data') todos;. this is a reference to the todo-data service, allowing us to interact with the service instance directly. all — a getter on the todo-data service that re
turns all the todos. try starting the server again and navigating to our app, and you'll find that it works! well, sort of. whenever you enter a new todo item, a new list item appears below the text input, but unfortunately it always says "buy movie tickets". this is because the text label inside each list item is hardcoded to that text, as seen in todo.hbs: <label>buy movie tickets</label> updat...
Ember app structure and componentization - Learn web development
oapp"> <h1>todos</h1> <input class="new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > </section> note: aria-label provides a label for assistive technology to make use of — for example, for a screenreader to read out. this is useful in such cases where we have an <input> being used with no corresponding html text that could be
turned into a label. when you save application.hbs, the development server you started earlier will automatically rebuild the app and refresh the browser. the rendered output should now look like this: it doesn't take too much effort to get our html looking like a fully-featured to-do list app. update the application.hbs file again so its content looks like this: <section class="todoapp"> <h1>...
... <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> </section> the rendered output should now be as follows: this looks pretty complete, but remember that this is only a static prototype. now we need to break up our html code into dynamic components; later we'll
turn it into a fully interactive app. looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the ui, but let's plan on splitting the html out into the following components: the component groupings are as follows: the main input / "new-todo" (red in the image) the containing body of the todo list + the mark-all-complete button (purple in th...
Getting started with Svelte - Learn web development
re frameworks, and there are also less job opportunities. but it's advantages should be enough to make you interested to explore it. note: recently svelte has added official typescript support, one of its most requested features. we'll look at it later on in this tutorial series. we encourage you to go through the svelte tutorial for a really quick introduction to the basic concepts, before re
turning to this tutorial series to learn how to build something slightly more in-depth. it should take you about 30 minutes to complete. use cases svelte can be used to develop small pieces of an interface or whole applications. you can either start from scratch letting svelte drive your ui or you can incrementally integrate it into an existing application. nevertheless, svelte is particularly appr...
... as you can see, the <h1> label is automatically updated. behind the scenes, svelte created the javascript code to update the dom whenever the value of the name variable changes, without using any virtual dom or other complex reconciliation mechanism. note the use of : in on:click. that's svelte's syntax for listening to dom events. inspecting main.js: th...
Handling common HTML and CSS problems - Learn web development
onflicts are less likely. for example .audio-player ul a. validation for html, validation involves making sure all your tags are properly closed and nested, you are using a doctype, and you are using tags for their correct purpose. a good strategy is to validate your code regularly. one service that can do this is the w3c markup validation service, which allows you to point to your code, and re
turns a list of errors: css has a similar story — you need to check that your property names are spelled correctly, property values are spelled correctly and are valid for the properties they are used on, you are not missing any curly braces, and so on. the w3c has a css validator available too, for this purpose. linters another good option to choose is a so-called linter application, which not...
...uch plugins generally work: install atom (if you haven't got an up-to-date version already installed) — download it from the atom page linked above. go to atom's preferences... dialog (e.g. by choosing atom > preferences... on mac, or file > preferences... on windows/linux) and choose the install option in the left hand menu. in the search packages text field, type "lint" and press enter/re
turn to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-csslint plugin for linting css, and the linter-tidy plugin for linting html. after the packages have finished installing, try loading up an html file and a css file: you'll see any ...
Deploying our app - Learn web development
and our git and github page is a good place to start. we initialized our working directory as a git working directory earlier on. a quick way to verify this is to run the following command: git status you should get a status report of what files are being tracked, what files are staged, and so on — all terms that are part of the git grammar. if you get the error fatal: not a git repository re
turned, then the working directory is not a git working directory and you’ll need to initialise git using git init. now we have three tasks ahead of us: add any changes we’ve made to the stage (a special name for the place that git will commit files from). commit the changes to the repository. push the changes to github. to add changes, run the following command: git add . note ...
...ush our code to github; run the following command now: git push github master at this point you'll be prompted to enter a username and password before git will allow the push to be sent. this is because we used the https option rather than the ssh option, as seen in the screenshot earlier. for this you need your github username and then — if you do not have two-factor authentication (2fa)
turned on — your github password. we would always encourage you to use 2fa if possible, but bear in mind that if you do, you'll also need to use a "personal access token". github help pages has an excellent and simple walkthrough covering how to get one. note: if you are interested in using the ssh option, thereby avoiding the need to enter your username and password every time you push to gith...
Introducing a complete toolchain - Learn web development
apter 2, to tidy our code in this project. if you followed the directions in the installing prettier section then you might already have prettier installed. if not, we'll get you to install prettier as a global utility using the terminal right now. you can check whether you've already got it installed globally using the following command: prettier -v if installed, you'll get a version number re
turned like 2.0.2; if not, it'll re
turn something along the lines of "command not found". if this is the case, install it using the following command: npm install prettier -g now that prettier is installed, running and tidying your code can be done on the command line on an individual file basis from anywhere on your computer, for example: prettier --write ./src/index.html note: in the command ab...
...ode will live in src. making sure you are inside the root of the will-it-miss directory, enter the following command to start git’s source control functionality working on the directory: git init this means that you'll now be able to start storing revisions to the folder's contents, saving it to a remote repository, etc. more on this later! next, enter the following command to
turn your directory into an npm package, with the advantages that we discussed in the previous article: npm init --force this will create a default package.json file that we can configure later on if desired. the --force flag causes the command to instantly create a default package.json file without asking you all the usual questions about what contents you want it to have (as we saw previously)...
Adding phishing protection data providers
r. each data provider has a unique id number. the data provider with the id number 0 is the default data provider shipped with firefox. when installing a new provider, you should use the next unused number. to find an id number to use, you can build a loop that requests the value of browser.safebrowsing.provider.0.name, then browser.safebrowsing.provider.1.name, and so forth until no value is re
turned. then you can use that value. you can find examples of how to read and write preferences in the article adding preferences to an extension. required preferences browser.safebrowsing.provider.idnum.name a human-readable name for the data provider. browser.safebrowsing.provider.idnum.keyurl an url that re
turns a private key to be used for encrypting of other requests. browser.safeb...
... optional preferences browser.safebrowsing.provider.idnum.reporturl an url used for reporting when users visit phishing pages and whether or not they decided to heed the warning or to ignore it. ...
A bird's-eye view of the Mozilla framework
table, uuid(00000000-0000-0000-c000-000000000046)] interface nsisupports { void queryinterface(in nsiidref uuid, iid_is(uuid),retval] out nsqiresult result); [noscript, notxpcom] nsrefcnt addref(); [noscript, notxpcom] nsrefcnt release(); }; the uuid parameter to queryinterface() is the iid uniqely identifying the interface. if nsirdfnode doesn't support nsirdfliteral, it re
turns null and it's up to the client to choose an alternate course of action. the xpcom component keeps track of all interface pointers currently held by its clients using an internal reference count it increments via client calls to addref(). it is up to the client to call release() when it no longer needs the interface. release() decrements the reference count and then the object becomes a candidat...
...orts a gettarget() method for obtaining the nsirdfnode for a given resource and property. var link = tocds.gettarget(resource, nc_link, true); now that getlink() has the nsirdfnode for the link, it can call queryinterface() to check whether the nsirdfliteral is supported. link = link.queryinterface(components.interfaces.nsirdfliteral); if nsirdfliteral is supported, getlink() uses it to re
turn the value of the link. otherwise it re
turns null. if (link) re
turn link.value; else re
turn null; the document page for the link is displayed in thehelp viewer window. ...
Choosing the right memory allocator
ncludes extensions with binary components. see the xpcom string guide for additional information. ...
...ts. see the xpcom string guide for additional information. ns_alloc() == nsimemory::alloc() ns_realloc() == nsimemory::realloc() ns_free() == nsimemory::free() nsmemory::clone() (note: not part of nsimemory) see infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only re
turn valid memory buffers, and never re
turn null. allocating strings in xpcom code see "callee-allocated parameters" in the xpcom strings guide; use tonewcstring() or tonewunicode() to allocate strings that will be passed out. these methods convert ns*string to nsimemory allocated, unowned [pruni]char* buffers. do not use nscrt::strdup for re
turning values from an xpcom object, as that uses a different allocator. nspr memory allocators...
Debugging Frame Reflow
same level where it started. advanced reflow debugging the previously described technique dumps the data for every frame. sometimes the log is clearer if only the main frames are shown. the entries in the reflow log can be controlled on a frame level. for instance adding text 0 to the rules in reflow_rules.txt would hide the text entries from the reflow. ...
...he previously described technique dumps the data for every frame. sometimes the log is clearer if only the main frames are shown. the entries in the reflow log can be controlled on a frame level. for instance adding text 0 to the rules in reflow_rules.txt would hide the text entries from the reflow. ...
Debugging on Windows
tails. ...
...symbols if both your application and visual c++ hang shortly after launching the application under the debugger, you may be hitting a known deadlock in the way visual studio downloads debug symbols for the system libraries; see https://connect.microsoft.com/visualstudio/feedback/details/422970/hang-loading-rasapi32-pdb-when-using-symbol-server. there are two ways to work around this problem:
turn off automatic symbol downloading for system libraries: in tools > options > debugging > symbols, uncheck the microsoft symbol server. pre-load all the windows debug symbols. these instructions apply to visual studio 10 on windows 7; other software versions likely need to have file paths adjusted. locate the microsoft utility "symchk.exe" on your system (it will likely be in the installatio...
Callgraph
given the knowledge that evil() does evil things, one could then determine foo() also does evil things. ...
...given the knowledge that evil() does evil things, one could then determine foo() also does evil things. ...
Inner and outer windows
this article will try to explain the concepts of inner and outer windows. consider that when the user is looking at a document in a browser window, not only can the document the user is currently viewing change, but the document's contents can change. then add to that the concept of frames, whereby a document in a window can itself contain other documents, which in
turn can contain more documents. in order to represent these levels of complexity, two "types" of window need to be considered. these don't technically refer to windows as the user sees them, but rather a perspective on what the user is looking at. windows and the bfcache an outer window is a browsing context; that is, the actual environment in which a document is presented to the user. this may be a window or a tab, or it might b...
...ical" browser window. here's the trick, though: the inner window in essence pretends to be the outer window. if the document currently being displayed asks "what window am i in?", it gets the outer window as the answer. that lets the document interact with the "physical" window, while the outer window can keep track of all the documents (inner windows) it contains. in other words, window always re
turns the outer window. nested windows things become slightly more complex when you consider that documents can contain other documents. this happens, for example, when a document contains a <frame> or <iframe>. not only can the outermost document be navigated, but if the user clicks a link in one of the frames, that frame can navigate. this means there needs to be a hierarchy of outer and inner windo...
Listening to events on all tabs
oes not define the set of possible status codes. note: some status values are defined by nsitransport and nsisockettransport. amessage localized text corresponding to astatus. onrefreshattempted notification that a refresh or redirect has been requested in awebprogress for example, via a <meta http-equiv="refresh"> or an http refresh: header. if any registered progress listener re
turns false from this method then the attempt to refresh will be blocked. boolean onrefreshattempted( nsidomxulelement abrowser, nsiwebprogress webprogress, nsiuri arefreshuri, long amillis, boolean asameuri ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the new uri...
...otification. awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the new uri that awebprogress has requested redirecting to. amillis the delay (in milliseconds) before refresh. asameuri true if awebprogress is requesting a refresh of the current uri. false if awebprogress is requesting a redirection to a different uri. re
turn value true if the refresh may proceed. false if the refresh should be aborted. onlinkiconavailable notification that the site icon for a browser has been found. void onlinkiconavailable( nsidomxulelement abrowser, ); parameters abrowser the browser that fired the notification. ...
mach
here are a number of bugs and numerous areas for improvement. some larger known issues include: mintty (alternative terminal emulator on windows) doesn't work. text encoding issues (especially on windows where latin-1 is not the default system encoding). failed commands spew lots of extra error output, e.g. you will see a big mach error message when all that happened was an invoked command re
turned a non-0 exit code - possibly expectedly so in mozilla! generally, mach is known to work pretty well without issues for most people and works terribly for others with even the "basics" being quite unsatisfactory. how do i report bugs? bugs against the mach core can be filed in bugzilla in the firefox build system::mach core. most mach bugs are bugs in individual commands, not bugs in the c...
...text. this object holds state from the mach driver, including the current directory, a handle on the logging manager, the settings object, and information about available mach commands. the arguments registered with @commandargument are passed to your method as keyword arguments using the **kwargs calling convention. so, you should define default values for all of your method's arguments. the re
turn value from the @command method should be the integer exit code from the process. if not defined or none, 0 will be used. registering mach command providers once you've written a python module providing a mach command, you'll need to register it with mach. there are two ways to do this. if you have a single file, the easiest solution is probably to register it as a one-off inside build/mach_boo...
HTMLIFrameElement.executeScript()
thod of the htmliframeelement interface allows a specified script to be executed against a page loaded in the browser <iframe>. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); re
turn value a domrequest object that re
turns an onsuccess handler if the script is successfully executed against the loaded content, or an onerror handler if not. parameters script the script to be executed. options optional optionally, you can provide an origin or url for the script to be executed against. it's recommended that you include an origin or url, in order to ensure that the script i...
...if the script value is a promise, the result of the request will be the promise-resolved value. specifications not part of any specification. ...
HTMLIFrameElement.getContentDimensions()
its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. ...
...its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. ...
HTMLIFrameElement.getScreenshot()
ropped if necessary but will not be distorted vertically or horizontally. note: getscreenshot() waits for the event loop to go idle before it takes the screenshot. it won't wait more than 2000ms (this delay is defined by the gecko dom.browserelement.maxscreenshotdelayms preference). syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); re
turns a domrequest for handling the screenshot request. its request.onsuccess handler handles the success case (the screenshot is contained in request.result as a blob object), and its request.onerror handler handles the failure case. parameters maxwidth a number representing the maximum width of the screenshot in device pixels. maxheight a number representing the maximum height of the screens...
...ccess case (the screenshot is contained in request.result as a blob object), and its request.onerror handler handles the failure case. parameters maxwidth a number representing the maximum width of the screenshot in device pixels. maxheight a number representing the maximum height of the screenshot in device pixels. mimetype optional a mime type specifying the format of the image to be re
turned; if not specified, the default used is image/jpeg. use image/png to capture the alpha channel of the rendered result by re
turning a png-format image. this lets you get a transparent background for the content <iframe>. examples var browser = document.queryselector('iframe'); var request = browser.getscreenshot(100, 100); request.onsuccess = function() { var blob = request.result; var u...
HTMLIFrameElement.getStructuredData()
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 getstructureddata() method of the htmliframeelement interface retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and re
turns it as json. syntax var instanceofdomrequest = instanceofhtmliframeelement.getstructureddata(); re
turns a domrequest to handle the getstructureddata() request's success and error cases. if the request is successful, the request.result is a json object representation of all microdata contained on the page loaded in the browser. parameters none. examples var browser = document.queryselector...
... specification not part of any specification. ...
mozbrowseractivitydone
o 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 mozbrowseractivitydone event is fired when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. if the activity has a re
turnvalue set to true, then the activity is consumed when postresult or posterror is invoked on the activity by the receiving app. note: for activities where the receiving app's activity definition in its manifest does not include re
turnvalue or re
turnvalue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in firefox os 2.5. postresult and posterror calls m...
...ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: success a boolean that indicates whether the activity has completed successfully (true) or not (false). examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseractivitydone", function(event) { if(event.details.success) { console.log('activity completed successfully'); } else { c...
mozbrowsercontextmenu
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: clientx the x value of the coordinate that was clicked inside the browser <iframe>'s viewport. clienty the y value of the coordinate that was clicked inside the browser <iframe>'s viewport. systemtargets an array containing one or more menusystem objects (see the menusystem object, below), containing details of the standard me...
...ent the menu is associated with. uri a domstring. in the case of an image or video context menu, this is the src of the image or video clicked on to get the context menu. in the case of an link context menu, it is the link's href. text a domstring representing the text of the link clicked on, in the case of a link context menu. hasvideo a boolean. in the case of a video context menu, this re
turns true if the video has metadata and is bigger than 0 x 0, or false if not. action a domstring representing the action of a form, in the case of a form context menu. method a domstring representing the method of a form, in the case of a form context menu. name a domstring representing the name of a form, in the case of a form context menu. the menu object an object representing a custom m...
mozbrowsermetachange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value. this can be viewmode, theme-color, theme-group, or application-name. content a domstring representing the <meta> content attribute value, i.e. the content of the meta tag. type a domstring representing the type of meta change that this event object represents. this...
...r, theme-group, or application-name. content a domstring representing the <meta> content attribute value, i.e. the content of the meta tag. type a domstring representing the type of meta change that this event object represents. this can be added, changed, removed, or undefined. lang optional a domstring representing the <meta> name attribute value, if included. if not included, the value re
turned is undefined. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermetachange", function(event) { console.log("a meta tag has been " + event.details.type + ". its name is " + event.details.name + ", and its content is " + event.details.content + "."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowseric...
Browser API
ntlistener(), and dispatchevent(). htmliframeelement.sendmouseevent() sends a mouseevent to the <iframe>'s content. utility methods last, there are some utility methods, useful for apps that host a browser <iframe>. htmliframeelement.getstructureddata() retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and re
turns it as json. browser api methods removed in firefox 65 in firefox 65, several of the mozilla browser api methods were removed in an effort to cut down on domrequest usage in the browser, and remove the parts of the browser api that are no longer needed (it is used only by the firefox devtools at this point). see bug 1503070 for more details. the methods removed in firefox 65 are: htmlifram...
...string relative to the caret position will be highlighted. htmliframeelement.findnext() highlights the next or previous instance of a search result after a findall() search has been carried out. htmliframeelement.getcontentdimensions() retrieves the x and y dimensions of the content window. htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and re
turns it as json. htmliframeelement.getscreenshot() takes a screenshot of the browser <iframe>'s content. this is particularly useful to get thumbnails of tabs in a tabbed browser app. htmliframeelement.purgehistory() clears all the resources (cookies, localstorage, cache, etc.) associated with the browser <iframe>. htmliframeelement.sendtouchevent() sends a touchevent to the <iframe>'s content.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
90, 3491, 3492.) these new rfc's now make it possible for domain name servers to register non-ascii domain names and application/client vendors to implement standardized support for handling non-ascii characters in domain names. how idn works when a browser sees a host name such as http://developer.mozilla.org, it passes a request to the dns resolver service (usually built into an os), which in
turn sends a request to a nearest domain name server to re
turn an ip address that corresponds to the host name. this ip address is then used to connect to the web server in question. idn allows host/domain names with non-ascii characters for user input into a browser's location bar or url's embedded in web pages. at the network protocol level, there is no change in the restriction that only a subset ...
...ters used in idn to be drawn from unicode standard 3.2. it also defines how an application should process non-ascii characters in such a way to conform to existing host name character restrictions. how mozilla browsers handle non-ascii domain names unicode and nameprep when mozilla receives idn input from the user via the location bar or a request to process non-ascii host name links, it first
turns them into unicode, then normalizes the input string to make it conform to general uri requirement. the process will convert uppercase characters to lowercase ones (case folding), unify characters with multiple representation, e.g. conversion of half-width kana characters in japanese into full-width ones (normalization), eliminate prohibited characters (e.g. space), eliminate ambiguities in bi-d...
JavaScript Tips
aces unless you need to access methods and properties of that interface. you do not have to query interfaces to compare objects, nor to pass objects as parameters (this is different from c++, where you do have to query interfaces in both cases). don't call queryinterface unless you expect to succeed. instead, use instanceof, e,g,: if (target instanceof components.interfaces.nsirdfresource) re
turn target.value; if (target instanceof components.interfaces.nsirdfliteral) re
turn target.value; re
turn null; don't test the re
turn value of queryinterface, it always re
turns the original variable if it succeeds. xpconnect knows all about tearoffs and modifies the object that you queryinterface or instanceof to cache all its known interfaces. when passing an object to an xpcom method it is he...
...rface method. however, in javascript this is quite simple even in the case of a weak reference which in c++ requires a helper class: var weakobserver = { queryinterface: function queryinterface(aiid) { if (aiid.equals(components.interfaces.nsiobserver) || aiid.equals(components.interfaces.nsisupportsweakreference) || aiid.equals(components.interfaces.nsisupports)) re
turn this; throw components.results.ns_nointerface; }, observe: function observe(asubject, atopic, astate) { } } when declaring xpcom methods, try to use the same names for method parameters as are used in the interface definition. dom elements dom elements are just xpcom objects with some of the interfaces precached. don't call getattribute to see if an attribute exists, call hasa...
InstallListener
onnewinstall() called when a new instance of addoninstall is created, primarily so ui can display some kind of progress for all installs. void onnewinstall( in addoninstall install ) parameters install the addoninstall representing the install ondownloadstarted() called when downloading begins for an add-on install. only called for add-ons that need to be downloaded. a listener may re
turn false to cancel the download. void ondownloadstarted( in addoninstall install ) parameters install the addoninstall representing the install ondownloadprogress() called as data is received during a download. check the progress property for the amount of data downloaded and the maxprogress property for the total data expected. a listener may re
turn false to cancel the download. void on...
... ) parameters install the addoninstall representing the install ondownloadfailed() called if there is some error downloading the add-on. only called for add-ons that need to be downloaded. void ondownloadfailed( in addoninstall install ) parameters install the addoninstall representing the install oninstallstarted() called when installation of an add-on begins. a listener may re
turn false to cancel the install. void oninstallstarted( in addoninstall install ) parameters install the addoninstall representing the install oninstallended() called when installation of an add-on is complete. the newly installed add-on may require a restart in order to become active. void oninstallended( in addoninstall install in addon addon ) parameters install the addoninsta...
DownloadList
mise<array<download>> getall(); promise add(download adownload); promise remove(download adownload); promise addview(object aview); promise removeview(object aview); void removefinished([optional] function afilterfn); methods getall() retrieves a snapshot of the downloads that are currently in the list. the re
turned array does not change when downloads are added or removed, though the download objects it contains are still updated in real time. promise<array<download>> getall(); parameters none. promise resolves to an array of download objects. add() adds a new download to the end of the items list. note: when a download is added to the list, its onchange event is registered by the list, thus it cannot...
...hout keeping partial data. a filter function may be specified to remove only a subset of those downloads. this method finalizes each removed download, ensuring that any partially downloaded data associated with it is also removed. promise removefinished( function afilterfn ); parameters afilterfn the filter function is called with each download as its only argument, and should re
turn true to remove the download and false to keep it. this parameter may be null or omitted to have no additional filter. ...
FxAccountsProfileClient.jsm
irefox profiler server api. components.utils.import("resource://gre/modules/fxaccountsprofileclient.jsm"); creating a new fxaccountsprofileclient new fxaccountsprofileclient(object options); method overview fetchprofile(); attributes serverurl url profiler server url. token string bearer token. constructor fxaccountsprofileclient() creates and re
turns a new fxaccountsprofileclient object. fxaccountsprofileclient fxaccountsprofileclient( object options string serverurl, string token ); parameters serverurl - firefox profile server url. token - firefox accounts oauth bearer token. re
turn value a newly created fxaccountsprofileclient object implementing the methods described in this article. methods fetchprofile() fetches firefo...
... rejects: fxaccountsprofileclienterror - profile client error. ...
Interfacing with the Add-on Repository
call a shownotification() method with some parameters that we'll look at shortly when we get to our shownotification() method below. the important thing to note is that this will handle the failure case. handling successful requests the callback object's searchsucceeded() method gets called when a search completes successfully. it receives a list of the matching addons, the number of add-ons re
turned, and the total number of add-ons that matched the query (in case the re
turned number is smaller than the requested number, for example). for example: searchsucceeded: function(addons, addoncount, totalresults) { var num = math.floor(math.random() * addoncount); this.shownotification("would you like to try the " + addons[num].name + " addon?", "install", addons[num].install); },...
...ed the query (in case the re
turned number is smaller than the requested number, for example). for example: searchsucceeded: function(addons, addoncount, totalresults) { var num = math.floor(math.random() * addoncount); this.shownotification("would you like to try the " + addons[num].name + " addon?", "install", addons[num].install); }, this routine randomly selects one of the re
turned add-ons, then calls the previously mentioned shownotification() routine, passing in as parameters a prompt including the name of the re
turned add-on, a label for the button to show in the notification ("install"), and the addoninstall object that can be used with the add-on manager api to install the add-on. installing the add-on the shownotification() routine displays a notification box offe...
OS.File.Info
ility to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code. global object os.file.info methods object tomsg(in os.file.info value) os.file.tomsg convert an instance of os.file.info to a form that can be serialized and transmitted between threads or processes. object tomsg( in os.file.info value ) arguments re
turns an object with the same fields as value but that may be serialized and transmitted between threads or processes. value an instance of os.file.info. instances of os.file.info cross-platform attributes isdir true if the file is a directory, false otherwise. issymlink true if the false is a symbolic link, false otherwise. (as of firefox 38 this is always true on all...
...ialized and transmitted between threads or processes. value an instance of os.file.info. instances of os.file.info cross-platform attributes isdir true if the file is a directory, false otherwise. issymlink true if the false is a symbolic link, false otherwise. (as of firefox 38 this is always true on all systems, this is a bug: bugzilla 1145885) (on windows this re
turns false for hard links) size the number of bytes in the file. creationdate deprecated in bugzilla :: bug 807875. before deprecation, this used to be the date at which the file was created on windows and mac os x, as a javascript date object. on unix systems it was re
turning the last modified date and thus it was deprecated. there is talk of reinstating this with proper func...
Mozilla Style System
de responsible for the loading and parsing of css style sheets, and the computation of computed values for all css properties. the handling of those computed values is the responsibility of other parts of the code. architecture the style system is split in half rather neatly. in one half (the backend) are the sources of specified style data, and in the other half (the frontend) is the code that
turns the specified values into computed values. the barrier between these two halves consists of three abstract interfaces, plus some smaller structures associated with some methods on each: nsistylesheet nsistylesheet represents what one would think of as a style sheet: the in-memory representation of a css file or other source of style data. some style sheets are managed by the document; some ...
...ptimizations in the style system. most callers who interact with the style system do so using the style structs. the style context has a getter for each struct, and nsiframe, which represents the concept of a css box (or rendering object), also has getters that forward to the frame's style context. thus, typical calling code looks like this: if (aframe->getstyledisplay()->mopacity < 1.0f) re
turn pr_true; or like this: const nsstyleposition *stylepos = aframe->getstyleposition(); if (stylepos->mwidth.getunit() == estyleunit_coord) { nscoord w = stylepos->mwidth.getcoordvalue(); ... } else if (stylepos->mwidth.getunit() == estyleunit_percent) { ... rule tree style data computation css style sheet backend loading parsing data structures cascading html mapped attribut...
Investigating leaks using DMD heap scan mode
pecifies that we want a dmd log to be taken very late in xpcom shutdown, and the location for that log to be saved. like with the cc log, we want this log very late to avoid as many non-leaking things as possible. moz_dmd_log_process=tab: as with the cc, this means that we only want these logs in content processes, in order to make shutdown faster. the allowed values here are the same as those re
turned by xre_getprocesstype(), so adjust as needed. finally, the --dmd option need to be passed in so that dmd will be run. --mode=scan is needed so that when we get a dmd log the entire contents of each block of memory is saved for later analysis. with that command line in hand, you can start firefox. be aware that this may take multiple minutes if you have optimization disabled. once it has sta...
...ional options to affect how the results are displayed. “-sfl 10000 -a” is useful. the -sfl 10000 tells it to not truncate stack frames, and -a tells it to not display generic frames related to the allocator. caveat: i think block_analyzer.py does not attempt to clamp the address you pass into it, so if it is an offset from the start of the block, it won’t find it. block_analyzer.py will re
turn a series of entries that look like this (with the [...] indicating where i have removed things): 0x7f089306b000 size = 4096 bytes at byte offset 2168 nsattrandchildarray::growby[...] nsattrandchildarray::insertchildat[...] [...] 0x7f089306b000 is the address of the block that contains $leakaddr. 144 bytes is the size of that block. that can be useful for confirming your guess about what c...
JS::PerfMeasurement
" perfmeasurement::num_measurable_events this constant equals the total number of events defined by the api - not necessarily the total number of events that a particular os allows you to measure. (at time of writing, linux allows all the above events to be measured, and we don't have back ends for any other operating system. static bool perfmeasurement::canmeasuresomething() this class method re
turns true if and only if some -- not necessarily all -- events can be measured by the current build of spidermonkey, running on the current os. at present, it re
turns true on linux when the <linux/perf_event.h> api is available (kernel 2.6.31 or later), and false everywhere else. perfmeasurement::perfmeasurement(eventmask tomeasure) the constructor creates a new profiling object, which measures some...
...rface, and you want to benchmark only part of your execution time but make the results available to javascript, you can declare a bare jsval argument in your .idl file and have javascript pass a perfmeasurement object that it created in that argument slot. the jsval you receive points to a javascript wrapper object. to extract the c++-level perfmeasurement object, call this function. it will re
turn null if javascript passed in something with the wrong dynamic type. jsobject* js::registerperfmeasurement(jscontext* cx, jsobject* global) you shouldn't need to use this function, but we mention it for completeness. it initializes the javascript wrapper interface for this api and pokes the constructor function into the global object you provide. ...
Power profiling overview
iod. strictly speaking, such a computation gives the average power but this is often referred to as just the power when context makes it clear. in the context of computing, a fully-charged mobile device battery (as found in a laptop or smartphone) holds a certain amount of energy, and the speed at which that stored energy is depleted depends on the power consumption of the mobile device. that in
turn depends on the software running on the device. web browsers are popular applications and can be power-intensive, and therefore can significantly affect battery life. as a result, it is worth optimizing (i.e. reducing) the power consumption caused by firefox and firefox os. intel processor basics processor layout the following diagram (from the intel power governor documentation) shows how mach...
... firefox's power consumption is high. "high" can most easily be gauged by comparing against other browsers. use power measurements or estimates (e.g. via tools/power/rapl, or mach power on mac, or intel power gadget on windows) for the comparisons. avoid lower-quality measurements, especially activity monitor's "energy impact". try using differential profiling to narrow down the cause. try
turning hardware acceleration on or off; e10s on or off; flash on or off. try putting the relevant tab in the foreground vs. in the background. if the problem manifests on a particular website, try saving a local copy of the site and then manually removing html elements to see if a particular page feature is causing the problem many power problems are caused by either high cpu usage or hig...
Profiling with Xperf
t; if they don't, it's a silent error.) quick start all these tools will live, by default, in c:\program files\microsoft windows performance toolkit. either run these commands from there, or add the directory to your path. you will need to use an elevated command prompt to start or stop profiling. start recording data: xperf -on latency -stackwalk profile "latency" is a special provider name that
turns on a few predefined kernel providers; run "xperf -providers k" to view a full list of providers and groups. you can combine providers, e.g., "xperf -on diageasy+file_io". "-stackwalk profile" tells xperf to capture a stack for each profile event; you could also do "-stackwalk profile+file_io" to capture a stack on each cpu profile tick and each file io completion event. stop: xperf -d out.etl vi...
...can be dragged left and right to change the grouping -- for example, drag it to the left of the module column to have grouping happen only by process (stuff that's to the left), so that you get symbols in order of weight, regardless of what module they're in. dragging the columns around will change grouping in various ways; experiment to get the data that you're looking for. also experiment with
turning columns on and off; removing a column will allow data to be aggregated without considering that column's contributions. disabling all but one core will make the numbers add up to 100%. this can be done by running 'msconfig' and going to advance options from the "boot" tab. building firefox to get good data from a firefox build, it is important to build with the following options in your mozc...
Reporting a Performance Problem
on the button and remove it from the toolbar when you're done with it. using the profiler when enabled, the profiler toolbar button is not recording by default. recording can be done by clicking on the toolbar icon to open its panel. make sure to choose an appropriate setting for the recording (if you're not sure, choose firefox platform), and then choosing "start recording". the toolbar icon
turns blue when it is recording. the profiler uses a fixed size buffer to store sample data. when it runs out of space in its buffer, it discards old entries so you may want to increase the buffer size if you find you are unable to capture the profile quickly enough after you notice a performance problem. if you choose custom settings (and then clicking edit settings) for the profiler, you can adjust...
...will be a button in the top right labeled 'publish' which will allow you to upload this profile and once completed will write out a link. before uploading, the publish button asks you what data you'd like to publish to our servers. note that while it's possible to strip profiles of potentially privacy sensitive information, the less information a profile contains, the harder it is to analyze and
turn into actionable data. once uploaded, copy permalink url to your clipboard by right clicking and add the profile url to a bug for your performance problem and/or send it to the appropriate person. try to give some context about what you were doing when the performance problem arose such as the url you were viewing and what actions were you doing (ex. scrolling on gmail.com). viewing addon pe...
TraceMalloc
0 514 63910 3.53 nshtmlvalue 139 7846 1215 68734 1076 60888 3.36 htmlcontentsink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. ...
... 3.36 htmlcontentsink 6 4816 12 57782 6 52966 2.92 uncategorized.pl, which lists all the void* allocations (the ones that couldn't be categorized by type), sorted by size. also, your javascript can call the following dom window methods: tracemallocdisable() -
turn off tracing, first flushing any buffered log events for all log files. tracemallocenable() -
turn on tracing. tracemallocopenlogfile(filename) - open a new log file and re
turn its log file descriptor (or -1 on error). tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, re
turning the previous fd (so you can maintain a number of open files; keep their fds in a js array!). tracemalloccloselogfd(logfd) - close the log file identified by logfd, flushing i...
Optimizing Applications For NSPR
r windows 3.1 applications for cross platform consistency, but do not expect to see real 64 bit file offset behavior. on windows 3.1, when nspr detects a value in a 64 bit file offset greater than 32bit significance, it terminates with an assert. the general rules of 16 bit large model memory restrictions apply to applications using nspr on windows 3.1. the nspr process creation api functions re
turn an error when invoked on windows 3.1. functions called in an application by a shared library require an additional function prolog. the prolog is presented in the macro <tt>pr_callback</tt>. for any function made available to any shared library (most likely passed in as a function pointer), that function must have the <tt>pr_callback</tt> qualifier. nspr functions are normally declared <tt>__cd...
...ion prolog. the prolog is presented in the macro <tt>pr_callback</tt>. for any function made available to any shared library (most likely passed in as a function pointer), that function must have the <tt>pr_callback</tt> qualifier. nspr functions are normally declared <tt>__cdecl</tt>. these declarations are hidden in the <tt>pr_extern()</tt> declarations in nspr's header files. nspr functions re
turning floating point types and structs by value, including the derived types print64, are declared <tt>__pascal</tt>. these different declarations are to accommodate restrictions in watcom's c/c++ version 11.0 and 11.0a compiler. windows 3.1 does not provide a non-blocking file i/o interface. nspr's file i/o is done using windows 3.1's synchronous file i/o api. the nspr file i/o apis may cause a th...
I/O Functions
ation; use condition variables instead. a pollable event has two states: set and unset. events are not queued, so there is no notion of an event count. a pollable event is either set or unset. pr_newpollableevent pr_destroypollableevent pr_setpollableevent pr_waitforpollableevent one can call pr_poll with the pr_poll_read flag on a pollable event. whe the pollable event is set, pr_poll re
turns the the pr_poll_read flag set in the out_flags. manipulating layers file descriptors may be layered. for example, ssl is a layer on top of a reliable bytestream layer such as tcp. each type of layer has a unique identity, which is allocated by the runtime. the layer implementor should associate the identity with all layers of that type. it is then possible to scan the chain of layers and find...
...sting stack of layers. the file descriptor of the top layer can be passed to nspr i/o functions, which invoke the appropriate version of the i/o methods polymorphically. nspr defines three identities: #define pr_invalid_io_layer (prdescidentity)-1 #define pr_top_io_layer (prdescidentity)-2 #define pr_nspr_io_layer (prdescidentity)0 pr_invalid_io_layer: an invalid layer identify (for error re
turn). pr_top_io_layer: the identity of the top of the stack. pr_nspr_io_layer: the identity for the layer implemented by nspr. pr_top_io_layer may be used as a shorthand for identifying the topmost layer of an existing stack. for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stack), my_...
PL_HashTableAdd
the specified key and value to the hash table. syntax #include <plhash.h> plhashentry *pl_hashtableadd( plhashtable *ht, const void *key, void *value); parameters the function has the following parameters: ht a pointer to the the hash table to which to add the entry. key a pointer to the key for the entry to be added. value a pointer to the value for the entry to be added. re
turns a pointer to the new entry. description add a new entry with the specified key and value to the hash table. if an entry with the same key already exists in the table, the freeentry function is invoked with the ht_free_value flag. you can write your freeentry function to free the value of the specified entry if the old value should be freed. the default freeentry function does not free the va...
...iption add a new entry with the specified key and value to the hash table. if an entry with the same key already exists in the table, the freeentry function is invoked with the ht_free_value flag. you can write your freeentry function to free the value of the specified entry if the old value should be freed. the default freeentry function does not free the value of the entry. pl_hashtableadd re
turns null if there is not enough memory to create a new entry. it doubles the number of buckets if the table is overloaded. ...
PRFileMap
then sections of the file can be mapped into memory by passing the prfilemap pointer to pr_memmap. the memory-mapped file object is closed by passing the prfilemap pointer to pr_closefilemap. ...
...then sections of the file can be mapped into memory by passing the prfilemap pointer to pr_memmap. the memory-mapped file object is closed by passing the prfilemap pointer to pr_closefilemap. ...
PRLinger
syntax #include <prio.h> typedef struct prlinger { prbool polarity; printervaltime linger; } prlinger; fields the structure has the following fields: polarity polarity of the option's setting: pr_false means the option is off, in which case the value of linger is ignored. pr_true means the option is on, and the value of linger will be used to determine how long pr_close waits before re
turning. linger time (in printervaltime units) to linger before closing if any data remain in the socket send buffer. description by default, pr_close re
turns immediately, but if there are any data remaining in the socket send buffer, the system attempts to deliver the data to the peer. the pr_sockopt_linger socket option, with a value represented by a structure of type prlinger, makes it possible ...
... if polarity is set to pr_true and linger is set to 0 (pr_interval_no_wait), the runtime aborts the connection when it is closed and discards any data remaining in the socket send buffer. ...
PR_Accept
n has the following parameters: fd a pointer to a prfiledesc object representing the rendezvous socket on which the caller is willing to accept new connections. addr a pointer to a structure of type prnetaddr. on output, this structure contains the address of the connecting entity. timeout a value of type printervaltime specifying the time limit for completion of the accept operation. re
turns the function re
turns one of the following values: upon successful acceptance of a connection, a pointer to a new prfiledesc structure representing the newly accepted connection. if unsuccessful, null. further information can be obtained by calling pr_geterror. description the socket fd is a rendezvous socket that has been bound to an address with pr_bind and is listening for connections ...
...ept more connections. if the addr parameter is not null, pr_accept stores the address of the connecting entity in the prnetaddr object pointed to by addr. pr_accept blocks the calling thread until either a new connection is successfully accepted or an error occurs. if the timeout parameter is not pr_interval_no_timeout and no pending connection can be accepted before the time limit, pr_accept re
turns null with the error code pr_io_timeout_error. ...
PR_AtomicAdd
description atomically add a 32 bit value. ...
... description atomically add a 32 bit value. ...
PR_CEnterMonitor
enters the lock associated with a cached monitor. syntax #include <prcmon.h> prmonitor* pr_centermonitor(void *address); parameter the function has the following parameter: address a reference to the data that is to be protected by the monitor. this reference must remain valid as long as there are monitoring operations being performed. re
turns the function re
turns one of the following values: if successful, the function re
turns a pointer to the prmonitor associated with the value specified in the address parameter. if unsuccessful (the monitor cache needs to be expanded and the system is out of memory), the function re
turns null. description pr_centermonitor uses the value specified in the address parameter to find a monitor in the monitor cache, then enters the lock assoc...
...ith the monitor. if no match is found, an available monitor is associated with the address and the monitor's entry count is incremented (so it has a value of one). if a match is found, then either the calling thread is already in the monitor (and this is a reentrant call) or another thread is holding the monitor's mutex. in the former case, the entry count is simply incremented and the function re
turns. in the latter case, the calling thread is likely to find the monitor locked by another thread and waits for that thread to exit before continuing. note: pr_centermonitor and pr_cexitmonitor must be paired--that is, there must be an exit for every entry--or the object will never become available for any other thread. ...
PR_CExitMonitor
if unsuccessful, pr_failure. ...
... if unsuccessful, pr_failure. ...
PR_CancelJob
causes a previously queued job to be canceled. ...
... causes a previously queued job to be canceled. ...
PR_CloseFileMap
if the memory region is not successfully unmapped, pr_failure. ...
... if the memory region is not successfully unmapped, pr_failure. ...
PR_CloseSemaphore
closes a specified semaphore. ...
... closes a specified semaphore. ...
PR_ConnectContinue
syntax #include <prio.h> prstatus pr_connectcontinue( prfiledesc *fd, print16 out_flags); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. out_flags the out_flags field of the poll descriptor re
turned by pr_poll(). re
turns if the nonblocking connect has successfully completed, pr_connectcontinue re
turns pr_success. if pr_connectcontinue() re
turns pr_failure, call pr_geterror(): - pr_in_progress_error: the nonblocking connect is still in progress and has not completed yet. the caller should poll the file descriptor for the in_flags pr_poll_write|pr_poll_except and retry pr_connectcontinue later when pr_poll() re
turns. - other errors: the nonblocking connect has failed with this error code. de...
...xcept and retry pr_connectcontinue later when pr_poll() re
turns. - other errors: the nonblocking connect has failed with this error code. description continue a nonblocking connect. after a nonblocking connect is initiated with pr_connect() (which fails with pr_in_progress_error), one should call pr_poll() on the socket, with the in_flags pr_poll_write | pr_poll_except. when pr_poll() re
turns, one calls pr_connectcontinue() on the socket to determine whether the nonblocking connect has completed or is still in progress. repeat the pr_poll(), pr_connectcontinue() sequence until the nonblocking connect has completed. ...
PR_CreateFileMap
object representing the file that is to be mapped to memory. size size of the file specified by fd. prot protection option for read and write accesses of a file mapping. this parameter consists of one of the following options: pr_prot_readonly. read-only access. pr_prot_readwrite. readable, and write is shared. pr_prot_writecopy. readable, and write is private (copy-on-write). ...
...private (copy-on-write). re
turns if successful, a file mapping of type prfilemap. if unsuccessful, null. description the prfilemapprotect enumeration used in the prot parameter is defined as follows: typedef enum prfilemapprotect { pr_prot_readonly, pr_prot_readwrite, pr_prot_writecopy } prfilemapprotect; pr_createfilemap only prepares for the mapping a file to memory. the re
turned file-mapping object must be passed to pr_memmap to actually map a section of the file to memory. the file-mapping object should be closed with a pr_closefilemap call when it is no longer needed. ...
PR_CreateThread
oid *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). start a pointer to the thread's root function, which is called as the root of the new thread. re
turning from this function is the only way to terminate a thread. arg a pointer to the root function's only parameter. nspr does not assess the type or the validity of the value passed in this parameter. priority the initial priority of the newly created thread. scope specifies your preference for making the thread local (pr_local_thread), global (pr_global_thread) or global bound (pr_global_bou...
...ead). however, nspr may override this preference if necessary. state specifies whether the thread is joinable (pr_joinable_thread) or unjoinable (pr_unjoinable_thread). stacksize specifies your preference for the size of the stack, in bytes, associated with the newly created thread. if you pass zero in this parameter, pr_createthread chooses the most favorable machine-specific stack size. re
turns the function re
turns one of the following values: if successful, a pointer to the new thread. this pointer remains valid until the thread re
turns from its root function. if unsuccessful, (for example, if system resources are unavailable), null. description if you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the...
PR_GMTParameters
re
turns the time zone offset information that maps the specified prexplodedtime to gmt. note: since this function requires gmt as input, its primary use is as "filler" for cases in which you need a do-nothing callback. syntax #include <prtime.h> prtimeparameters pr_gmtparameters ( const prexplodedtime *gmt); parameter gmt a pointer to the clock/calendar time whose offsets are to be determined. this time should be specified in gmt. re
turns a time parameters structure that expresses the time zone offsets at the specified time. description this is a frequently-used time parameter callback function. you don't normally call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime(). ...
...s are to be determined. this time should be specified in gmt. re
turns a time parameters structure that expresses the time zone offsets at the specified time. description this is a frequently-used time parameter callback function. you don't normally call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime(). this is a trivial function; for any input, it re
turns a prtimeparameters structure with both fields set to zero. ...
PR_GetConnectStatus
get the completion status of a nonblocking connection. syntax prstatus pr_getconnectstatus(const prpolldesc *pd); parameter the function has the following parameter: pd a pointer to a prpolldesc satructure whose fd field is the socket and whose in_flags field must contain pr_poll_write and pr_poll_except. re
turns the function re
turns one of these values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. if pr_geterror re
turns pr_in_progress_error, the nonblocking connection is still in progress and has not completed yet.other errors indicate that the connection has failed. description after pr_connect on a nonblocking socket fails with pr_in_progress_error, you may wait for the connection to complete by cal...
...pr_geterror re
turns pr_in_progress_error, the nonblocking connection is still in progress and has not completed yet.other errors indicate that the connection has failed. description after pr_connect on a nonblocking socket fails with pr_in_progress_error, you may wait for the connection to complete by calling pr_poll on the socket with the in_flags pr_poll_write | pr_poll_except. when pr_poll re
turns, call pr_getconnectstatus on the socket to determine whether the nonblocking connect has succeeded or failed. ...
PR_GetLibraryName
constructs a full library path name. syntax #include <prlink.h> char* pr_getlibraryname ( const char *dir, const char *lib); parameters the function has these parameters: dir a null-terminated string representing the path name of the library, as re
turned by pr_getlibrarypath. lib the leaf name of the library of interest. re
turns if successful, re
turns a new character string containing a constructed path name. in case of error, re
turns null. description this function constructs a full path name from the specified directory name and library name. the constructed path name refers to the actual dynamically loaded library. it is suitable for use in the pr_loadlibrary call. this function does not test for existence of the specified file, it just constructs the full filename.
...me and library name. the constructed path name refers to the actual dynamically loaded library. it is suitable for use in the pr_loadlibrary call. this function does not test for existence of the specified file, it just constructs the full filename. the way the name is constructed is system dependent. if sufficient storage cannot be allocated to contain the constructed path name, the function re
turns null. storage for the result is allocated by the runtime and becomes the responsibility of the caller. when it is no longer used, free it using pr_freelibraryname. ...
PR_GetSpecialFD
gets the file descriptor that represents the standard input, output, or error stream. syntax #include <prio.h> prfiledesc* pr_getspecialfd(prspecialfd id); parameter the function has the following parameter: id a pointer to an enumerator of type prspecialfd, indicating the type of i/o stream desired: pr_standardinput, pr_standardoutput, or pr_standarderror. re
turns if the id parameter is valid, pr_getspecialfd re
turns a file descriptor that represents the corresponding standard i/o stream. otherwise, pr_getspecialfd re
turns null and sets the error to pr_invalid_argument_error. description type prspecialfd is defined as follows: typedef enum prspecialfd{ pr_standardinput, pr_standardoutput, pr_standarderror } prspecialfd; #define pr_stdin pr_getspecialfd(pr_standardi...
... re
turns null and sets the error to pr_invalid_argument_error. description type prspecialfd is defined as follows: typedef enum prspecialfd{ pr_standardinput, pr_standardoutput, pr_standarderror } prspecialfd; #define pr_stdin pr_getspecialfd(pr_standardinput) #define pr_stdout pr_getspecialfd(pr_standardoutput) #define pr_stderr pr_getspecialfd(pr_standarderror) file descriptors re
turned by pr_getspecialfd are owned by the runtime and should not be closed by the caller. ...
PR_Interrupt
sets the interrupt request for a target thread. syntax #include <prthread.h> prstatus pr_interrupt(prthread *thread); parameter pr_interrupt has the following parameter: thread the thread whose interrupt request you want to set. re
turns the function re
turns one of the following values: if the specified thread is currently blocked, pr_success. otherwise, pr_failure. description the purpose of pr_interrupt is to request that a thread performing some task stop what it is doing and re
turn to some control point. it is assumed that a control point has been mutually arranged between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the c...
...ntrol point has been mutually arranged between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change in plans. the interrupt request remains in the thread's state until it is delivered exactly once or explicitly canceled. the interrupted thread re
turns pr_failure (-1) with an error code (see pr_geterror) for blocking operations that re
turn a prstatus (such as i/o operations, monitor waits, or waiting on a condition). to check whether the thread was interrupted, compare the result of pr_geterror with pr_pending_interrupt_error. pr_interrupt may itself fail if the target thread is invalid. bugs pr_interrupt has the following limitations and k...
PR_JoinJob
blocks the current thread until a job has completed. ...
... blocks the current thread until a job has completed. ...
PR_JoinThread
blocks the calling thread until a specified thread terminates. syntax #include <prthread.h> prstatus pr_jointhread(prthread *thread); parameter pr_jointhread has the following parameter: thread a valid identifier for the thread that is to be joined. re
turns the function re
turns one of the following values: if successful, pr_success if unsuccessful--for example, if no joinable thread can be found that corresponds to the specified target thread, or if the target thread is unjoinable--pr_failure. ...
... successful, pr_success if unsuccessful--for example, if no joinable thread can be found that corresponds to the specified target thread, or if the target thread is unjoinable--pr_failure. description pr_jointhread is used to synchronize the termination of a thread. the function is synchronous in that it blocks the calling thread until the target thread is in a joinable state. pr_jointhread re
turns to the caller only after the target thread re
turns from its root function. pr_jointhread must not be called until after pr_createthread has re
turned. if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's responsibility to ensure that pr_createthread has completed. several threads cannot wait for the same thread to complete. one of the calling threads op...
PR_LoadLibrary
loads a referenced library. syntax #include <prlink.h> prlibrary* pr_loadlibrary(const char *name); parameters the function has this parameter: name a platform-dependent character array that names the library to be loaded, as re
turned by pr_getlibraryname. re
turns if successful, re
turns a reference to an opaque prlibrary object. if the operation fails, re
turns null. use pr_geterror to find the reason for the failure. description this function loads and re
turns a reference to the specified library. ...
...tion has this parameter: name a platform-dependent character array that names the library to be loaded, as re
turned by pr_getlibraryname. re
turns if successful, re
turns a reference to an opaque prlibrary object. if the operation fails, re
turns null. use pr_geterror to find the reason for the failure. description this function loads and re
turns a reference to the specified library. the re
turned reference becomes the library's identity. the function suppresses duplicate loading if the library is already known by the runtime. each call to pr_loadlibrary must be paired with a corresponding call to pr_unloadlibrary in order to re
turn the runtime to its original state. ...
PR_LocalTimeParameters
description this is a frequently-used time parameter callback function. you don't normally call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime(). ...
... description this is a frequently-used time parameter callback function. you don't normally call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime(). ...
PR_NewThreadPrivateIndex
if the total number of indices exceeds 128, pr_failure. ...
...dprivatedtor destructor); parameters pr_newthreadprivateindex has the following parameters: newindex on output, an index that is valid for all threads in the process. you use this index with pr_setthreadprivate and pr_getthreadprivate. destructor specifies a destructor function prthreadprivatedtor for the private data associated with the index. this function can be specified as null. re
turns the function re
turns one of the following values: if successful, pr_success. if the total number of indices exceeds 128, pr_failure. description if pr_newthreadprivateindex is successful, every thread in the same process is capable of associating private data with the new index. until the data for an index is actually set, the value of the private data at that index is null. you pass thi...
PR_NormalizeTime
adjusts the fields of a clock/calendar time to their proper ranges, using a callback function. syntax #include <prtime.h> void pr_normalizetime ( prexplodedtime *time, prtimeparamfn params); parameters the function has these parameters: time a pointer to a clock/calendar time in the prexplodedtime format. params a time parameter callback function. re
turns nothing; the time parameter is altered by the callback function. description this function adjusts the fields of the specified time structure using the specified time parameter callback function, so that they are in the proper range. call this function in these situations: to normalize a time after performing arithmetic operations directly on the field values of the calendar time object. for example, if you have a ] ...
...y "forty days from 3 march 1998", you can simply add 40 to the tm_mday field and then call pr_normalizetime(). to calculate the optional field values tm_wday and tm_yday. for example, suppose you want to compute the day of week for 3 march 1998. you can set tm_mday to 3, tm_month to 2, and tm_year to 1998, and all the other fields to 0, then call pr_normalizetime() with pr_gmtparameters. on re
turn, tm_wday (and tm_yday) are set for you. to convert from one time zone to another. for example, if the input argument time is in time zone a and the input argument params represents time zone b, when pr_normalizetime() re
turns, time will be in time zone b. ...
PR_NotifyCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure. ...
... if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure. ...
PR_PopIOLayer
removes a layer from the stack. syntax #include <prio.h> prfiledesc *pr_popiolayer( prfiledesc *stack, prdescidentity id); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack from which the specified layer is to be removed. id identity of the layer to be removed from the stack. re
turns the function re
turns one of the following values: if the layer is successfully removed from the stack, a pointer to the removed layer. if the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function re
turns null with the error code pr_invalid_argument_error. description pr_popiolayer pops the specified layer from the stack. if the object to be removed is found, pr_popiolayer ret...
...xample, the bottommost layer), the function re
turns null with the error code pr_invalid_argument_error. description pr_popiolayer pops the specified layer from the stack. if the object to be removed is found, pr_popiolayer re
turns a pointer to the removed object the object then becomes the responsibility of the caller. even if the identity indicates the top layer of the stack, the reference re
turned is not the file descriptor for the stack and that file descriptor remains valid. in other words, stack continues to point to the top of the stack after the function re
turns. ...
PR_PostSemaphore
increments the value of a specified semaphore. ...
... increments the value of a specified semaphore. ...
PR_PushIOLayer
pr_pushiolayer( prfiledesc *stack, prdescidentity id, prfiledesc *layer); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack. id a prdescidentity object for the layer on the stack above which the new layer is to be added. layer a pointer to a prfiledesc object representing the new layer to be added to the stack. re
turns the function re
turns one of the following values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_geterror to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing sta...
...ay be pushed onto an existing stack of file descriptors at any time. the new layer is inserted into the stack just above the layer with the identity specified by id. even if the id parameter indicates the topmost layer of the stack, the value of the file descriptor describing the original stack will not change. in other words, stack continues to point to the top of the stack after the function re
turns. caution keeping the pointer to the stack even as layers are pushed onto the top of the stack is accomplished by swapping the contents of the file descriptor being pushed and the stack's current top layer file descriptor. the intent is that the pointer to the stack remain the stack's identity even if someone (perhaps covertly) has pushed other layers. some subtle ramifications: the ownersh...
PR_StringToNetAddr
if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
... if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_TicksPerSecond
the relationship between a printervaltime tick and standard clock units is platform-dependent. pr_pr_tickspersecond() allows you to discover exactly what that relationship is. seconds per tick (the inverse of pr_pr_tickspersecond()) is always between 10 microseconds and 1 millisecond. ...
... the relationship between a printervaltime tick and standard clock units is platform-dependent. ...
PR_Write
es a buffer of data to a file or socket. syntax #include <prio.h> print32 pr_write( prfiledesc *fd, const void *buf, print32 amount); parameters the function has the following parameters: fd a pointer to the prfiledesc object for a file or socket. buf a pointer to the buffer holding the data to be written. amount the amount of data, in bytes, to be written from the buffer. ...
...ta, in bytes, to be written from the buffer. re
turns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure is obtained by calling pr_geterror. description the thread invoking pr_write blocks until all the data is written or the write operation fails. therefore, the re
turn value is equal to either amount (success) or -1 (failure). note that if pr_write re
turns -1, some data (less than amount bytes) may have been written before an error occurred. ...
PR_Writev
ay of priovec structures that describe the buffers to write from. size number of priovec structures in the iov array. the value of this parameter must not be greater than pr_max_iovector_size. if it is, the function will fail and the error will be set to pr_buffer_overflow_error. timeout a value of type printervaltime describing the time limit for completion of the entire write operation. ...
...ompletion of the entire write operation. re
turns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure can be obtained by calling pr_geterror. description the thread calling pr_writev blocks until all the data is written or the write operation fails. therefore, the re
turn value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). note that if pr_writev re
turns -1, part of the data may have been written before an error occurred. if the timeout parameter is not pr_interval_no_timeout and all the data cannot be written in the specified interval, pr_writev re
turns -1 with the error code pr_io_timeout_error. this is the type definition...
PR_strtod
converts the prefix of a decimal string to the nearest double-precision floating point number. syntax #include <prdtoa.h> prfloat64 pr_strtod(const char *s00, char **se); parameters the function has these parameters: s00 the input string to be scanned. se a pointer that, if not null, will be assigned the address of the last character scanned in the input string. re
turns the result of the conversion is a prfloat64 value equivalent to the input string. if the parameter se is not null the location it references is also set. description pr_strtod converts the prefix of the input decimal string pointed to by s00 to a nearest double-precision floating point number. ties are broken by the ieee round-even rule. the string is scanned up to the first unrecognized character. if the valu...
...refix of the input decimal string pointed to by s00 to a nearest double-precision floating point number. ties are broken by the ieee round-even rule. the string is scanned up to the first unrecognized character. if the value of se is not (char **) null, pr_strtod stores a pointer to the character terminating the scan in *se. if the answer would overflow, a properly signed huge_val (infinity) is re
turned. if the answer would underflow, a properly signed 0 is re
turned. in both cases, pr_geterror() re
turns the error code pr_range_error. if no number can be formed, se is set to s00, and 0 is re
turned. ...
Threads
i. threading types and constants threading functions a thread has a limited number of resources that it truly owns. these resources include a stack and the cpu registers (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, independent execution entity until it re
turns from its root function or the process abnormally terminates. threads are critical resources and therefore require some management. to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread). joining a thread provides definitive proof that the target thread has terminated and has finished with both the resources to which the thread has access and the resou...
...ese functions on invalid threads are undefined. creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread. pr_jointhread blocks the calling thread until a specified thread terminates. pr_getcurrentthread re
turns the current thread object for the currently running code. pr_attachthread associates a prthread object with an existing native thread. pr_detachthread disassociates a prthread object from a native thread. controlling thread priorities for an overview of the way nspr controls thread priorities, see setting thread priorities. you set a thread's nspr priority when you create it with pr_cr...
An overview of NSS Internals
t as a personal certificate. (a personal certificate is a certificate for which the private key is in possession, and which could be used for signing data or for decrypting data.) a unique nickname can/should be assigned to the certificate at the time of import, which can later be used to easily identify and retrieve it. it's important to note that nss requires strict cleanup for all handles re
turned by nss. the application should always call the appropriate dereference (destroy) functions once a handle is no longer needed. this is particularly important for applications that might need to close a database and reinitialize nss using a different one, without restarting. such an operation might fail at runtime if data elements are still being referenced. in addition to the freebl, softoken...
... use your application code that supports proxies. when using hashing, encryption, and decryption functions, it is possible to stream data (as opposed to operating on a large buffer). create a context handle while providing all the parameters required for the operation, then call an “update” function multiple times to pass subsets of the input to nss. the data will be processed and either re
turned directly or sent to a callback function registered in the context. when done, you call a finalization function that will flush out any pending data and free the resources. this line is a placeholder for future sections that should explain how libpkix works and is designed. if you want to work with nss, it's often helpful to use the command line utilities that are provided by the nss devel...
NSS Memory allocation
l arenas that are truly leaked from those that are merely in the free list. there is a function named pl_arenafinish that really frees all the arenas on the free list. see the prototype at http://mxr.mozilla.org/nspr/source/n.../ds/plarenas.h a program should call that function at the very end, after having shutdown nss and nspr, to really free the contents of the free list. after that function re
turns, any arenas that still appear to be leaked have truly been leaked, and are not merely on the free list. 2. leak analysis tools will frequently report the wrong call stack for the allocation of leaked arenas. when the arena free list is in use, the first user of an arena will allocate it from the heap, but will then free it to the free list. the second user will allocated it from the free list an...
...ny arenas that still appear to be leaked have truly been leaked, and are not merely on the free list. 2. leak analysis tools will frequently report the wrong call stack for the allocation of leaked arenas. when the arena free list is in use, the first user of an arena will allocate it from the heap, but will then free it to the free list. the second user will allocated it from the free list and re
turn it to the free list. if and when an arena is leaked, the developer wants to see the call stack of the most recent allocation of the arena, not the stack of the oldest allocation of that arena. but leak analysis tools only record the allocation of memory from the heap, not memory from the arena free list, so they will always show the first allocation (from the heap) and not the most recent allocat...
NSS_3.12.1_release_notes.html
eed to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.1 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. new in nss 3.12.1 new functions in the nss shared library: cert_nametoasciiinvertible (see cert.h) convert an certname into its rfc1485 encoded equivalent. re
turns a string that must be freed with port_free(). caller chooses encoding rules. cert_encodesubjectkeyid (see cert.h) encode certificate skid (subject key id) extension. pk11_getallslotsforcert (see pk11pub.h) pk11_getallslotsforcert re
turns all the slots that a given certificate exists on, since it's possible for a cert to exist on more than one pkcs#11 token. levels of standards conformance st...
...new and revised documents available since the release of nss 3.11 include the following: b...
NSS 3.15 release notes
_true); added function secitem_reallocitemv2. it replaces function secitem_reallocitem, which is now declared as obsolete. support for single-operation (eg: not multi-part) symmetric key encryption and decryption, via pk11_encrypt and pk11_decrypt. certutil has been updated to support creating name constraints extensions. new functions in ssl.h ssl_peerstapledocspresponse - re
turns the server's stapled ocsp response, when used with a tls client socket that negotiated the status_request extension. ssl_setstapledocspresponses - set's a stapled ocsp response for a tls server socket to re
turn when clients send the status_request extension. in ocsp.h cert_postocsprequest - primarily intended for testing, permits the sending and receiving of raw ocsp r...
... 554369: fixed correctness of cert_cacheocspresponsefromsidechannel and other ocsp caching behaviour. bug 853285: fixed bugs in aes gcm. bug 341127: fix the invalid read in rc4_wordconv. ...
NSS 3.16 release notes
ss_disable_ecc=1 when building nss. bug 903885: (cve-2014-1492) in a wildcard certificate, the wildcard character should not be embedded within the u-label of an internationalized domain name. see the last bullet point in rfc 6125, section 7.2. bug 962760: libpkix should not include the common name of ca as dns names when evaluating name constraints. bug 981170: aeskeywrap_decrypt should not re
turn secsuccess for invalid keys. bug 974693: fix a memory corruption in sec_pkcs12_new_asafe. bug 956082: if the nss_sdb_use_cache environment variable is set, skip the runtime test sdb_measureaccess. the built-in roots module has been updated to version 1.97, which adds, removes, and distrusts several certificates. the atob utility has been improved to automatically ignore lines of text that are...
...ots module has been updated to version 1.97, which adds, removes, and distrusts several certificates. the atob utility has been improved to automatically ignore lines of text that aren't in base64 format. ...
NSS 3.17.3 release notes
a:9a cn = america online root certification authority 1 sha-1 fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a cn = america online root certification authority 2 sha-1 fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84 the following ca certificates had the websites and code signing trust bits
turned off ou = class 3 public primary certification authority - g2 sha1 fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f cn = equifax secure ebusiness ca-1 sha1 fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41 the following ca certificates were added cn = comodo rsa certification authority ...
...a program linked with older nss 3.x shared libraries will work with nss 3.17.3 shared libraries without recompil...
NSS 3.18.1 release notes
n nss 3.18.1 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites. the websites and code signing trust bits were
turned off in nss 3.18. but when firefox 38 went into beta, there was a huge spike in the number of certificate verification errors attributed to this change. so, to give website administrators more time to update their web servers, we reverted the trust bits back to being enabled. ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62...
...has been added as actively distrusted because it was misused to issue certificates for domain names the holder did not own or control. cn=mcsholding test, o=mcsholding, c=eg sha1 fingerprint: e1:f3:59:1e:76:98:65:c4:e4:47:ac:c3:7e:af:c9:e2:bf:e4:c5:76 the version number of the updated root ca list has been set to 2.4 bugs fixed in nss 3.18.1 this bugzilla query re
turns all the bugs fixed in nss 3.18.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.18.1 compatibility nss 3.18.1 shared libraries are backward compatible with all older nss 3.18 shared libraries. a program linked with older nss 3.18 shared libraries will work with nss 3.18.1 shared libraries without recomp...
NSS 3.18 release notes
default has been increased from dtls 1.0 to dtls 1.2. the default key size used by certutil when creating an rsa key pair has been increased from 1024 bits to 2048 bits. on mac os x, by default the softokn shared library will link with the sqlite library installed by the operating system, if it is version 3.5 or newer. ...
...a program linked with older nss 3.x shared libraries will work with nss 3.18 shared libraries without recompiling or r...
NSS 3.19.3 release notes
62:8f:5c:55:70:b1:c9:57:fa:fd:38:3f:b0:3d:7b:7d:d7:b9:c6 cn = tc trustcenter universal ca i sha-1 fingerprint: 6b:2f:34:ad:89:58:be:62:fd:b0:6b:5c:ce:bb:9d:d9:4f:4e:39:f3 cn = tc trustcenter class 2 ca ii sha-1 fingerprint: ae:50:83:ed:7c:f4:5c:bc:8f:61:c6:21:fe:68:5d:79:42:21:15:6e the following ca certificate had the websites trust bit
turned off cn = comsign secured ca sha1 fingerprint: f9:cd:0e:2c:da:76:24:c1:8f:bd:f0:f0:ab:b6:45:b8:f7:fe:d5:7a the following ca certificates were added cn = tÜrktrust elektronik sertifika hizmet sağlayıcısı h5 sha1 fingerprint: c4:18:f6:4d:46:d1:df:00:3d:27:30:13:72:43:a9:12:11:c6:75:fb cn = tÜrktrust elektronik sertifika hizmet sağl...
...a program linked with older nss 3.19 shared libraries will work with nss 3.19.3 shared libraries without recomp...
NSS 3.19 release notes
as name constraints. a new api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints. it is possible to override the directory (sqlite_lib_dir) in which the nss build system will look for the sqlite library. new functions in cert.h cert_getimposednameconstraints - check if any imposed constraints exist for the given certificate, and if found, re
turn the constraints as encoded certificate extensions. notable changes in nss 3.19 the ssl 3 protocol has been disabled by default. nss now more strictly validates tls extensions and will fail a handshake that contains malformed extensions (bug 753136). in tls 1.2 handshakes, nss advertises support for the sha512 hash algorithm in order to be compatible with tls servers that use certifica...
...he ssl 3 protocol has been disabled by default. nss now more strictly validates tls extensions and will fail a handshake that contains malformed extensions (bug 753136). in tls 1.2 handshakes, nss advertises support for the sha512 hash algorithm in order to be compatible with tls servers that use certificates with a sha512 signature (bug 1155922). bugs fixed in nss 3.19 this bugzilla query re
turns all the bugs fixed in nss 3.19: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.19 acknowledgements the nss development team would like to thank karthikeyan bhargavan from inria for responsibly disclosing the issue in bug 1086145. compatibility nss 3.19 shared libraries are backward compatible with all ...
NSS 3.23 release notes
an attacker could create a specially-crafted certificate whic...
...1:55:b3:7f:d7:60:66 security fixes in nss 3.23 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. bugs fixed in nss 3.23 this bugzilla query re
turns all the bugs fixed in nss 3.23: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.23 acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.23 shared libraries are backward compatible with a...
NSS 3.30 release notes
h a new boolean attribute, cka_nss_mozilla_ca_policy, set to true. applications that need to distinguish them from other other root cas, may use the exported function pk11_hasattributeset. support for callback functions that can be used to monitor ssl/tls alerts that are sent or received. new functions in cert.h cert_compareava - performs a comparison of two certava structures, and re
turns a seccomparison result. in pk11pub.h pk11_hasattributeset - allows to check if a pkcs#11 object in a given slot has a specific boolean attribute set. in ssl.h ssl_alertreceivedcallback - register a callback function, that will be called whenever an ssl/tls alert is received ssl_alertsentcallback - register a callback function, that will be called whenever an ssl/tls al...
...has been enhanced to support session tickets when no rsa certificate (e.g. only an ecdsa certificate) is configured. rsa-pss signatures produced by key pairs with a modulus bit length that is not a multiple of 8 are now supported. the pk12util tool now supports importing and exporting data encrypted in the aes based schemes defined in pkcs#5 v2.1. bugs fixed in nss 3.30 this bugzilla query re
turns all the bugs fixed in nss 3.30: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.30 compatibility nss 3.30 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.30 shared libraries without recompiling or r...
NSS 3.32 release notes
hg tag is nss_3_32_rtm. nss 3.32 requires netscape portable runtime (nspr) 4.16, or newer. nss 3.32 source distributions are available on ftp.mozilla.org, for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_32_rtm/src/ notable changes in nss 3.32 various minor improvements and correctness fixes. the code signing trust bit was
turned off for all, included root certificates. the websites (tls/ssl) trust bit was
turned off for the following root certificates. cn = addtrust class 1 ca root sha-256 fingerprint: 8c:72:09:27:9a:c0:4e:27:5e:16:d0:7f:d3:b7:75:e8:01:54:b5:96:80:46:e3:1f:52:dd:25:76:63:24:e9:a7 cn = swisscom root ca 2 sha-256 fingerprint: f0:9b:12:2c:71:14:f4:a0:9b:d4:ea:4f:4a:9...
...first-object sha-256 fingerprint: 6f:ff:78:e4:00:a7:0c:11:01:1c:d8:59:77:c4:59:fb:5a:f9:6a:3d:f0:54:08:20:d0:f4:b8:60:78:75:e5:8f bugs fixed in nss 3.32 nss versions 3.28.x, 3.29.x. 3.30.x and 3.31.x contained a bug in function cert_comparename, which caused the first rdn to be ignored. nss version 3.32 fixed this bug. (cve-2018-5149, bug 1361197) this bugzilla query re
turns all the bugs fixed in nss 3.32: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.32 compatibility nss 3.32 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.32 shared libraries, without recompiling, or...
NSS 3.47 release notes
ified root cert bug 1588557 - bad debug statement in tls13con.c bug 1579060 - mozilla::pkix tag definitions for issueruniqueid and subjectuniqueid shouldn't have the constructed bit set bug 1583068 - nss 3.47 should pick up fix from bug 1575821 (nspr 4.23) bug 1152625 - support aes hw acceleration on armv8 bug 1549225 - disable dsa signature schemes for tls 1.3 bug 1586947 - pk11_importandre
turnprivatekey does not store nickname for ec keys bug 1586456 - unnecessary conditional in pki3hack, pk11load and stanpcertdb bug 1576307 - check mechanism param and param length before casting to mechanism-specific structs bug 1577953 - support longer (up to rfc maximum) hkdf outputs bug 1508776 - remove refcounting from sftk_freesession (cve-2019-11756) bug 1494063 - support tls exporter in ts...
...l bug 1578626 - [cid 1453375] ub: decrement nullptr. bug 1578751 - ensure a consistent style for pk11_find_certs_unittest.cc bug 1570501 - add cmac to freebl and pkcs #11 libraries bug 657379 - nss uses the wrong oid for signaturealgorithm field of signerinfo in cms for dsa and ecdsa bug 1576664 - remove -mms-bitfields from mingw nss build. bug 1577038 - add pk11_getcertsfromprivatekey to re
turn all certificates with public keys matching a particular private key this bugzilla query re
turns all the bugs fixed in nss 3.47: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.47 compatibility nss 3.47 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with...
NSS Config Options
cified hashes and curves will be allowed, and rsa keys of 2048 or more will be accepted, and dh key exchange with 1024-bit primes or more: config="disallow=all allow=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" a policy that enables the aes ciphersuites and the secp256/384 curves: config="allow=aes128-cbc:aes128-gcm::hmac-sha1:sha1:sha256:sha384:rsa:ecdhe-rsa:secp256r1:secp384r1"
turn off md5 config="disallow=md5"
turn off md5 and sha1 only for ssl config="disallow=md5(ssl):sha1(ssl)" disallow values are parsed first, and then allow values, independent of the order in which they appear. future key words (not yet implemented): enable:
turn on ciphersuites by default. disable:
turn off ciphersuites by default without disallowing them by policy. flags:
turn on the following ...
...llow=md5"
turn off md5 and sha1 only for ssl config="disallow=md5(ssl):sha1(ssl)" disallow values are parsed first, and then allow values, independent of the order in which they appear. future key words (not yet implemented): enable:
turn on ciphersuites by default. disable:
turn off ciphersuites by default without disallowing them by policy. flags:
turn on the following flags: ssl-lock:
turn off the ability for applications to change policy with the ssl_setcipherpolicy (or ssl_setpolicy). policy-lock:
turn off the ability for applications to change policy with the call nss_setalgorithmpolicy. ssl-default-lock:
turn off the ability for applications to change cipher suite states with ssl_enablecipher, ssl_disablecipher. ecc cur...
NSS Sample Code sample2
bc_pad, ckm_des3_ecb, ckm_des3_cbc..... * note that some mechanisms (*_pad) imply the padding is handled for you * by nss. if you choose something else, then data padding is the * application's responsibility */ ciphermech = ckm_des_cbc_pad; slot = pk11_getbestslot(ciphermech, null); /* slot = pk11_getinternalkeyslot(); is a simpler alternative but in * theory, it *may not* re
turn the optimal slot for the operation. for * des ops, internal slot is typically the best slot */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); goto out; } /* nss passes blobs around as secitems. these contain a pointer to * data and a length.
turn the raw key into a secitem. */ keyitem.type = sibuffer; keyi...
..., internal slot is typically the best slot */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); goto out; } /* nss passes blobs around as secitems. these contain a pointer to * data and a length.
turn the raw key into a secitem. */ keyitem.type = sibuffer; keyitem.data = gkey; keyitem.len = sizeof(gkey); /*
turn the raw key into a key object. we use pk11_originunwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using raw keys isn't a good idea */ symkey = pk11_importsymkey(slot, ciphermech, pk11_originunwrap, cka_encrypt, &keyitem, null); if (symkey == null) { fprintf(stderr, "failure to import key into nss (err %d)\n"...
NSS Sample Code sample4
st=ca, c=us" \ * -n testca -t ctu,ctu,ctu -v 60 -x -d . -1 -2 -5 * * there are many ways to setup a public/private key to use - this * example shows one of them. * * this example does not do any padding. it simply encrypts/decrypts a block * of length equal to modulus length of the public/private key. */ #include "nss.h" #include "pk11pub.h" /* this callback is responsible for re
turning the password to the nss * key database. for example purposes, this function hardcodes the password. * in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; ...
...n", outlen); fprintf(stderr, "result of decryption, buf = \n%s\n", buf1); exit(0); cleanup: if (cert) cert_destroycertificate(cert); if (pubkey) seckey_destroypublickey(pubkey); if (pvtkey) seckey_destroyprivatekey(pvtkey); if (buf1) free(buf1); if (buf2) free(buf2); exit(1); } char *passwdcb(pk11slotinfo *info, prbool retry, void *arg) { if (!retry) re
turn pl_strdup("test"); else re
turn null; } ...
nss tech note1
ation of the current component within the target component, typically the decoded sequence. sub† . this field does not apply to all template types. if kind contains the sec_asn1_inline or sec_asn1_pointer modifiers, then it must point to the required subtemplate. if kind contains the sec_asn1_xtrn or sec_asn1_dynamic modifiers, this is a pointer to a callback function that will dynamically re
turn the required subtemplate. size† . this field does not apply to all template types. it is only required for dynamically allocating memory for the structure if the template is being included from an asn.1 sequence or sequence of, or if dynamic allocation was requested from the parent template using the sec_asn1_pointer modifier here is a description of the various tags and modifiers that app...
..._asn1_set_of and sec_asn1_sequence_of which define both the tag number and this modifier (but still need the method type, this may be a bug). sec_asn1_dynamic or sec_asn1_xtrn : specifies that the component format is defined in a dynamic subtemplate. there is no difference between the two macros. the sub field of the template points to a callback function of type sec_asn1templatechooser that re
turns the subtemplate depending on the component data. sec_asn1_skip: specifies that the decoder should skip decoding of the component. sec_asn1decodeitem can only skip required components and will assert if you try to skip an optional component. sec_quickderdecodeitem supports skipping the decoding of optional components if you define the tag of the component in the template sec_asn1_inner: rec...
FC_DecryptFinal
ck_rv fc_decryptfinal( ck_session_handle hsession, ck_byte_ptr plastpart, ck_ulong_ptr puslastpartlen ); parameters hsession [in] session handle. plastpart [out] pointer to the location where the last block of recovered data, if any, is to be stored. ...
...rt [out] pointer to the location where the last block of recovered data, if any, is to be stored. puslastpartlen [in,out] pointer to location where the number of bytes of recovered data is to be stored. ...
FC_DigestKey
ame fc_digestkey - add the digest of a key to a multi-part digest operation. syntax ck_rv fc_digestkey( ck_session_handle hsession, ck_object_handle hkey ); parameters hsession [in] session handle. ...
...ession, ck_object_handle hkey ); parameters hsession [in] session handle. hkey [in] handle of the key to be digested. description fc_digestkey continues a multi-part digest operation by digesting the value of a secret key. ...
FC_DigestUpdate
n_handle hsession, ck_byte_ptr ppart, ck_ulong uspartlen ); parameters hsession [in] session handle. ppart [in] pointer to the next block of data to be digested. uspartlen [in] length of data block in bytes. ...
...next block of data to be digested. uspartlen [in] length of data block in bytes. description fc_digestupdate starts or continues a multi-part digest operation. one or more blocks may be part of the message digest operation. ...
FC_EncryptFinal
n_handle hsession, ck_byte_ptr plastencryptedpart, ck_ulong_ptr puslastencryptedpartlen ); parameters hsession [in] session handle. ...
...pointer to the location that receives the last encrypted data part, if any puslastencryptedpartlen [in,out] pointer to location where the number of bytes of the last encrypted data part is to be stored. ...
FC_GenerateKey
ndle_ptr phkey ); parameters hsession [in] session handle. pmechanism [in] pointer to the mechanism to use. ptemplate [in] pointer to the template for the new key. ...
...o use. ptemplate [in] pointer to the template for the new key. ulcount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the new key. ...
FC_GenerateKeyPair
key template. usprivatekeyattributecount [in] number of attributes in the private key template. phpublickey [out] pointer to the location to receive the handle of the new public key. ...
... [out] pointer to the location to receive the handle of the new public key. phprivatekey [out] pointer to the location to receive the handle of the new private key. ...
FC_GetSessionInfo
name fc_getsessioninfo - obtain information about a session. syntax ck_rv fc_getsessioninfo( ck_session_handle hsession, ck_session_info_ptr pinfo ); parameters hsession [in] the open session handle. pinfo [out] pointer to the ck_session_info structure to be re
turned. description fc_getsessioninfo obtains information about a session. a user may call fc_getsessioninfo without logging into the token (to assume the nss user role). if the nss cryptographic module is in the error state, fc_getsessioninfo re
turns ckr_device_error. otherwise, it fills in the ck_session_info structure with the following information: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type...
...ormation: state: the state of the session, i.e., no role is assumed, the user role is assumed, or the crypto officer role is assumed flags: bit flags that define the type of session ckf_rw_session (0x00000002): true if the session is read/write; false if the session is read-only. ckf_serial_session (0x00000004): this flag is provided for backward compatibility and is always set to true. re
turn value examples see also fc_closesession, nsc_opensession ...
FC_GetTokenInfo
name fc_gettokeninfo - obtain information about a particular token in the system. syntax ck_rv fc_gettokeninfo(ck_slot_id slotid, ck_token_info_ptr pinfo); parameters fc_gettokeninfo has two parameters: slotid the id of the token's slot pinfo points to a ck_token_info structure description fc_gettokeninfo re
turns information about the token in the specified slot. on re
turn, the ck_token_info structure that pinfo points to has the following information: label: the label of the token, assigned during token initialization, padded with spaces to 32 bytes and not null-terminated. manufacturerid: id of the device manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. model: model of the device, "nss 3", padded with spaces to 16 char...
...ons that this application currently has open with the token hardwareversion: hardware version number, for example, 8.3 (major=0x08, minor=0x03), which are the version numbers of the certificate and key databases, respectively. firmwareversion: firmware version number, 0.0 (major=0x00, minor=0x00). a user may call fc_gettokeninfo without logging into the token (to assume the nss user role). re
turn value ckr_ok token information was successfully copied. ckr_cryptoki_not_initialized the pkcs #11 module library is not initialized. ckr_slot_id_invalid the specified slot number is out of the defined range of values. fc_gettokeninfo should re
turn ckr_arguments_bad if pinfo is null. examples note the use of the %.32s format string to print the label and manufacturerid members of th...
FC_Initialize
generic crypto services' dbtokendescription='software security device' cryptoslotdescription='psm internal cryptographic services' dbslotdescription='psm private keys' fipsslotdescription='psm internal fips-140-1 cryptographic services' fipstokendescription='psm fips-140-1 user private key services' minps=0" see pkcs #11 module specs for complete documentation of the library parameters string. re
turn value fc_initialize re
turns the following re
turn codes. ckr_ok: library initialization succeeded. ckr_arguments_bad pinitargs is null. pinitargs->libraryparameters is null. only some of the lock functions were provided by the application. ckr_cant_lock: the ckf_os_locking_ok flag is not set in pinitargs->flags. the nss cryptographic module always uses os locking and doesn't k...
...ant_lock: the ckf_os_locking_ok flag is not set in pinitargs->flags. the nss cryptographic module always uses os locking and doesn't know how to use the lock functions provided by the application. ckr_cryptoki_already_initialized: the library is already initialized. ckr_device_error we failed to create the oid tables, random number generator, or internal locks. (note: we probably should re
turn ckr_host_memory instead.) the software integrity test or power-up self-tests failed. the nss cryptographic module is in a fatal error state. ckr_host_memory: we ran out of memory. examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; ck_c_initialize_args initargs; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); initargs.createmutex = null; inita...
FC_SignRecover
dle of the key to be usedn. psignature [out] pointer to the buffer or null. ...
... the output buffer, replaced by the length of the signature if the operation is successful. ...
FC_SignUpdate
ck_session_handle hsession, ck_byte_ptr ppart, ck_ulong uspartlen ); parameters hsession [in] session handle. ppart [in] pointer to the next block of the data to be signed. uspartlen [in] length of data block in bytes. ...
...ointer to the next block of the data to be signed. uspartlen [in] length of data block in bytes. description fc_signupdate starts or continues a multi-part signature operation. one or more blocks may be part of the signature. ...
FC_UnwrapKey
wrappedkeylen [in] length of the wrapped key. ptemplate [in] pointer to the list of attributes for the unwrapped key. usattributecount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the unwrapped key. ...
...ation to receive the handle of the unwrapped key. description fc_unwrapkey unwraps (decrypts) a key and creates a new key opbject. ...
FC_VerifyRecover
] handle of the key to be usedn. pdata [out] pointer to the buffer or null. pusdatalen [in, out] pointer to the size of the output buffer, replaced by the length of the signature if the operation is successful. ...
...tput buffer, replaced by the length of the signature if the operation is successful. ...
FC_VerifyUpdate
spartlen ); parameters hsession [in] session handle. ppart [in] pointer to the next block of the data to be verified. uspartlen [in] length of data block in bytes. ...
...n] length of data block in bytes. description fc_verifyupdate starts or continues a multi-part signature verification operation where the signature is an appendix to the data. one or more blocks may be part of the signature. ...
FC_WrapKey
pointer to the mechanism to use. hwrappingkey [in] pointer to the public key template. hkey [in] number of attributes in the public key template. pwrappedkey [out] pointer to the location to receive the wrapped key or null. ...
...rapped key or null. puswrappedkeylen [in, out] pointer to length of wrapped key buffer. description fc_wrapkey wraps (encrypts) a key. ...
NSS tools : certutil
for example, the -n argument passes the certificate name, while the -a argument prints the certificate in ascii format: $ certutil -l -d sql:/home/my/sharednssdb -a -n "certificate authority - example domain" -----begin certificate----- miidmtccaoggawibagibatanbgkqhkig9w0baqufada5mrcwfqydvqqkew5fegft cgxliervbwfpbje...
...rvices " < 0> rsa 455a6673bde9375c2887ec8bf8016b3f9f35861d thawte freemail member's thawte consulting (pty) ltd. id < 1> rsa 40defeeb522ade11090eacebaaf1196a172127df example domain administrator cert < 2> rsa 1d0b06f44f6c03842f7d4f4a1dc78b3bcd1b85a5 john smith user cert there are ways to narrow the keys listed in the search results: * to re
turn a specific key, use the -n name argument with the name of the key. * if there are multiple security devices loaded, then the -h tokenname argument can search a specific token or all tokens. * if there are multiple key types available, then the -k key-type argument can search a specific type of key, like rsa, dsa, or ecc. listing security m...
sslkey.html
, your help would be very much appreciated. upgraded documentation may be found in the current nss reference key functions chapter 6 key functions this chapter describes two functions used to manipulate private keys and key databases such as the key3.db database provided with communicator. ...
...ey functions this chapter describes two functions used to manipulate private keys and key databases such as the key3.db database provided with communicator. seckey_getdefaultkeydb seckey_destroyprivatekey seckey_getdefaultkeydb re
turns a handle to the default key database opened by nss_init. syntax #include <key.h> #include <keyt.h> seckeykeydbhandle *seckey_getdefaultkeydb(void); re
turns the function re
turns a handle of type seckeykeydbhandle. description nss_init opens the certificate, key, and security module databases that you specify for use with nss. seckeykeydbhandle re
turns a handle to the key database opened by nss_init. seckey_destroyprivatekey destroys a private key structure. syntax #include <key.h> #include <keyt.h> void seckey_destroyprivatekey(seckeyp...
NSS_3.12.3_release_notes.html
rds compatibility (wildcards) bug 334678: prng_fips1861.c redefines the macro bsize on hp-ux bug 335016: mpp_pprime (miller-rabin probabilistic primality test) may choose 0 or 1 as the random integer bug 347037: make shlibsign depend on the softoken only bug 371522: auto-update of crls stops after first update bug 380784: pk11mode in non fips mode failed. bug 394077: libpkix need to re
turn revocation status of a cert bug 412468: modify certutil bug 417092: modify pkix_certselector api to re
turn an error if cert was rejected. bug 426413: audit messages need distinct types bug 438870: free freebl hashing code of dependencies on nspr and libutil bug 439115: db merge allows nickname conflicts in merged db bug 439199: sse2 instructions for bignum are not implemented on windo...
...on windows 32-bit bug 441321: tolerate incorrect encoding of dsa signatures in ssl 3.0 handshakes bug 444404: libpkix reports unknown issuer for nearly all certificate errors bug 452391: certutil -k incorrectly reports ec private key as an orphan bug 453234: support for seed cipher suites to tls rfc4010 bug 453364: improve pk11_cipherop error reporting (was: pk11_createcontextbysymkey re
turns null bug 456406: slot list leaks in symkeyutil bug 461085: rfe: export function cert_comparecerts bug 462293: crash on fork after softoken is dlclose'd on some unix platforms in nss 3.12 bug 463342: move some headers to freebl/softoken bug 463452: sql db creation does not set files protections to 0600 bug 463678: need to add rpath to 64-bit libraries on hp-ux bug 464088: option to ...
certutil
for example, the -n argument passes the certificate name, while the -a argument prints the certificate in ascii format: $ certutil -l -d sql:/home/my/sharednssdb -a -n "certificate authority - example domain" -----begin certificate----- miidmtccaoggawibagibatanbgkqhkig9w0baqufada5mrcwfqydvqqkew5fegft cgxliervbwfpbjeembwg...
...cate services " < 0> rsa 455a6673bde9375c2887ec8bf8016b3f9f35861d thawte freemail member's thawte consulting (pty) ltd. id < 1> rsa 40defeeb522ade11090eacebaaf1196a172127df example domain administrator cert < 2> rsa 1d0b06f44f6c03842f7d4f4a1dc78b3bcd1b85a5 john smith user cert there are ways to narrow the keys listed in the search results: o to re
turn a specific key, use the -n name argument with the name of the key. o if there are multiple security devices loaded, then the -h tokenname argument can search a specific token or all tokens. o if there are multiple key types available, then the -k key-type argument can search a specific type of key, like rsa, dsa, or ecc. listing security modules the device...
Necko walkthrough
nshttpconnection::onreadsegment passes bytes read from request to msocketout->write back to the context of onsocketwritable: nsiasyncinputstream::asyncwait (i.e. msocketin) sets the callback and waits. the http request is now written to the socket, which has a callback to the nshttpconnection... note: from what i can tell, there are some cases where the t...
...eamready function. remember that nspipeinputstream::asyncwait was called earlier, after the transaction was initially created and posted to the connection manager on the socket thread. and in that function it created a proxy callback because it wished to have oninputstreamready called on the main thread. back on the main thread: nsinputstreampump::oninputstreamready this function in
turn calls nsinputstreampump::onstatestart, nsinputstreampump::onstatetransfer and nsinputstreampump::onstatestop. these functions call nsistreamlistener::onstartrequest, nsistreamlistener::ondataavailable and nsistreamlistener::onstoprequest respectively. and that brings us back to the nshttpchannel api and nsdocshell gets its data. ...
Rhino overview
strict equality for the == and != operators. in version 1.3 and greater, == and != have the same meanings as ecma. the operators === and !== use strict equality in all versions. toboolean boolean(new boolean(false)) is false for all versions before 1.3. it is true (and thus ecma conformant) for version 1.3 and greater. array.prototype.tostring and object.prototype.tostring version 1.2 only re
turns array or object literal notation ("[1]" or "{a:1, b:2}" for example). in version 1.3 and greater these functions are ecma conformant. array constructor array(i) for a number argument i constructs an array with a single element equal to i for version 1.2 only. otherwise the ecma conformant version is used (an array is constructed with no elements but with length property equal to i). string.pr...
....prototype.split for version 1.2 only, split performs the perl4 special case when given a single space character as an argument (skips leading whitespace, and splits on whitespace). all other versions split on the space character proper as specified by ecma. security the security features in rhino provide the ability to track the origin of a piece of code (and any pieces of code that it may in
turn generate). these features allow for the implementation of a traditional url-based security policy for javascript as in netscape navigator. embeddings that trust the javascript code they execute may ignore the security features. embeddings that run untrusted javascript code must do two things to enable the security features. first, every context that is created must be supplied an instance of an ...
Performance Hints
var statements use var statements when possible. not only is it good programming practice, it can speed up your code by allowing the compiler to generate special code to access the variables. for example, you could rewrite function sum(a) { result = 0; for (i=0; i < a.length; i++) result += a[i]; re
turn result; } as function sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; re
turn result; } this is not equivalent code because the second version does not modify global variables result and i. however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). arrays use the forms...
...avascript array. eval and new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. for example, the code function myobject(a) { this.s = a; this.tostring = new function("re
turn this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { re
turn this.s } } beginning with rhino 1.4 release 2, code passed to eval and new function will be interpreted rather than compiled to class files. with using the with statement prevents the compiler from generating code for fast access to local variables. you're probab...
Creating JavaScript jstest reftests
(expected, actual, description) is somewhat like asserteq(actual, expected, description) except that the first two arguments are swapped, failures are reported via stdout rather than by throwing exceptions, and the matching is fuzzy in an unspecified way. for example, reportcompare sometimes considers numbers to be the same if they are "close enough" to each other, even if the == operator would re
turn false. expected = 3; actual = 1 + 2; reportcompare(expected, actual, '3==1+2'); comparesource comparesource(expected, actual, description) is used to test if the decompilation of a javascript object (conversion to source code) matches an expected value. note that tests which use comparesource should be located in the decompilation sub-suite of a suite. for example, to test the decompilation...
...ctual, '3==1+2'); comparesource comparesource(expected, actual, description) is used to test if the decompilation of a javascript object (conversion to source code) matches an expected value. note that tests which use comparesource should be located in the decompilation sub-suite of a suite. for example, to test the decompilation of a simple function you could write: var f = (function () { re
turn 1; }); expect = 'function () { re
turn 1; }'; actual = f + ''; comparesource(expect, actual, 'decompile simple function'); handling shell or browser specific features jstests run both in the browser and in the javascript shell. if your test needs to use browser-specific features, either: make the test silently pass if those features aren't present; or write a mochitest instead (preferred);...
Invariants
me cpu cycles (in other words, for no good reason whatsoever). if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment. while executing a script, cx->compartment == script->compartment. but this is true only so long as we are actually in the interpreter or jit code. a jsnative or other callback may move cx to another compartment, as long as it re
turns cx to the script's compartment before re
turning. a given trace-jit trace stays within a single compartment (indeed, a single global object) end-to-end. lifetime invariants in some places, pointers to jsobjects and jsstrings must refer to live heap objects, but this is not a hard fast rule, especially for strings. some jsstrings are allocated on the stack for quick operations. some commonly us...
...name. if it cannot be statically proven that a name always refers to a specific variable (meaning either a parameter or a variable introduced by var/let/function/const) in the program, then a name op must be emitted. (it would result in a bug where the wrong variable is used. javascript is only mostly lexically scoped. some nameexpressions might refer to a variable or global; or might at runtime
turn out to reference another object property, due to with, or a variable that isn't in the source code at all but was injected into a local scope by eval. these cases can be detected statically by looking for with and eval "nearby" in the parse tree.) if a nested function contains a nameexpression that refers to a variable in an enclosing scope which the function can outlive (i.e. the function can b...
JS::AutoIdArray
rray(jscontext *cx, jsidarray *ida); name type description cx jscontext * the context in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ida jsidarray * a pointer to jsidarray to take the ownership. methods method description bool operator!() const re
turn true if this has no owned array. jsid operator[](size_t i) const re
turn a jsid in specified index of the owned array. size_t length() const re
turn the length of the owned array. jsidarray *steal() re
turn the owned array and release the ownership. description js::autoidarray takes the ownership of jsidarray, and frees it in destructor by calling js_destr...
...ied index of the owned array. size_t length() const re
turn the length of the owned array. jsidarray *steal() re
turn the owned array and release the ownership. description js::autoidarray takes the ownership of jsidarray, and frees it in destructor by calling js_destroyidarray. examples { js::autoidarray ids(cx, js_enumerate(cx, obj)); if (!ids) // check the re
turned value from js_enumerate re
turn false; for (int32_t i = 0, len = ids.length(); i < len; i++) { somefunc(cx, ids[i]); } /* when leaving this scope, the jsidarray re
turned by js_enumerate is freed. */ } see also mxr id search for js::autoidarray jsidarray js_destroyidarray js_enumerate bug 332648 ...
JS::IdentifyStandardInstance
entifystandardinstanceorprototype(jsobject *obj); jsprotokey js::identifystandardconstructor(jsobject *obj); // added in spidermonkey 38 name type description obj jsobject * pointer to the instance/prototype/constructor object to determine. description js::identifystandardinstance determines if the given object is an instance for a standard class. if so, re
turn the associated jsprotokey. if not, re
turn jsproto_null. js::identifystandardprototype determines if the given object is a prototype for a standard class. if so, re
turn the associated jsprotokey. if not, re
turn jsproto_null. js::identifystandardinstanceorprototype determines if the given object is an instance or prototype for a standard class. if so, re
turn the associated jsprotokey. if not, ret...
...ype for a standard class. if so, re
turn the associated jsprotokey. if not, re
turn jsproto_null. js::identifystandardinstanceorprototype determines if the given object is an instance or prototype for a standard class. if so, re
turn the associated jsprotokey. if not, re
turn jsproto_null. js::identifystandardconstructor determines if the given object is a constructor for a standard class. if so, re
turn the associated jsprotokey. if not, re
turn jsproto_null. see also mxr id search for js::identifystandardinstance mxr id search for js::identifystandardprototype mxr id search for js::identifystandardinstanceorprototype mxr id search for js::identifystandardconstructor jsprotokey bug 975277 bug 976148 - added identifystandardconstructor ...
JSExtendedClass.wrappedObject
wrappedobject, then objects of that class may be wrappers. in a few cases the javascript engine will pretend the wrapper isn't there, instead operating on the object it wraps. in these cases the engine calls the jsextendedclass.wrappedobject callback to get the wrapped object. most classes do not implement wrappedobject. the specific cases where this happens are: the default tostring method re
turns a string that contains the name of the wrapped object's class rather than the wrapper's class. in typeof expressions and in js_typeofvalue, the type of the wrapped object is re
turned. (the result may be "object", "function", or "xml".) when assigning to __proto__ or __parent__ from script, the javascript engine checks to see if the assignment would produce a cycle. if so, it fails with a...
...= and !==. two wrapper objects that wrap the same object are also strictly equal. object.prototype.eval unwraps. a wrapper object that wraps an array is considered an array for the purpose of array.prototype.concat and array.concat (which treat array arguments differently from other arguments, per ecma 262-3 §15.4.4.4). the wrappedobject callback implementation must never fail. if it re
turns null or obj, then the js engine treats the object as though it were not a wrapper. wrapper objects typically have no prototype, do not allow setting __proto__, and inherit properties from the wrapped object rather than the prototype chain (see jsnewresolveop). ...
JSFunction
to get a jsfunction * given the jsobject * of a function object, use js_valuetofunction. to get the jsobject * given the jsfunction *, use js_getfunctionobject. ...
...to get a jsfunction * given the jsobject * of a function object, use js_valuetofunction. to get the jsobject * given the jsfunction *, use js_getfunctionobject. ...
JSReserveSlotsOp
description cx jscontext * the js context in which the new object is being created. obj jsobject * the new object. description warning: jsapi applications should not use this hook. a class cannot freely use a reserveslots hook to reserve a different number of slots for each object. rather, within a jsruntime, every call to the same reserveslots hook must re
turn the same value (excepting a few internal classes such as function, call, and block). jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a new object is created. the optional jsclass.reserveslots hook allows a class to make computed per-instance object slots reservations, in addition to or instead of using jsclass_has_reserved_slots(n...
...following hook: the jsclass.reserveslots callback is called each time a new object is created. the optional jsclass.reserveslots hook allows a class to make computed per-instance object slots reservations, in addition to or instead of using jsclass_has_reserved_slots(n) in the jsclass.flags initializer to reserve a constant-per-class number of slots. implementations of this hook should re
turn the number of slots to reserve, not including any reserved by using jsclass_has_reserved_slots(n) in jsclass.flags. see also jsclass ...
JS_AddArgumentFormatter
be handled by formatter, or whose handler should be removed. formatter jsargumentformatter the function to be used to convert arguments described by the given format. this function is described in more detail below. description js_addargumentformatter establishes formatter as the conversion function for format strings beginning with format in the context cx. on success, it re
turns js_true. otherwise it re
turns js_false. (at the moment, js_addargumentformatter fails only if there is no memory available to record the registration.) js_addargumentformatter does not copy format, it points at the string storage allocated by the caller, which is typically a string constant. if format is in dynamic storage, the caller must keep the string alive until js_removeargumentformatter i...
...tion should convert from jsval values to c values; js_false if the conversion function should convert from c values to jsval values. vpp jsval ** in-out parameter. a pointer into an array of jsval values. app va_list * in-out parameter. a pointer to an argument pointer, used to retrieve pointers to c values. callback description the conversion function should re
turn true on success, and re
turn false after reporting an error or detecting an already-reported error. for a given format string, for example "aa", the formatter is called from js_convertargumentsva like so: formatter(cx, "aa...", js_true, &sp, &ap); sp points into the arguments array on the js stack, while ap points into the stdarg.h va_list on the c stack. the js_true passed for fromjs tells the f...
JS_CallFunction
nce to the array of argument values to pass to the function. added in spidermonkey 31 argc unsigned number of arguments you are passing to the function. obsolete since jsapi 30 argv jsval * pointer to the array of argument values to pass to the function. obsolete since jsapi 30 rval js::mutablehandlevalue out parameter. on success, *rval receives the re
turn value from the function call. description js_callfunction calls a specified function, fun, on an object, obj. in terms of function execution, the object is treated as this. js_callfunctionname calls a function with specified name, name on an object obj. if js engine fails to get the function, it re
turns false. js_callfunctionvalue calls a specified function, fval on an object obj. js_ca...
...e. there should be one value for each argument you pass to the function; the number of arguments you pass may be different from the number of arguments defined for the function. obsolete since jsapi 30. in argc, indicate the number of arguments passed to the function. in argv, pass a pointer to the actual argument values to use. rval is a pointer to a variable that will hold the function's re
turn value, if any, on successful function execution. if the called function executes successfully, js_callfunction re
turns true. otherwise it re
turns false, and rval is undefined. calling js_callfunction is safe only if the fun argument could be passed to js_getfunctionobject safely: that is, it is a function implemented by a jsnative or jsfastnative or the result of a call to js_compilefunction, j...
JS_DecompileScript
re
turn the source code of the script or the function. syntax jsstring * js_decompilescript(jscontext *cx, js::handle<jsscript*> script); name type description cx jscontext * the context to use to decompile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. script js::handle<jsscript*> script or function to decompile. description js_decompilescript re
turns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it re
turns the original source code of the script. if the script is not cached, it tries to load the source from file, and re
turns nullptr if an error happened while loading. ...
...jsscript*> script or function to decompile. description js_decompilescript re
turns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it re
turns the original source code of the script. if the script is not cached, it tries to load the source from file, and re
turns nullptr if an error happened while loading. if successful, js_decompilescript re
turns a string containing the source code of the script. otherwise, it re
turns a string containing "[no source]". from spidermonkey 17, this does not actually decompile the script, but re
turns the original source code (bug 761723). see also mxr id search for js_decompilescript js::compile js_compilescript js_decompilefunction js_destroyscript js::evaluate js_executescript bug 761723 ...
JS_DefinePropertyWithTinyId
see also bug 975069 ...
...t engine to call the getter for the color property, but obj[10] wouldn't. traditionally, negative tiny ids are used to minimize the potential confusion, but it is best to specify a non-null getter and setter when defining a property with a tiny id. on success, js_definepropertywithtinyid and js_defineucpropertywithtinyid re
turn js_true. if the property already exists or cannot be created, they re
turn js_false. see also bug 975069 ...
JS_EnterLocalRootScope
o tell the js engine about each variable that may point to such a value. calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc. for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) re
turn js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx. even if js_gc is // called, these new values will not be collected. ok = my_getpropertybody(cx, obj, id, vp); // when we leave the local root scope, this protection ends. new // items created in this local root scope become subject to gc. js_leavelo...
...function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx. even if js_gc is // called, these new values will not be collected. ok = my_getpropertybody(cx, obj, id, vp); // when we leave the local root scope, this protection ends. new // items created in this local root scope become subject to gc. js_leavelocalrootscope(cx); re
turn ok; } note: js_leavelocalrootscope or js_leavelocalrootscopewithresult must be called once for every prior successful call to js_enterlocalrootscope. if js_enterlocalrootscope fails, you must not make the matching js_leavelocalrootscope call. local root scopes do not cover objects that are the result of jsapi calls like js_getproperty or js_callfunction. to remove a gc thing from a local root sc...
JS_ExecuteRegExp
exp and js_newregexpobjectnostatics store the match result array to *rval if matches, otherwise stores null to *rval. if test is true, js_executeregexp and js_newregexpobjectnostatics store the boolean value true to *rval if matches, otherwise stores null to *rval. ...
...ult array to *rval if matches, otherwise stores null to *rval. if test is true, js_executeregexp and js_newregexpobjectnostatics store the boolean value true to *rval if matches, otherwise stores null to *rval. js_executeregexp updates the built-in regexp object's properties. ...
JS_FlattenString
characters of the string infallible. syntax jsflatstring * js_flattenstring(jscontext *cx, jsstring *str); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string to flatten. description js_flattenstring flattens a string str and re
turns a pointer to jsflatstring. to catch errors, an opaque jsflatstring type is re
turned. note: the input and output of js_flattenstring() are the same actual gc-thing so only one needs to be rooted. if a jsstring is known to be flat, you can use js_assert_string_is_flat to make a debug-checked cast. example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) r...
... a pointer to jsflatstring. to catch errors, an opaque jsflatstring type is re
turned. note: the input and output of js_flattenstring() are the same actual gc-thing so only one needs to be rooted. if a jsstring is known to be flat, you can use js_assert_string_is_flat to make a debug-checked cast. ...
JS_GetElement
syntax bool js_getelement(jscontext *cx, js::handleobject obj, uint32_t index, js::mutablehandlevalue vp); name type description cx jscontext * the context in which to perform the property lookup. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to search for the element. index uint32_t index of the element to look up. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the element, if it exists, and undefined otherwise. ...
...s::mutablehandlevalue out parameter. on success, *vp receives the current value of the element, if it exists, and undefined otherwise. description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_getelement sets *vp to the element's current value. if not, it sets *vp to undefined and re
turns true (to indicate no error occurred). if the search fails with an error or exception, js_getelement re
turns false, and the value left in *vp is undefined. see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_GetFlatStringChars
wsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 get the chars of a flat string. use js_flattenstring to flatten the string. ...
...le covers features introduced in spidermonkey 1.8.5 get the chars of a flat string. use js_flattenstring to flatten the string. ...
JS_GetFunctionCallback
note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls. ...
...was defined at compile time using --enable-trace-jscalls. syntax jsfunctioncallback js_getfunctioncallback(jscontext *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getfunctioncallback re
turns the current function invocation callback, or null if there isn't one set up. see also mxr id search for js_getfunctioncallback js_setfunctioncallback jsfunctioncallback bug 1103269 ...
JS_GetFunctionObject
retrieves the object for a specified function. syntax jsobject * js_getfunctionobject(jsfunction *fun); name type description fun jsfunction * pointer to a js function. fun should be a native function or jsapi-compiled function. see below. description js_getfunctionobject re
turns the javascript function object for a specified function pointer, fun. fun must be either a function implemented by a jsnative (or jsfastnative) or the result of a call to js_compilefunction or similar functions. in other cases, the object re
turned by js_getfunctionobject is not necessarily safe to call and should not be exposed to script. in the javascript language, functions are objects. but in the jsapi there are two separate concepts: a jsobject is what is expo...
... the code of a function. for certain functions, the two have a strictly one-to-one relationship, and for those functions it is safe to call js_getfunctionobject to move from the jsfunction to the jsobject. however, for other functions, and particularly for javascript closures, many jsobjects may share the same jsfunction. in these cases, this function should not be called. calling the jsobject re
turned by it could cause a crash or worse. js_getfunctionobject always re
turns a pointer to an object. see also mxr id search for js_getfunctionobject js_compilefunction ...
JS_GetFunctionScript
see also mxr id search for js_getfunctionscript bug 1069694 ...
...iption cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handlefunction pointer to a js function. description js_getfunctionscript re
turns a pointer to jsscript for the specified function, fun. if fun is a native function, it re
turns null. see also mxr id search for js_getfunctionscript bug 1069694 ...
JS_GetGlobalObject
ion cx jscontext * the context from which to retrieve the global object. description this function is obsolete: use js_getglobalforobject or js_getglobalforscopechain instead. the concept of a global object belonging to a context will likely be phased out in future versions of spidermonkey. js_getglobalobject retrieves the global object for a specified jscontext *, cx. ...
...orscopechain instead. the concept of a global object belonging to a context will likely be phased out in future versions of spidermonkey. js_getglobalobject retrieves the global object for a specified jscontext *, cx. this re
turns null if cx has no global object. spidermonkey supports applications that have multiple global objects, such as the various window objects in a web browser. the object re
turned by js_getglobalobject is not necessarily the same thing as the global object seen by any javascript code that runs in cx! if a function is executing, the global object used by that function is determined when the function is created. furthermore, some jsapi functions, such as js_executescript, allow the caller to specify a global object in which the script executes. in either case, the global f...
JS_GetInstancePrivate
pi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null. description js_getinstanceprivate determines if a javascript object, obj, is an instance of a given jsclass, clasp, and if it is, re
turns a pointer to the object's private data. otherwise it re
turns null. note that if obj is an instance of clasp, but there is no private data currently associated with the object, or the object cannot have private data, js_getinstanceprivate also re
turns null. if you pass a non-null argument vector, argv, to js_getinstanceprivate, and obj is not an instance of clasp, this function reports a class mi...
...in this case, js_getinstanceprivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an error message using the js_reporterror function. ...
JS_GetPropertyAttributes
ror occurs, *foundp receives js_true if the specified property is found and js_false if it is not found. if an error occurs, the value left in *foundp is unspecified. description js_getpropertyattributes retrieves the property attributes of the property with the given name on a given object, obj. js_getucpropertyattributes is the unicode version of the function. if an error occurs, the re
turn value is js_false, and the values left in *attrsp and *foundp are unspecified. if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false. the value left in *attrsp is unspecified. the re
turn value is js_true (to indicate that no error occurred). if the property exists and belongs to obj, then *...
...rty, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false. the value left in *attrsp is unspecified. the re
turn value is js_true (to indicate that no error occurred). if the property exists and belongs to obj, then *foundp is set to js_true, *attrsp is set to the logical or of zero or more property attributes flags, and the function re
turns js_true. see also property attributes bug 893186 ...
JS_GetScopeChain
js_getscopechain has been removed in spidermonkey 1.8.7 with no identical replacement. when you only used this function to retrieve the scope chain's global, then you can use the function js_getglobalforscopechain. syntax jsobject * js_getscopechain(jscontext *cx); name type description cx jscontext * the context to query. description js_getscopechain re
turns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. the ecmascript standard, ecma 262-3 §10, describes execution contexts and scope chains. a scope chain is a sequence of objects whose properties are searched whenever a script or function refers to a variable. these objects represent the lexical scope of the currently executing statement or...
... different global object, then that object will be the last object in the current scope chain. if the context is currently executing a script, and not in any function, it's running in a scope that was passed to js_executescript or a similar function by the application. this scope chain may or may not contain cx's current global object. if any code is currently executing in cx, js_getscopechain re
turns a pointer to the first jsobject on the current scope chain. otherwise, if cx has a global object, js_getscopechain re
turns that. otherwise, an error is reported and js_getscopechain re
turns null. to walk the scope chain, use js_getparent. see also mxr id search for js_getscopechain js_getglobalforscopechain bug 632064 ...
JS_GetSecurityCallbacks
r; // obsolete since jsapi 13 jsobjectprincipalsfinder findobjectprincipals; // obsolete since jsapi 13 }; name type description contentsecuritypolicyallows jscspevalchecker a pointer to the function which checks if a csp instance wants to disable eval() and friends. use null is not needed. subsumes jssubsumesop a pointe to the function which re
turns whether the first principal subsumes the second. use null is not needed. description js_setsecuritycallbacks sets the runtime's security callbacks to callbacks. it allows the embedding to control certain aspects of js code execution based on security settings of the global object the code is executed in. if callbacks is null, it sets callbacks to default value. js_getsecuritycallbacks ret...
...tion js_setsecuritycallbacks sets the runtime's security callbacks to callbacks. it allows the embedding to control certain aspects of js code execution based on security settings of the global object the code is executed in. if callbacks is null, it sets callbacks to default value. js_getsecuritycallbacks re
turns the runtime's current security callbacks. ...
JS_GetStringBytes
; // added in jsapi 1.8.2 name type description cx jscontext * (js_getstringbytesz and js_encodestring only) a context. str jsstring * string to retrieve bytes from. description js_getstringbytes and js_getstringbytesz convert the specified javascript string, str, to a c string (an array of 8-bit chars). if js_cstringsareutf8 is true, then the re
turned string is utf-8, and the conversion is lossless. otherwise the high byte is simply dropped from each jschar. on success, the re
turn value is a pointer to the char array, which is null-terminated. on failure, js_getstringbytes re
turns a pointer to a null-terminated empty string; js_getstringbytesz re
turns null. note: js_getstringbytes() and js_getstringbytesz() have both been removed as of jav...
...n value is a pointer to the char array, which is null-terminated. on failure, js_getstringbytes re
turns a pointer to a null-terminated empty string; js_getstringbytesz re
turns null. note: js_getstringbytes() and js_getstringbytesz() have both been removed as of javascript 1.8.5 (firefox 4). instead, you should use js_encodestring, js_getstringencodinglength, js_encodestringtobuffer. the array re
turned by js_getstringbytes or js_getstringbytesz is automatically freed when str is finalized by the javascript garbage collection mechanism. the application must not modify the contents of the array. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can re
turn a corrupted copy of the contents of the string. use js_getstringchars to access the 16-bit characters of a jav...
JS_GetStringCharAt
syntax bool js_getstringcharat(jscontext *cx, jsstring *str, size_t index, char16_t *res); char16_t js_getflatstringcharat(jsflatstring *str, size_t index); name type description cx jscontext * the context in which to create the new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * or jsflatstring * the string to get character. index size_t an integer between 0 and 1-less-than the length of the string. res char16_t * (js_getstringcharat only) out parameter. ...
...tstring * the string to get character. index size_t an integer between 0 and 1-less-than the length of the string. res char16_t * (js_getstringcharat only) out parameter. on successful, receives the character code. description js_getstringcharat and js_getflatstringcharat get the specified character from the string str. on successful, js_getstringcharat re
turns true and stores the character code into *res, otherwise re
turns false. js_getflatstringcharat always succeeds, and re
turns the character code. index should not be greater than or equal to the length of str. see also mxr id search for js_getstringcharat mxr id search for js_getflatstringcharat bug 1034627 ...
JS_GetStringChars
; // obsolete since jsapi 1.8.5 const jschar * js_getstringcharsz(jscontext *cx, jsstring *str); // added in spidermonkey 1.8.2, obsolete since jsapi 33 name type description cx jscontext * (in js_getstringcharsz only) a context. str jsstring * the string to obtain characters from. description js_getstringchars obsolete since javascript 1.8.5 re
turns a pointer to the first element of an array of jschars. warnings: the array is not necessarily null-terminated. to get the length of the string, use js_getstringlength. the program must not modify the array. if it does, the behavior is undefined. the content of a js string is not guaranteed to be valid utf-16. it may contain surrogate code units that aren't properly paired. it may also contai...
...t element of an array of jschars. warnings: the array is not necessarily null-terminated. to get the length of the string, use js_getstringlength. the program must not modify the array. if it does, the behavior is undefined. the content of a js string is not guaranteed to be valid utf-16. it may contain surrogate code units that aren't properly paired. it may also contain zeroes. the array re
turned by this function remains valid as long as str is valid. (eventually, str becomes unreachable, the garbage collector collects it, and the array is freed by the system.) js_getstringcharsz is the same except that it always re
turns either a null-terminated string or null, indicating out-of-memory. see also bug 609440 - removed js_getstringchars bug 1037869 - removed js_getstringcharsz ...
JS_GetStringCharsAndLength
text * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...r must be in a request on this jscontext. str jsstring * a string to get characters. ...
JS_GetStringLength
because some unicode characters are represented using two 16-bit code units, the result is not necessarily the same as the number of unicode characters in the string. ...
...n the length, in 16-bit code units, of a javascript string. syntax size_t js_getstringlength(jsstring *str); name type description str jsstring * the string to examine. description js_getstringlength reports the length, in 16-bit code units, of the string str. this is the same as the length property of the string. this is the same as the length of the array re
turned by js_getstringchars, in char16_ts (not bytes). because some unicode characters are represented using two 16-bit code units, the result is not necessarily the same as the number of unicode characters in the string. see also mxr id search for js_getstringlength js_comparestrings js_convertvalue js_getemptystringvalue js_getstringbytes js_internstring js_newstringcopyn js_newstringcopyz js_value...
JS_InitClass
ucture to initialize. this structure defines the class for use by other api functions. constructor jsnative the constructor for the class. its scope matches that of the obj argument. if constructor is null, then static_ps and static_fs must also be null. unlike other jsnatives, this function must not call js_this or js_this_object. instead it must create a new object and re
turn it. nargs unsigned number of arguments for the constructor. ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec, which can be written {0, 0, 0, 0, 0}. these properties, if any, are added to the class's new prototype object. all instances of the new class will inherit these propert...
...ript code can create new instances using the new keyword. classes can have methods and properties that are present on all instances. they can also have methods and properties that are only present on the constructor; these are called "static methods" and "static properties" because they serve the same purpose and use the same syntax as static methods and fields in java. on success, js_initclass re
turns a pointer to a js object that is the prototype for the newly initialized class. if js_initclass fails, it re
turns null. the constructor for the class is built in the same context as cx, and in the same scope as obj. if you pass null as the constructor parameter, then a constructor is not built, and you cannot specify static properties and functions for the class. note: starting with spidermonk...
JS_InternString
must be in a request on this jscontext. s const char * or const char16_t * pointer to a character array containing the data for the string. in js_internstring and js_internucstring, the string must be null-terminated. length size_t (only in js_internstringn and js_internucstringn) the length of s in characters. description js_internstring and js_internstringn re
turn an interned javascript string with a specified value, s. js_internucstring and js_internucstringn are the unicode versions of the function. each jsruntime keeps a table of all existing interned strings. if an interned string already exists with the desired value, these functions re
turn the existing string. otherwise a new string is created and added to the table. strings created with these functi...
...unicode versions of the function. each jsruntime keeps a table of all existing interned strings. if an interned string already exists with the desired value, these functions re
turn the existing string. otherwise a new string is created and added to the table. strings created with these functions are protected from garbage collection for the lifetime of the jsruntime. on success, these functions re
turn a pointer to the interned string. otherwise they report an error and re
turn null. see also mxr id search for js_internstring mxr id search for js_internstringn mxr id search for js_internucstring mxr id search for js_internucstringn js_getemptystringvalue js_newstringcopyn js_newstringcopyz js_newucstring js_newucstringcopyn js_newucstringcopyz js_valuetostring ...
JS_MapGCRoots
*/ #define js_map_gcroot_remove 2 /* remove and free the current entry */ typedef int (*jsgcrootmapfun)(void *rp, const char *name, void *data); description call js_mapgcroots to map the gc's roots table using map(rp, name, data). the root is pointed at by rp; if the root is unnamed, name is null; data is supplied from the third parameter to js_mapgcroots. the map function should re
turn js_map_gcroot_remove to cause the currently enumerated root to be removed. to stop enumeration, re
turn js_map_gcroot_stop. to continue mapping, re
turn js_map_gcroot_next. these constants are flags; you can or them together. this function acquires and releases rt's gc lock around the mapping of the roots table, so the map function should run to completion in as few cycles as possible. the map fun...
...hese constants are flags; you can or them together. this function acquires and releases rt's gc lock around the mapping of the roots table, so the map function should run to completion in as few cycles as possible. the map function cannot call js_gc, js_maybegc, js_beginrequest, or any js api entry point that acquires locks, without double-tripping or deadlocking on the gc lock. js_mapgcroots re
turns the count of roots that were successfully mapped. see also bug 803907 ...
JS_NewArrayObject
h the specified contents elements. js_newarrayobject defines an enumerable array element with the value contents[i] on the new array. js_newarrayobject with length parameter creates a new array object with the specified length; the result is like the javascript expression new array(length). the new array has the specified length, but it doesn't have any elements. on success, js_newarrayobject re
turns the new array object. otherwise it reports an error as though by calling js_reportoutofmemory and re
turns null. obsolete since jsapi 30. js_newarrayobject with length parameter creates a new array object with the specified length. if vector is non-null, then for each index i from 0 to length - 1, js_newarrayobject defines an enumerable array element with the value vector[i] on the new array. ...
...ach index i from 0 to length - 1, js_newarrayobject defines an enumerable array element with the value vector[i] on the new array. (this means that if length is nonzero and vector is null, the result is like the javascript expression new array(length). the new array has the specified length, but it doesn't have any elements.) it is often better to call js_newarrayobject(cx, 0, null), store the re
turned object in a gc root, and then populate its elements with js_setelement or js_defineelement. this avoids unrooted jsvals in vector from being subject to garbage collection until the new object has been populated. see also mxr id search for js_newarrayobject bug 969812 - change parameter to contents ...
JS_NewGlobalObject
lobject creates a new global object based on the specified class. the new object has no parent. it initially has no prototype either, since it is typically the first object created; call js_initstandardclasses to create all the standard objects, including object.prototype, and set the global object's prototype. the constructor clasp->construct is not called. on success, js_newglobalobject re
turns a pointer to the new object. otherwise it re
turns null. debugger api hook during global creation, we fire notifications to callbacks registered via the debugger api. these callbacks are arbitrary script, and can touch the global in arbitrary ways. when that happens, the global should not be in a half-baked state. but this creates a problem for consumers that need to set slots on the global to ...
...rovides a way for consumers to set slots atomically (immediately after the global is created), before any debugger hooks are fired. it's unfortunately on the clunky side, but that's the way the cookie crumbles. if callers have no additional state on the global to set up, they may pass fireonnewglobalhook to js_newglobalobject, which causes that function to fire the hook as its final act before re
turning. otherwise, callers should pass dontfireonnewglobalhook, which means that they are responsible for invoking js_fireonnewglobalobject upon successfully creating the global. if an error occurs and the operation aborts, callers should skip firing the hook. but otherwise, callers must take care to fire the hook exactly once before compiling any script in the global's scope (we have assertions in p...
JS_NewUCString
quires request. in a js_threadsafe build, the caller must be in a request on this jscontext. buf char * or char16_t * pointer to a character array, allocated with js_malloc, containing the characters for the js string to create. the javascript engine adopts the buffer. length size_t number of characters in the text string. description js_newstring creates and re
turns a new string, using the memory starting at buf and ending at buf + length as the character storage. js_newucstring is the unicode version of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the ja...
...torage. js_newucstring is the unicode version of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the javascript engine to avoid needless data copying. on success, js_newstring and js_newucstring re
turn a pointer to the new string. on error or exception, they re
turn null. see also js_convertvalue js_getemptystringvalue js_getstringbytes js_getstringchars js_getstringlength js_internstring js_internucstring js_internucstringn js_newstringcopyn js_newstringcopyz js_newucstringcopyn js_newucstringcopyz js_valuetostring bug 618262 - removed js_newstring ...
JS_NextProperty
s_newpropertyiterator. syntax bool js_nextproperty(jscontext *cx, js::handleobject iterobj, js::mutablehandleid idp); name type description cx jscontext * the js context in which to enumerate properties. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...ust be in a request on this jscontext. iterobj js::handleobject the opaque iterator object re
turned by a previous call to js_newpropertyiterator. idp js::mutablehandleid out parameter. on success, *idp receives the name or index of the next property name; or jsid_void if there are no more enumerable properties to visit. description on success, js_nextproperty re
turns true, with *idp containing the id of the next enumerable own property to visit using iterobj, or jsid_void if there is no such property left to visit. on error, it re
turns false, and the value left in *idp is undefined. see also bug 1081660 ...
JS_PushArguments
ject * f jsfunction * * none. any asterisks (*) in format are ignored. this function also takes in consideration any additional custom types defined in cx using js_addargumentformatter. for example, if format is "biob", then there must be four arguments after format. their types must be jsbool, jsdouble, jsobject *, and jsbool. if successful, js_pusharguments would re
turn a pointer to the first element of an array of four jsvals: a boolean, a number, an object (or null), and a boolean. on success, js_pusharguments fills in the supplied markp pointer and re
turns a pointer to the first element of an array of jsval which are automatically rooted as necessary (protected from the gc temporarily). the application must call js_poparguments using the supplied markp stack ...
...ss, js_pusharguments fills in the supplied markp pointer and re
turns a pointer to the first element of an array of jsval which are automatically rooted as necessary (protected from the gc temporarily). the application must call js_poparguments using the supplied markp stack pointer when done with this stack frame, to free the memory and unroot the jsvals. on error or exception, js_pusharguments re
turns null. to perform the opposite conversion, converting an array of jsvals to various native c types, use js_convertarguments. see also js_poparguments bug 542091 ...
JS_SaveExceptionState
t *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description saves the current exception state (that is, any pending exception, or a cleared exception state) associated with the specified context cx, and re
turns a jsexceptionstate object holding this state. that object may then be used to restore again the context using js_restoreexceptionstate, or discarded using js_dropexceptionstate. either of those two functions frees any memory used by the jsexceptionstate. the jsexceptionstate created by this function automatically roots any pending exception object which needs to be protected from the gc. this fu...
...eptionstate object holding this state. that object may then be used to restore again the context using js_restoreexceptionstate, or discarded using js_dropexceptionstate. either of those two functions frees any memory used by the jsexceptionstate. the jsexceptionstate created by this function automatically roots any pending exception object which needs to be protected from the gc. this function re
turns null if the engine was not built with support for exceptions. see also mxr id search for js_saveexceptionstate jsexceptionstate js_restoreexceptionstate js_dropexceptionstate ...
JS_SetOperationCallback
t 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 re
turning js_false.) js_getoperationcallback re
turns the currently installed operation callback, or null if none is currently installed. js_triggeroperationcallback triggers a callback set using js_setoperationcallback. js_clearoperationcallback clears the current operation callback. obsolete since javascript 1.9.1 js_setoperationcallbackfunction sets the operation callback without changing the ope...
...ed operation callback, or null if none is currently installed. js_triggeroperationcallback triggers a callback set using js_setoperationcallback. js_clearoperationcallback clears the current operation callback. obsolete since javascript 1.9.1 js_setoperationcallbackfunction sets the operation callback without changing the operation limit. obsolete since javascript 1.9.1 js_getoperationlimit re
turns the current operation limit, or js_max_operation_limit if no operation callback is currently installed. obsolete since javascript 1.9.1 js_setoperationlimit sets the operation limit without changing the operation callback. it must be called only when an operation callback is installed. obsolete since javascript 1.9.1 see also mxr id search for js_setoperationcallback mxr id search for js_g...
JS_SetPropertyAttributes
nd in loops. jsprop_readonly property is read only. jsprop_permanent property cannot be deleted. jsprop_exported property can be imported by other objects. jsprop_index property is actually an index into an array of properties, and is cast to a const char *. if js_setpropertyattributes cannot locate an object with the specified property, it re
turns js_false, and the value left in *foundp is undefined. if the specified property or the specified object does not exist, foundp is set to js_false. then, if the property exists, but is associated with a different object, js_setpropertyattributes re
turns js_true. otherwise, it sets foundp to js_true, and attempts to set the attributes as specified. if the attributes can be set, js_setpropertyattr...
...e, and the value left in *foundp is undefined. if the specified property or the specified object does not exist, foundp is set to js_false. then, if the property exists, but is associated with a different object, js_setpropertyattributes re
turns js_true. otherwise, it sets foundp to js_true, and attempts to set the attributes as specified. if the attributes can be set, js_setpropertyattributes re
turns js_true. if not, it re
turns js_false. to get the attributes of a property, use js_getpropertyattributes. property attributes bug 893186 ...
JS_StringToVersion
re
turns a jsversion value representing the version string. syntax jsversion js_stringtoversion(const char *string); name type description string const char * version string to convert. description js_stringtoversion attempts to convert the version string to a jsversion value. ...
... re
turns a jsversion value representing the version string. syntax jsversion js_stringtoversion(const char *string); name type description string const char * version string to convert. description js_stringtoversion attempts to convert the version string to a jsversion value. ...
JS_SuspendRequest
any, to allow the thread to block or perform time-consuming calculations. syntax jsrefcount js_suspendrequest(jscontext *cx); void js_resumerequest(jscontext *cx, jsrefcount savedepth); name type description cx jscontext * the context whose current request is to be suspended or resumed. savedepth jsrefcount (only in js_resumerequest) the valued re
turned by the matching js_suspendrequest call. description in js_threadsafe builds, when a multi-threaded application is in a request but needs to block or perform lengthy computation that can race safely with the garbage collector, it should call js_suspendrequest before the time-consuming operation and js_resumerequest after. for more information about thread safety and requests, see js_thre...
...call js_suspendrequest before the time-consuming operation and js_resumerequest after. for more information about thread safety and requests, see js_threadsafe. js_suspendrequest suspends any currently active requests associated with the context cx. this allows the runtime to perform garbage collection if needed and allows other threads to access objects that the calling thread had locked. the re
turn value is the number of nested requests that were suspended. it may be 0. js_resumerequest resumes the previously suspended requests. the savedepth argument must be the value re
turned by the matching js_suspendrequest call. if savedepth is nonzero and garbage collection is underway, js_resumerequest blocks until the garbage collector is done. jsapi 1.7 and earlier js_suspendrequest and js_resume...
JS_THREADSAFE
_size = recv(socket, buf, size, flags); js_resumerequest(cx, rc); ... } garbage collection requests help make garbage collection safe when multiple threads are using the jsapi. for each thread that is in a request: almost any call into the jsapi may trigger garbage collection; but garbage collection does not happen at any other time (such as, for example, at the moment before the re
turn value of js_newobject is assigned to a rooted variable). these are actually the same rules that apply to single-threaded jsapi programs. but in multithreaded programs, if you break the rules, your program is more likely to crash. this is because in single-threaded programs, a random call into the jsapi is actually pretty unlikely to trigger gc, especially if the calling thread has not been usin...
...x even in js_threadsafe builds, threads cannot safely share objects or strings. instead, data must be copied when it is sent from one thread to another. use js_writestructuredclone to transform data into a flat array of bytes that can be safely written to disk, sent to another process or even another machine, or just passed to another thread. then use js_readstructuredclone on the other side to
turn the serialized data back into javascript objects, strings, and so on. sharing native functions and private data among threads in a js_threadsafe build, spidermonkey's internal data structures that represent javascript values are single-thread-only. in a debug build, this is enforced with assertions. however, spidermonkey does not protect the application's data structures. jsnatives and other c...
JS_ValueToFunction
f the function. unless the function happens to be a native function, this means it isn't attached to any global or enclosing scope, and therefore must not be treated like a real function. instead, use jsval_is_object and js_objectisfunction() to check whether a value is already a function, or use js_convertvalue() to convert a value to jstype_function safely. if v is a function object, this re
turns the associated jsfunction. if v is null, undefined, a boolean, a number, or a string, a typeerror is reported and js_valuetofunction re
turns null. otherwise, v is an object. the javascript engine attempts to convert it to a function. (implementation note: the actual conversion is performed by the object itself. the object's jsobjectops.defaultvalue method is called with hint=jstype_function.)...
...ction. if v is null, undefined, a boolean, a number, or a string, a typeerror is reported and js_valuetofunction re
turns null. otherwise, v is an object. the javascript engine attempts to convert it to a function. (implementation note: the actual conversion is performed by the object itself. the object's jsobjectops.defaultvalue method is called with hint=jstype_function.) js_valuetofunction re
turns a pointer to the converted function. if conversion fails with an error or exception, js_valuetofunction re
turns null. see also mxr id search for js_valuetofunction mxr id search for js_valuetoconstructor ...
JS_ValueToNumber
number converts a javascript value to a number. it implements the tonumber operator described in ecma 262-3 §9.3. if v is already a number, conversion succeeds. if v is undefined, null, false, or true, conversion succeeds, and the result is nan, 0, 0, or 1 respectively. if v is a string, conversion proceeds as specified in ecma 262-3 §9.3.1. js_valuetonumber always succeeds in this case, re
turning js_true. if the string is not a numeric string, *dp is set to nan. otherwise v is an object. js_valuetonumber carries out the following steps to convert it to a number. if at any step an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (this behavior is implemented by v's jsobjectops.defaultvalue hook, so host objects can override it all.) first, the...
...e value, the value is converted to a number as described above and conversion succeeds. otherwise, the resulting object's tostring method, if any, is called. if that produces a primitive value, the value is converted to a number as described above and conversion succeeds. otherwise conversion fails with a typeerror. on success, js_valuetonumber stores the converted value in *dp and re
turns js_true. on error or exception, it re
turns js_false, and the value left in *dp is undefined. see also js_convertarguments js_convertvalue js_gettypename js_typeofvalue js_valuetoint32 js_valuetoecmaint32 bug 884410 ...
JS_ValueToString
sing exponential notation. otherwise v is an object. js_valuetostring uses the steps below to convert it to a string. if at any point an error or exception occurs, or conversion succeeds, the rest of the steps are skipped. (this behavior is implemented by v's jsobjectops.defaultvalue method, so host objects can override it all.) if v.tostring() is a function, it is called. if that method re
turns a primitive value, the value is converted to a string as described above and conversion succeeds. otherwise, the resulting object's jsclass.convert callback is called. for standard classes, this is js_convertstub, which simply calls v.valueof() if present. if the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds. oth...
...onversion succeeds. otherwise, the resulting object's jsclass.convert callback is called. for standard classes, this is js_convertstub, which simply calls v.valueof() if present. if the convert callback produces a primitive value, the value is converted to a string as described above and conversion succeeds. otherwise conversion fails with a typeerror. on success, js_valuetostring re
turns a pointer to a string. on error or exception, it re
turns null. this happens, for example, if v is an object and v.tostring() throws an exception. the resulting jsstring is subject to garbage collection. protect it using a local root, an object property, or the js_addroot function. see also bug 933834 js::tostring ...
JS_VersionToString
re
turns a string representation of a jsversion value. syntax const char * js_versiontostring(jsversion version); name type description version jsversion version value to convert. description js_versiontostring attempts to convert the version to a const char * string representation. ...
... re
turns a string representation of a jsversion value. syntax const char * js_versiontostring(jsversion version); name type description version jsversion version value to convert. description js_versiontostring attempts to convert the version to a const char * string representation. ...
JSAPI reference
obsolete since jsapi 38 js_pusharguments obsolete since javascript 1.8.5 js_pushargumentsva obsolete since javascript 1.8.5 js_poparguments obsolete since javascript 1.8.5 js_addargumentformatter obsolete since jsapi 18 js_removeargumentformatter obsolete since jsapi 18 the following functions convert js values to various types. they can be safely applied to jsvals of any type. they may re
turn new objects. for example, js_valuetoobject(cx, s) where s is a string creates a new string wrapper object. these functions may call javascript methods. for example, js_valuetostring(cx, obj) may call obj.tostring(). js::toboolean added in spidermonkey 17 js::touint16 added in spidermonkey 17 js::toint32 added in spidermonkey 17 js::touint32 added in spidermonkey 17 js::toint64 added in spi...
... js_nextproperty obsolete since jsapi 36 js_setpropertyattributes obsolete since jsapi 26 js_setucpropertyattributes obsolete since jsapi 26 the following functions behave like js_getproperty and js_getpropertybyid except when operating on e4x xml objects. js_getmethod obsolete since jsapi 23 js_getmethodbyid obsolete since jsapi 23 a spidermonkey extension allows a native function to re
turn an lvalue—that is, a reference to a property of an object: js_setcallre
turnvalue2 obsolete since javascript 1.8.5 id a jsid is an identifier for a property or method of an object. struct jsid js_idtovalue js_idtoprotokey added in spidermonkey 31 js_valuetoid js_stringtoid added in spidermonkey 38 js_indextoid added in spidermonkey 17 js_charstoid added in spidermonkey 24 js::pro...
SpiderMonkey 1.8.5
the interface was finalized only after js 1.8.0 shipped, with bug 477187. the primary change in thi...
...rlying functions to retrieve the characters in the string failed. additionally, js_newstring, js_getstringbytes, and js_getstringchars were removed, replaced by fallible interfaces like js_getstringcharszandlength and js_encodestringtobuffer (not an exhaustive list). numbers spidermonkey 1.8.5 now stores integers up to 32-bits in the jsval. this means that the int_fits_in_jsval macro is always re
turns true (be careful to only use this macro with jsints, not 64-bit integers). the jsval now also stores jsdoubles directly, rather than storing them on the heap. the jsval_to_double and double_to_jsval macros have been updated to work directly on jsdoubles rather than their pointers, and the js_newdoublevalue and js_newdouble interfaces have been removed. javascript shell changes there are many new...
SpiderMonkey 1.8
d the object is created with no prototype. js_alreadyhasownproperty and friends are new functions for examining an object without triggering resolve hooks. it was possible to configure spidermonkey 1.7 to treat c/c++ char strings as utf-8 by compiling with a non-default compiler option. in spidermonkey 1.8, it is no longer necessary to make a special build to get this behavior. applications can
turn on utf-8 at run time by calling js_setcstringsareutf8. js_encodestring is a new variation on js_getstringbytes that re
turns a newly allocated, writable buffer which the application must js_free. js_reportallocationoverflow can be used (instead of js_reportoutofmemory) to indicate that the script is trying to do something that would require more memory than the implementation is designed to hand...
...specially helpful. when gc zeal is enabled, gc happens extremely frequently. this makes gc-related problems easier to reproduce, reveals gc problems that you may not have noticed before, and causes gc-safety bugs to surface much closer to their cause. js_dumpheap dumps parts of the gc heap and can help detect leaks. a new gc parameter, jsgc_stackpool_lifespan, controls how eagerly spidermonkey re
turns unused memory back to the system. the new function js_setextragcroots provides another way to protect values from garbage collection. there is a new set of apis for integrating spidermonkey's garbage collector with other memory management systems. these apis are undocumented but fairly stable. the apis include the new jstraceop callback. new javascript shell functions there are a few new bu...
Web Replay
s that should go unrecorded. replaying a replaying content process behaves in the same way as a recording process, except for the following: the calls and mach messages which were intercepted during recording are also intercepted here. when a call/message is intercepted, the wrapped call/message is not performed, but rather the results of the call/message are read from the data stream and re
turned to the caller, emulating the behavior of the call/message. this requires the process to be deterministic enough that events play out in the same order on each thread between recording and replay. the data stream should have enough error checking in place that we can immediately detect if the replay has gone out of sync with the recording. the recorded data streams which specify the acquisiti...
... callbacks. recording an event in one of these areas will fail a !arethreadeventsdisallowed() assertion. these failures usually result from accessing a recorded lock or atomic. core xpcom and mozglue lock classes and mozilla::atomic atomics are recorded by default, but many locks and atomics don't actually need to be recorded in order to correctly replay. recording for a lock or atomic can be
turned off by specifying recordreplay::behavior::dontpreserve in either the lock's contructor argument or the atomic's template arguments. interactions with the middleman process when recording or replaying an execution, there is an extra content process involved, the middleman process as described above. the presence of the middleman requires special handling in ipc internals and some graphics cod...
Using the Places favicon service
s handled by browser/components/places/src/nsnavhistoryexpire.cpp as described in places design. the expiration time is only used to determine whether data should be reloaded from the network (or cache) or whether the version in the database is fresh enough. getting favicon images you can use favicons in the browser ui using special annotation uris. nsifaviconservice.getfaviconimageforpage() re
turns an annotation uri for the favicon for a given page, and nsifaviconservice.getfaviconlinkforicon() re
turns an annotation uri for the given favicon. the annotation service's "moz-anno:" protocol handler notices annotations called "favicon" and forwards these to the favicon service. these annotation uris are described in more detail in using the places annotation service. you should always use nsif...
...notation service's "moz-anno:" protocol handler notices annotations called "favicon" and forwards these to the favicon service. these annotation uris are described in more detail in using the places annotation service. you should always use nsifaviconservice.getfaviconimageforpage() to get the favicon for a page. if the page has no favicon, or we have never heard of the page, this function will re
turn a "chrome:" uri of the default favicon. this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. if there is an error loading the favicon for an annotation uri, the default favicon data will be re
turned by the annotation service's protocol handler. however, since the uri will be different from the default favicon, the decoded image...
extIApplication
fuelibookmarkroots the root bookmarks object for the application. windows readonly attribute nsivariant an array of browser windows within the application. activewindow readonly attribute fueliwindow the currently active browser window. methods quit() attempts to shutdown the application. it is possible for the shutdown to be canceled. boolean quit() re
turn value boolean value indicating whether the shutdown was successful. restart() attempts to restart the application. it is possible for the restart to be canceled. boolean restart() re
turn value boolean value indicating whether the restart was successful. getextensions(acallback) calls acallback with the list of installed extensions. void getextensions(extiextensionscallback acallback) ...
... xpcom although the application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. ...
Creating XPCOM components
ing weblock getting called at startup registering for notifications getting access to the category manager providing access to weblock creating the weblock programming interface defining the weblock interface in xpidl the xpidl syntax scriptable interfaces subclassing nsisupports the web locking interface implementing weblock declaration macros representing re
turn values in xpcom xpidl code generation getting the weblock service from a client implementing the iweblock interface the directory service modifying paths with nsifile manipulating files with nsifile using nsilocalfile for reading data processing the white list data iweblock method by method lock and unlock addsite removesite setsites getnext getsites hasmoreel...
...this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
Interfacing with the XPCOM cycle collector
and can locate ownership cycles that pass in and out of it. how the collector can fail the cycle collector is a conservative device. there are situations in which it will fail to collect a garbage cycle. it does not suspect any pointers by default; objects must suspect themselves, typically by using an nscyclecollectingautorefcnt rather than a nsautorefcnt. it only traverses objects that re
turn a helper object when qi'ed to nsicyclecollectionparticipant. if it encounters an unknown edge during its traversal, it gives up on that edge; this means that every edge involved in a cycle must be participating, otherwise the cycle will not be found. the traverse and unlink methods on the helper object are not magic; they are programmer-supplied and must be correct, or else the collector will fa...
...sfoo.cpp: ns_impl_cycle_collection_class(nsfoo) change the line ns_decl_isupports to ns_decl_cycle_collecting_isupports in the definition of nsfoo. add a line ns_decl_cycle_collection_class(nsfoo) within the public portion of definition of nsfoo. or ns_decl_cycle_collection_class_ambiguous(nsfoo, nsibar) if nsfoo inherits from multiple interfaces, where nsibar is the interface which is re
turned when you queryinterface nsfoo to nsisupports. (we call nsibar the canonical isupports type for nsfoo.) add a line ns_interface_map_entries_cycle_collection(nsfoo) to the interface map of nsfoo in nsfoo.cpp. or if that doesn't work: ns_interface_table_head(nsfoo) ns_interface_table2(nsfoo, nsibar, nsibaz) ns_interface_table_to_map_segue_cycle...
Components.results
against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw components.results.ns_error_unexpected; the elements of the components.results object can be enumerated using a for-in loop. ...
... implemented in javascript by using components.results to get a failure re
turn value if does not implement the given interface. note the common use of an abbreviation for components.results, cr: const ci = components.interfaces, cr = components.results; function class() { /* ... */ } class.prototype = { /* ... ...
Components.utils.cloneInto
this function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it re
turns a reference to the clone: var clonedobject = cloneinto(myobject, targetwindow); you can then assign the clone to an object in the target scope as an expando property, and scripts running in that scope can access it: targetwindow.foo = clonedobject; in this way privileged code, such as an add-on, can share an object with less-privileged code like a normal web page script. syntax components.utils.cloneinto(obj, targetscope[, options]); parameters obj : object the object to clone. targetscope : object the object to attach the object to. options : object this optional parameter is an object with the following o...
... omitted the default value is false. cloned functions have the same semantics as functions exported using components.utils.exportfunction. see cloning objects that have functions below. wrapreflectors: a boolean value that determines if objects reflected from c++, such as dom objects, should be cloned. if omitted the default value is false. see cloning objects that contain dom elements below. re
turns a reference to the cloned object. example this add-on script creates an object, clones it into the content window and makes it a property of the content window global: // add-on script var addonscriptobject = {"greeting" : "hello from add-on"}; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow); scripts running in the page can now access the object: // page script bu...
Components.utils.createObjectIn
ow-for-the-add-on-sdk/. syntax var newobject = components.utils.createobjectin(obj, options); parameters obj an object indicating the compartment in which the new object should be created; the new object will be created in the scope of this object's compartment. options an object containing a single option defineas, which determines the name of the object in the target compartment. ...
...ct should be created; the new object will be created in the scope of this object's compartment. options an object containing a single option defineas, which determines the name of the object in the target compartment. re
turn value a new object in the specified scope. ...
Components.utils.import
parameters url a string of the url of the script to be loaded. the url must point to a file on the disk, possibly in a jar. scope an optional object to import onto; if omitted, the global object is used. under boot2gecko, the scope is not optional. if your code is meant to work on all platforms, you should always provide a scope. in case of doubt, this is generally a good scope. re
turn value the module's global object. use of the re
turn value is discouraged since it grants access to the module's internal properties which are not part of its public api. import throws if it encounters an error (like a syntax error) in the file it reads. example components.utils.import("resource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences fr...
... specified code each time it is invoked, with the caller's global object. components.utils.import evaluates the code of each module only once, in its own scope. for example: var scope1 = {}, scope2 = {}; components.utils.import("resource://gre/modules/json.jsm", scope1); components.utils.import("resource://gre/modules/json.jsm", scope2); assert(scope2.xpcomutils === scope1.xpcomutils); ...re
turns true, whereas: var someurl = "resource://gre/modules/json.jsm"; var obj1 = {}, obj2 = {}; var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript(someurl, obj1); loader.loadsubscript(someurl, obj2); assert(obj2 === obj1); ...re
turns false. this means components.utils.import ...
Components.utils.waiveXrays
any of them, including prototypes and accessors, could have been redefined by the less-privileged code. to undo waivexrays and get xray vision back, call components.utils.unwaivexrays on the object. ...
... the wrappedjsobject property for xrayed objects, but it's more useful because you can call it on primitives or objects that aren't xrays, in which case it just re
turns the argument you passed in. this means you don't have to care whether the initial object is an xray or not. syntax waived = components.utils.waivexrays(obj); parameters obj the object for which we wish to waive xrays. re
turns if the argument obj is an xray, this function re
turns a wrapper that transitively waives xray behavior on the underlying object and anything that comes off the object. if obj is not an xray, this function just re
turns obj. example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content...
Components object
utils.createobjectin creates a new object in the scope of the specified object's compartment. may only be called from j...
... environment. utils.createobjectin creates a new object in the scope of the specified object's compartment. may only be called from javascript code. utils.evalinsandbox runs javascript code in a sandbox, usually used to run code with restricted privileges. utils.forcegc forces a garbage collection cycle. utils.getglobalforobject re
turns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a weak reference for the object passed in. utils.import loads a javascript module into the current script, without sharing a scope. utils.lookupmethod looks up a native (i.e. declared in the interface) method ...
HOWTO
solution 1. ...
...s modules and non-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell. the file uses js modules. maybe it even uses javascript files from chrome:// urls. e.g., you use: components.utils.import("resource://app/modules/gloda/log4moz.js"); however, you get (for that particular line, which is the first import): uncaught exception: [exception... ...
Observer Notifications
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 re
turns. 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 instead of http-on-examine-response when a response will be read completely from the cache. headers are available on the channel. ht...
...d be interested in). topic data description idle the length of time the user has been idle, in milliseconds. sent when the user becomes idle. idle-daily the length of time the user has been idle, in milliseconds. sent once a day while the user is idle. back the length of time the user has been idle, in milliseconds. sent when the user re
turns from being idle. computer sleep and wake this topic indicates when actions related to the computer going to sleep or waking up occur. (note: these notifications are not currently available on linux. see bug 758848.) topic data description sleep_notification null sent when the computer is going to sleep. wake_notification null sent when the ...
NS_InitXPCOM2
« xpcom api reference summary the ns_initxpcom2 function initiates use of xpcom in the calling process. #include "nsxpcom.h" nsresult ns_initxpcom2( nsiservicemanager** aresult, nsifile* abindirectory, nsidirectoryserviceprovider* aappfilelocationprovider ); parameters aresult [out] the resulting xpcom service manager. you may pass null if you are not interested in this re
turn value. the service manager may alternatively be accessed by calling ns_getservicemanager. the resulting interface pointer is addref'd upon re
turn and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom. abindirectory [in] the directory containing the component registry and runtime libraries. pass null to specify that the current working...
...ion is finished with xpcom. abindirectory [in] the directory containing the component registry and runtime libraries. pass null to specify that the current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. re
turn values the ns_initxpcom2 function re
turns ns_ok if successful. otherwise, it re
turns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutd...
NS_InitXPCOM3
t for statically defined xpcom modules. #include "nsxpcom.h" nsresult ns_initxpcom3( nsiservicemanager** aresult, nsifile* abindirectory, nsidirectoryserviceprovider* aappfilelocationprovider, nsstaticmoduleinfo const* astaticmodules, pruint32 astaticmodulecount ); parameters aresult [out] the resulting xpcom service manager. you may pass null if you are not interested in this re
turn value. the service manager may alternatively be accessed by calling ns_getservicemanager. the resulting interface pointer is addref'd upon re
turn and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom. abindirectory [in] the directory containing the component registry and runtime libraries. pass null to specify that the current working...
... [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. astaticmodules [in] an array of nsstaticmoduleinfo objects. passing null causes the default (built-in) static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. re
turn values the ns_initxpcom3 function re
turns ns_ok if successful. otherwise, it re
turns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutd...
NS_NewLocalFile
h. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. re
turn values the ns_newlocalfile function re
turns ns_ok if successful. otherwise, it re
turns an error code. ns_error_file_unrecognized_path indicates that the specified path is invalid. this error is re
turned if a relative file path is passed to ns_newlocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. example code // create a local f...
...urned if a relative file path is passed to ns_newlocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) re
turn rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. nsembedstring is used to convert the ucs-2 character array to an object that can be passed as a const nsastring& parameter. history this function was finalized for mozilla 1.0. see bug 129279 for details. see also nsilocalfile, nsi...
NS_NewNativeLocalFile
h. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. re
turn values the ns_newnativelocalfile function re
turns ns_ok if successful. otherwise, it re
turns an error code. ns_error_file_unrecognized_path indicates that the specified path is invalid. this error is re
turned if a relative file path is passed to ns_newnativelocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. if you use this functio...
...gh the os has no problem dealing with them. do not use this function (on windows) unless it is guaranteed that the full path involved is always ascii. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) re
turn rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter. history this function was finalized for mozilla 1.0. see bug 129279 for details. see also nsilocalfile, nsifile ...
BeginReading
« xpcom api reference summary the beginreading function re
turns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. ...
...e array is determined by the result of the length method. ...
EndReading
the ns_cstringgetdata function can be used to determine if a nsacstring instance has null-terminated storage. example code see beginreading for an example. ...
...the ns_cstringgetdata function can be used to determine if a nsacstring instance has null-terminated storage. example code see beginreading for an example. ...
BeginReading
« xpcom api reference summary the beginreading function re
turns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. ...
...ermined by the result of the length method. ...
EndReading
the ns_cstringgetdata function can be used to determine if a nsastring instance has null-terminated storage. example code see beginreading for an example. ...
...the ns_cstringgetdata function can be used to determine if a nsastring instance has null-terminated storage. example code see beginreading for an example. ...
operator+=
« xpcom api reference summary this operator+= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsastring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. ...
...s operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also append parameters astring [in] a nsastring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also append ...
IAccessibleImage
ser can edit the content that includes an image and therefore the user needs to be able to review the image's position. method overview [propget] hresult description([out] bstr description ); [propget] hresult imageposition([in] enum ia2coordinatetype coordinatetype, [out] long x, [out] long y ); [propget] hresult imagesize([out] long height, [out] long width ); methods description() re
turns the localized description of the image. [propget] hresult description( [out] bstr description ); parameters description the localized description of the image. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. imageposition() re
turns the coordinates of the image. [propget] hresult imageposition( [in] enum ia2coordinatetype coordinatetype, [out] long x, [ou...
...iption( [out] bstr description ); parameters description the localized description of the image. re
turn value s_false if there is nothing to re
turn, [out] value is null. s_ok. imageposition() re
turns the coordinates of the image. [propget] hresult imageposition( [in] enum ia2coordinatetype coordinatetype, [out] long x, [out] long y ); parameters coordinatetype specifies whether the re
turned coordinates should be relative to the screen or the parent object. x the x coordinate. y the y coordinate. re
turn value s_ok. imagesize() re
turns the size of the image in units specified by parent's coordinate system. [propget] hresult imagesize( [out] long height, [out] long width ); parameters height the height of the image. width the width of the image. re
turn value s_ok. ...
amIWebInstallListener
oolean onwebinstallblocked( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs. auri the uri of the site that triggered the installs. ainstalls the addoninstalls that were blocked. acount optional the number of addoninstalls. re
turn value true if the caller should start the installs. onwebinstalldisabled() called when installation by websites is currently disabled. void onwebinstalldisabled( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs. auri the uri of the site that ...
... ...
amIWebInstaller
f add-ons to be installed. ahashes the hashes for the add-ons to be installed. anames the names for the add-ons to be installed. aicons the icons for the add-ons to be installed. acallback optional an optional callback to notify about installation success and failure. ainstallcount optional an optional argument including the number of add-ons to install. ...
...er of add-ons to install. re
turn value true if the installation was successfully started. isinstallenabled() checks if installation is enabled for a web page. boolean isinstallenabled( in astring amimetype, in nsiuri areferer ); parameters amimetype the mime type for the add-on to be installed. areferer the uri of the web page for which to see if installation is allowed. re
turn value true if installation is enabled. ...
imgICache
rvice(components.interfaces.imgitools); var cache = tools.getimgcachefordocument(relevantdocument); // alternatively, tools.getimgcacheforchannel(relevantchannel) if there is no relevant document or channel, null may be passed, but this will cause any image cache requests to use the permanent storage cache (ie. any images from windows in private browsing mode will not be present in the cache re
turned from a call with a null parameter). method overview void clearcache(in boolean chrome); nsiproperties findentryproperties(in nsiuri uri); void removeentry(in nsiuri uri); methods clearcache() evict images from the cache. void clearcache( in boolean chrome ); parameters chrome if true, evict only chrome images. if false,...
...as 'type' and 'content-disposition' 'type' is a nsisupportscstring containing the images' mime type such as 'image/png' 'content-disposition' will be a nsisupportscstring containing the header if you call this before any data has been loaded from a uri, it will succeed, but come back empty. nsiproperties findentryproperties( in nsiuri uri ); parameters uri the uri to look up. re
turn value null if the url was not found in the cache. removeentry() evict images from the cache. void removeentry( in nsiuri uri ); parameters uri the uri to remove. exceptions thrown ns_ok if a uri was removed from the cache. ns_error_not_available if a uri was unable to be removed from the cache. ...
imgILoader
r (may be null) acx some random data. aloadflags load flags for the request. cachekey arequest a newly created, unused imgirequest object or null for one to be created for you. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimage should make sure to cancel() the resulting request before the observer goes away. channelpolicy re
turn value loadimagewithchannel() start the load and decode of an image. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimagewithchannel should make sure to cancel() the resulting request before the observer goes away. imgirequest loadimagewithchannel( in nsichannel achannel, in imgidecoderobserver aobserver, in nsisupports cx, ...
...ust already be opened before this method is called, and there must have been no ondataavailable calls for it yet. aobserver the observer (may be null) cx some random data. alistener a listener that you must send the channel's notifications and data to. can be null, in which case imagelib has found a cached image and is not interested in the data. achannel will be canceled for you in this case. re
turn value supportimagewithmimetype() checks if a decoder for the an image with the given mime type is available. boolean supportimagewithmimetype( in string mimetype ); parameters mimetype the type to find a decoder for. re
turn value true if a decoder is available, false otherwise. ...
jsdIStackFrame
top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. this attribute is only valid for contexts which implement nsiscriptcontext. setting or getting this attribute on any other context will throw a ns_error_no_interface exception. stack frame objects. these are only valid inside the jsdiexecutionhook which gave it to you. after you re
turn 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. method overview boolean eval(in astring bytes, in autf8string filename, in unsigned long line, out jsdivalue result); attributes attribut...
...e |this| object for this stack frame. ...
mozIAsyncFavicons
page uri via setandfetchfaviconforpage will be stored in memory, but may be expired at any time, so you should make an effort to associate favicon uris with page uris as soon as possible. it's better to not use this function for chrome: icon uris since you can reference the chrome image yourself. getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just re
turn the same chrome uri. this function does not send out notifications that the data has changed. pages using this favicons that are visible in history or bookmarks views will keep the old icon until they have been refreshed by other means. void replacefavicondata( in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, [op...
...page uri via setandfetchfaviconforpage will be stored in memory, but may be expired at any time, so you should make an effort to associate favicon uris with page uris as soon as possible. it's better to not use this function for chrome: icon uris since you can reference the chrome image yourself. getfaviconlinkforicon/page will ignore any associated data if the favicon uri is "chrome:" and just re
turn the same chrome uri. this function does not send out notifications that the data has changed. pages using this favicons that are visible in history or bookmarks views will keep the old icon until they have been refreshed by other means. void replacefavicondatafromdataurl( in nsiuri afaviconuri, in astring adataurl, [optional] in prtime aexpiration); parameters afaviconuri ur...
nsIAccessibleEvent
for accessibility events listened to by in-process accessibility clients, which can be used to find out how to get accessibility and dom interfaces for the event and its target. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) attributes attribute type description accessible nsiaccessible the nsiaccessible associated with the event. may re
turn null if no accessible is available. read only. accessibledocument nsiaccessibledocument the nsiaccessibledocument that the event target nsiaccessible resides in. this can be used to get the dom window, the dom document and the window handler, among other things. read only. domnode nsidomnode the nsidomnode associated with the event. may re
turn null if accessible for event has been shut down. ...
... in. this can be used to get the dom window, the dom document and the window handler, among other things. read only. domnode nsidomnode the nsidomnode associated with the event. may re
turn null if accessible for event has been shut down. read only. eventtype unsigned long the type of event, based on the enumerated event values defined in this interface. read only. isfromuserinput boolean re
turns true if the event was caused by explicit user input, as opposed to purely originating from a timer or mouse movement. constants constant gecko version description 1.7 - 1.8.1 1.9 - 1.9.2 2.0 event_show 0x8002 0x0001 an object has been created. event_hide 0x8003 0x0002 an object has been destroyed. event_reorder 0x8004 0x005c 0x0003 an object's children have changed. event_ac...
nsIAccessibleImage
ptable this interface allows in-process accessibility clients to retrieve information about an image. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void getimageposition(in unsigned long coordtype, out long x, out long y); void getimagesize(out long width, out long height); methods getimageposition() re
turns the coordinates of the image accessible. this method is the same as nsiaccessible.getbounds() excepting coordinate origin parameter. void getimageposition( in unsigned long coordtype, out long x, out long y ); parameters coordtype specifies coordinates origin (for available constants refer to nsiaccessiblecoordinatetype). x the x coordinate of the image accessible position. y the y coord...
...signed long coordtype, out long x, out long y ); parameters coordtype specifies coordinates origin (for available constants refer to nsiaccessiblecoordinatetype). x the x coordinate of the image accessible position. y the y coordinate of the image accessible position. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. getimagesize() re
turns the size of the image accessible. this method is the same as nsiaccessible.getbounds(). void getimagesize( out long width, out long height ); parameters width the width of the image accessible. height the height of the image accessible. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleTableCell
accessible/public/nsiaccessibletable.idlscriptable please add a summary to this article. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview boolean isselected(); attributes attribute type description columnextent long re
turn the number of columns occupied by this cell. the result differs from 1 if the specified cell spans multiple columns. read only. columnheadercells nsiarray re
turn an array of column header cells for this cell. read only. columnindex long re
turn column index of this cell. read only. rowextent long re
turn the number of rows occupied by this accessible cell. the result differs from 1 if the specified cell spans multiple rows. read on...
...if the specified cell spans multiple columns. read only. columnheadercells nsiarray re
turn an array of column header cells for this cell. read only. columnindex long re
turn column index of this cell. read only. rowextent long re
turn the number of rows occupied by this accessible cell. the result differs from 1 if the specified cell spans multiple rows. read only. rowheadercells nsiarray re
turn an array of row header cells for this cell. read only. rowindex long re
turn row index of this cell. read only. table nsiaccessibletable re
turn host table accessible. read only. methods isselected() boolean isselected(); parameters none. re
turn value a boolean value indicating whether this cell is selected. ...
nsIApplicationUpdateService
nk that will be notified of state and progress information as the update is downloaded. downloadupdate() starts downloading a software update. astring downloadupdate( in nsiupdate update, in boolean background ); parameters update an nsiupdate object indicating the update to download. background true to download the update in the background or false to download it in the foreground. re
turn value a string indicating the status of the update upon re
turn: "downloading" the update is being downloaded. "pending" the update is ready to be applied. "applying" the update is in the process of being applied. "succeeded" the update has been installed successfully. "download-failed" the update failed to be downloaded. "failed" installing the update failed. pausedownload() pauses the currentl...
...stener ); parameters listener the listener object to remove. selectupdate() selects the best update to install from a provided list of available updates. nsiupdate selectupdate( [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount ); parameters updates an array of updates that are available to install. updatecount the number of updates in the updates array. re
turn value an nsiupdate object indicating the most appropriate update to install. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiupdatepatch nsiupdatemanager nsiupdateprompt nsiupdatetimermanager ...
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 re
turn 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() re
turn true. nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream. method overview void asyncwait(in nsiinputst...
...s closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the input end of a pipe is closed, then writes to the output end of the pipe will fail. the error code re
turned when an attempt is made to write to a "broken" pipe corresponds to the status code passed in when the input end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult astatus ); parameters astatus the error that will be reported if this stream is accessed after it has been closed. ...
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 re
turn 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() re
turn true. nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. method overview void asyncwait(in nsio...
... closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the output end of a pipe is closed, then reads from the input end of the pipe will fail. the error code re
turned when an attempt is made to read to a "closed" pipe corresponds to the status code passed in when the output end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult reason ); parameters reason the error that will be reported if this stream is accessed after it has been closed. ...
nsICache
re stored as streams of data or as objects. this constant specify that cache session is a stream based entry when calling nsicacheservice.createsession() method. non_blocking 0 the synchronous opencacheentry() may be blocking or non-blocking. if a cache entry is waiting to be validated by another cache descriptor (so no new cache descriptors for that key can be created), opencacheentry() will re
turn ns_error_cache_wait_for_validation in non-blocking mode. if the cache entry is validated, then a descriptor for that entry will be created and re
turned. if the cache entry was doomed, then a descriptor will be created for a new cache entry for the key. blocking 1 the synchronous opencacheentry() may be blocking or non-blocking. in blocking mode, it will wait until the cache entry for the key ha...
...if the cache entry was doomed, then a descriptor will be created for a new cache entry for the key. note: if you think that you might need to modify cached data or meta data, then you must open a cache entry requesting write access. only one cache entry descriptor, per cache entry, will be granted write access. ...
nsICachingChannel
may fail if the disk cache is not present. the value of this attribute is usually only settable during the processing of a channel's onstartrequest. the default value of this attribute depends on the particular implementation of nsicachingchannel. cachefile nsifile get the "file" where the cached data can be found. this is valid for as long as a reference to the cache token is held. this may re
turn an error if cacheasfile is false. read only. cacheforofflineuse boolean specifies whether or not the data should be placed in the offline cache, in addition to normal memory/disk caching. this may fail if the offline cache is not present. the value of this attribute should be set before opening the channel. cachekey nsisupports uniquely identifies the data in the cache for this channel. hol...
...be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only see onstartrequest followed by onstoprequest. methods isfromcache() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this method finds out whether or not this channel's data is being loaded from the cache. boolean isfromcache(); parameters none. re
turn value re
turns true if this channel's data is being loaded from the cache, otherwise re
turns false. this value is undefined before the channel fires its onstartrequest notification and after the channel fires its onstoprequest notification. see also nsicache ...
nsICharsetResolver
uestcharset(in nsiwebnavigation awebnavigation, in nsichannel achannel, out boolean awantcharset, out nsisupports aclosure); methods notifyresolvedcharset() some implementations may request that they be notified when the charset is actually detected. void notifyresolvedcharset( in acstring charset, in nsisupports closure ); parameters charset the detected charset. closure the closure re
turned by requestcharset(). requestcharset() called to resolve the charset that should be used for parsing the document being loaded from achannel. if the charset cannot be resolved, but the implementation of nsicharsetresolver wants to be notified of the final resolved charset when one is available, it can set awantcharset to true. if this is done, the caller of requestcharset is responsible for cal...
...t, out nsisupports aclosure ); parameters awebnavigation the nsiwebnavigation the document is being loaded in. may be null. achannel the channel the document is coming in from. awantcharset gets set to true if notifyresolvedcharset() should be called with the given aclosure object. aclosure a resulting object which should be passed to notifyresolvedcharset() if awantcharset is set to true. re
turn value the resolved charset, or an empty string if no charset could be determined. ...
nsIContentSniffer
especially, they should not attempt to set the content type property that subclasses of nsirequest might offer. acstring getmimetypefromcontent( in nsirequest arequest, [const,array,size_is(alength)] in octet adata, in unsigned long alength ); parameters arequest the request where this data came from. may be null. adata data to check. alength length of the data. re
turn value the content type. example how to read content from adata. let charset = "iso-8859-1"; try { // this pref has been removed, see bug 910192 charset = services.prefs.getcomplexvalue("intl.charset.default", ci.nsipreflocalizedstring).data; } catch (e) { } let conv =...
... ci.nsipreflocalizedstring).data; } catch (e) { } let conv = cc["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(ci.nsiscriptableunicodeconverter); conv.charset = charset; try { let str = conv.convertfrombytearray(adata, alength); if (str.substring(0, 5) == "%pdf-") re
turn "application/pdf"; // we detected a pdf file } catch (e) { // try to get information from arequest } ...
nsIContentViewManager
iewsin(in float axpx, in float aypx, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, [optional] out unsigned long alength, [retval, array, size_is(alength)] out nsicontentview aresult); attributes attribute type description rootcontentview nsicontentview the root content view. read only. methods getcontentviewsin() re
turns an array of nsicontentview objects representing all of the content views that intersect with the specified rectangle in the browser. note: the rectangle is specified using an anchor point, then four distances to indicate how far in each direction to expand the rectangle. this lets you, for example, take the coordinates at which the user clicked (or touched) the screen, and expand outward to cre...
... anchor point of the rectangle, in css pixels. atopsize the distance upward from the y anchor to expand the rectangle. arightsize the distance to the right from the x anchor to expand the rectangle. abottomsize the distance downward from the y anchor to expand the rectangle. aleftsize the distance to the left from the x anchor to expand the rectangle. alength optional if specified, on re
turn this parameter indicates the number of nsicontentview objects re
turned in the aresult array. aresult on re
turn, an array of nsicontentview objects representing the content views in the specified rectangle. ...
nsIController
implementation should execute the command with the specified name. void docommand( in string command ); parameters command the name of the command to execute. iscommandenabled() implement this method to indicate whether or not the specified command is enabled. boolean iscommandenabled( in string command ); parameters command the name of the command whose availability is to be checked. re
turn value re
turn true if the specified command is currently available to be used; otherwise, it should re
turn false. onevent() implement this method to process the event with the specified name. void onevent( in string eventname ); parameters eventname the name of the event to process. supportscommand() implement this method to report whether or not the command with the specified name is support...
... to process the event with the specified name. void onevent( in string eventname ); parameters eventname the name of the event to process. supportscommand() implement this method to report whether or not the command with the specified name is supported. boolean supportscommand( in string command ); parameters command the name of the command to determine whether or not it is supported. re
turn value true if the specified command is supported; otherwise false. see also nsicommandcontroller nsicontrollers xul tutorial/commands ...
nsICookieConsent
kie/public/nsicookieconsent.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void getconsent(); methods getconsent() gives a decision on what should be done with a cookie, based on a site's p3p policy and the user's preferences. the policy for the given uri and channel is also re
turned. nscookiestatus getconsent( in nsiuri uri, in nsihttpchannel httpchannel, in boolean isforeign, out nscookiepolicy policy ); parameters uri the uri to find the policy for. httpchannel the channel to extract the p3p headers from. isforeign true if the cookie originates from a third-party site. this is used to decide the cookie status based on user preferences. polic...
... ); parameters uri the uri to find the policy for. httpchannel the channel to extract the p3p headers from. isforeign true if the cookie originates from a third-party site. this is used to decide the cookie status based on user preferences. policy the policy for the given uri, or nsicookie::policy_unknown if one cannot be found. valid values are defined in nsicookie.idl. re
turn value re
turns nscookiestatus. valid values are defined in nsicookie.idl. see also nsicookie ...
nsICookieService
kie string associated with the uri. string getcookiestring( in nsiuri auri, in nsichannel achannel ); parameters auri the uri of the document for which cookies are being queried. achannel the channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. re
turn value re
turns the resulting cookie string. getcookiestringfromhttp() get the complete cookie string associated with the uri. note: this function is redundant and will most likely be removed in a future revision of this interface. getcookiestring() will query the documenturi property off of nsihttpchannelinternal if supported, so getcookiestring() can be used in place of this method. string ...
... auri the uri of the document for which cookies are being queried. afirsturi the uri that the user originally typed in or clicked on to initiate the load of the document referenced by auri. achannel the channel used to load the document. this parameter may be null, but it is strongly recommended that a non-null value be provided to ensure that the cookie privacy preferences are honored. re
turn value re
turns the resulting cookie string. setcookiestring() set the cookie string associated with the uri. note: should be able to allow null aprompt, since nsiprompt can be queried from achannel. void setcookiestring( in nsiuri auri, in nsiprompt aprompt, in string acookie, in nsichannel achannel ); parameters auri the uri of the document for which cookies are being que...
nsIDOMHTMLAudioElement
[implicit_jscontext] unsigned long mozwriteaudio(in jsval data); methods mozcurrentsampleoffset() 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. re
turns the current offset of the audio stream, specified as the number of samples that have played since the beginning of the stream. unsigned long long mozcurrentsampleoffset(); parameters none. re
turn value an unsigned 64-bit value indicating how many audio samples have been played since the stream began playing. mozsetup() non-standard this feature is non-standard and is not on a sta...
...io stream should use. specify 1 for mono or 2 for stereo. rate the sampling rate to use on the stream, in samples per second. for example, specify 44100 for 44.1khz. mozwriteaudio() writes samples to the audio stream. unsigned long mozwriteaudio( in jsval data ); parameters data the samples to write into the audio stream, specified either as a javascript array or as a numeric typed array. re
turn value the actual number of bytes written to the stream. exceptions thrown ns_error_dom_invalid_state_err the stream has not been initialized for writing by a call to mozsetup(). ns_error_dom_type_mismatch_err the data isn't a valid data type (an array or typed array of numeric values). ns_error_dom_index_size_err the number of samples specified doesn't divide evenly across the number of channels...
nsIDOMHTMLTimeRanges
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 float start(in unsigned long index); float end(in unsigned long index); attributes attribute type description length unsigned long the number of ranges represented by the nsidomhtmltimeranges object. read only. methods end() re
turns the time offset to the end of the specified time range. float end( in unsigned long index ); parameters index the index to the time range whose end time is to be re
turned. re
turn value the time at which the specified range ends, in seconds measured from the beginning of the timeline represented by the object. exceptions thrown index_size_err the specified index is not valid. start() retur...
... re
turn value the time at which the specified range ends, in seconds measured from the beginning of the timeline represented by the object. exceptions thrown index_size_err the specified index is not valid. start() re
turns the time offset to the start of the specified time range. float start( in unsigned long index ); parameters index the index to the time range whose start time is to be re
turned. re
turn value the time at which the specified range starts, in seconds measured from the beginning of the timeline represented by the object. exceptions thrown index_size_err the specified index is not valid. ...
nsIDOMWindow
age session storage for the current browsing context. data stored in session storage may be accessed by any site in the browsing context. read only.note: prior to gecko 8.0 this attribute was part of nsidomstoragewindow. textzoom float get or set the document scale factor as a multiplier of the default size. when setting this attribute, an ns_error_not_implemented error may be re
turned by implementations not supporting zoom. this attribute should always re
turn 1.0 for implementations not supporting text zoom. 1.0 represents normal (unzoomed) size. native code only! top nsidomwindow the root window for the hierarchy of windows that contain this nsidomwindow. this is the window itself if there is no parent, or if the parent is of a different type. the window hier...
...s window as well as every other window nested in that window root. read only. native code only! note: prior to gecko 7.0 this attribute was part of nsidomwindow2. methods getcomputedstyle() see dom-window-getcomputedstyle for details. nsidomcssstyledeclaration getcomputedstyle( in nsidomelement elt, in domstring pseudoelt optional ); parameters elt pseudoelt optional re
turn value getselection() re
turns the nsiselection object indicating what if any content is currently selected in the window. nsiselection getselection(); parameters none. re
turn value the nsiselection object for the window. scrollby() scrolls the window by a given number of pixels relative to the current scroll position. void scrollby( in long xscrolldif, in long yscrolldif ); para...
nsIDOMXPathExpression
nsisupports evaluate( in nsidomnode contextnode, in unsigned short type, in nsisupports result ); parameters contextnode a dom node to evaluate the xpath expression against. ...
...s contextnode a dom node to evaluate the xpath expression against. to evaluate against a whole document, use the document.documentelement method to get the node to evaluate against. type a number that corresponds to one of the type constants of nsidomxpathresult. result an existing nsidomxpathresult to use for the result. using null will create a new nsidomxpathresult. re
turn value an xpath result. see also introduction to using xpath in javascript nsidomxpathevaluator document.evaluate document object model (dom) level 3 xpath specification nsidomxpathresult ...
nsIDialogParamBlock
tring( in print32 inindex, in wstring instring); attributes attribute type description objects nsimutablearray a place where you can store an nsimutablearray to pass nsisupports. methods getint() get a previously set integer. print32 getint( in print32 inindex ); parameters inindex the index of the integer to get. must be in the range 0..7. ...
...setint() void setint( in print32 inindex, in print32 inint ); parameters inindex the index of the integer to set. must be in the range 0..7. ...
nsIDirectoryServiceProvider
1.7 nsidirectoryserviceprovider. method overview nsifile getfile(in string prop, out prbool persistent); methods getfile() the directory service calls this method when it gets the first request for a prop or on every request if the prop is not persistent. nsifile getfile( in string prop, out prbool persistent ); parameters prop the symbolic name of the file. persistent true if the re
turned file will be cached by directory service. subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. re
turn value the nsifile represented by the property. example this code creates a global, read-only string called currdir with the value of the current working directory. __definegetter__("currdir",...
...for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. re
turn value the nsifile represented by the property. example this code creates a global, read-only string called currdir with the value of the current working directory. __definegetter__("currdir", function getcurrdir() { re
turn components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryserviceprovider) .getfile("curworkd",{}).path; }); test it with to see the magic happen. alert(currdir); see also nsdirectoryservice nsidirectoryservice additionally, see section 16.5.2 of the ra...
nsIDirectoryServiceProvider2
xpcom/io/nsidirectoryservice.idlscriptable an extension of nsidirectoryserviceprovider which allows multiple files to be re
turned for the given key. inherits from: nsidirectoryserviceprovider last changed in gecko 0.9.6 method overview nsisimpleenumerator getfiles(in string prop); methods getfiles() the directory service calls this when it gets a request for a prop and the requested type is nsisimpleenumerator. nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. re
turn value an enumerator for a list of file locations. the elements in the enumeration are nsifile. use an xpcom re
turn code of ns_success_aggregate_result if this result should be aggregated with other "lower" providers. if you are implementing this from js, ...
... nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. re
turn value an enumerator for a list of file locations. the elements in the enumeration are nsifile. use an xpcom re
turn code of ns_success_aggregate_result if this result should be aggregated with other "lower" providers. if you are implementing this from js, you would be using components.re
turncode, but sadly this does not currently work (see bug 287107). ...
nsIEditorMailSupport
oid inserttextwithquotations(in domstring astringtoinsert); void pasteascitedquotation(in astring acitation, in long aselectiontype); void pasteasquotation(in long aselectiontype); void rewrap(in boolean arespectnewlines); void stripcites(); methods getembeddedobjects() get a list of img and object tags in the current document. nsisupportsarray getembeddedobjects(); parameters none. re
turn value an nsisupportsarray containing the img and object tags of the current document. insertascitedquotation() insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any), including, if possible, a "cite" attribute. nsidomnode insertascitedquotation( in astring aquotedtext, in astring acitation, in boolean ainserthtml ); param...
... (whose representation is dependent on the editor type), replacing the selected text (if any), including, if possible, a "cite" attribute. nsidomnode insertascitedquotation( in astring aquotedtext, in astring acitation, in boolean ainserthtml ); parameters aquotedtext the actual text to be quoted. acitation the "mid" url of the source message. ainserthtml insert as html? (vs plaintext) re
turn value the nsidomnode which was inserted. insertasquotation() insert a string as quoted text (whose representation is dependent on the editor type), replacing the selected text (if any). nsidomnode insertasquotation( in astring aquotedtext ); parameters aquotedtext the actual text to be quoted. re
turn value the nsidomnode which was inserted. inserttextwithquotations() inserts a plain text str...
nsIErrorService
errormodule); void unregistererrorstringbundlekey(in nsresult error); methods geterrorstringbundle() retrieves a string bundle url for an error module. string geterrorstringbundle( in short errormodule ); parameters errormodule the module for which the string bundle is registered. error modules are obtained from nsresult code with ns_error_get_module. re
turn value the url of the string bundle registered for that module. geterrorstringbundlekey() retrieves a key in a string bundle for an nsresult error code. if no key is registered for the specified nsresult, then the caller should use the nsresult's code (obtained with ns_error_get_code) instead. string geterrorstringbundlekey( in nsresult error ); parameters error the nsresult for ...
...that module. geterrorstringbundlekey() retrieves a key in a string bundle for an nsresult error code. if no key is registered for the specified nsresult, then the caller should use the nsresult's code (obtained with ns_error_get_code) instead. string geterrorstringbundlekey( in nsresult error ); parameters error the nsresult for which the string bundle key is to be retrieved. re
turn value the key to use to retrieve the error string from the nsresult's module's string bundle. registererrorstringbundle() registers a string bundle url for an error module. void registererrorstringbundle( in short errormodule, in string stringbundleurl ); parameters errormodule the module for which the string bundle is to be registered. should be one of the modules listed in x...
nsIEventTarget
entthread(); void postevent(in pleventptr aevent); native code only! obsolete since gecko 1.9 constants dispatch flags constant value description dispatch_normal 0 this flag specifies the default mode of event dispatch, whereby the event is simply queued for later processing. when this flag is specified, dispatch() re
turns immediately after the event is queued. dispatch_sync 1 this flag specifies the synchronous mode of event dispatch, in which the dispatch() method does not re
turn until the event has been processed. note: passing this flag to dispatch may have the side-effect of causing other events on the current thread to be processed while waiting for the given eve...
... exceptions thrown ns_error_unexpected indicates that the thread is shutting down and has finished processing events, so this event would never run and has not been dispatched. ns_error_invalid_arg indicates that event is null. isoncurrentthread() check to see if this event target is associated with the current thread. boolean isoncurrentthread(); parameters none. re
turn value re
turns true if events dispatched to this event target will run on the current thread (that is, the thread calling this method). if events dispatched to this target will be processed on another thread, re
turns 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...
nsIExternalHelperAppService
ion() determines whether or not data whose filename has the specified extension should be decoded from the specified encoding type before being saved or delivered to helper applications. boolean applydecodingforextension( in autf8string aextension, in acstring aencodingtype ); parameters aextension the filename extension to check. aencodingtype the encoding type to check. re
turn value true if data from urls with the specified extension and encoding should be decoded prior to saving the file or delivering it to a helper application; otherwise false. docontent() binds an external helper application to a stream listener. the caller should pump data into the re
turned stream listener. when the onstoprequest is issued, the stream listener implementation will launch the helper ...
...the content type of the incoming data. arequest the request corresponding to the incoming data. awindowcontext use nsiservicemanager.getinterface() to retrieve properties like the dom window or parent window; the service might need this in order to bring up dialogs. aforcesave true to always save this content to disk, regardless of nsimimeinfo and other such influences. re
turn value a nsistreamlistener which the caller should pump the data into. ...
nsIFeedTextConstruct
t those as well. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by: @mozilla.org/feed-textconstruct;1, but users usually don't need to create instances of this directly. various other feed-related interfaces, such as nsifeed, nsifeedentry, and nsifeedcontainer have attributes that re
turn objects implementing nsifeedtextconstruct. method overview nsidomdocumentfragment createdocumentfragment(in nsidomelement element); astring plaintext(); attributes attribute type description base nsiuri if the text construct contains html or xhtml, relative references in the content should be resolved against this base uri. lang ...
...content described; one of "text", "html", or "xhtml". methods createdocumentfragment() creates a new document fragment on a given dom element, containing the text and (if the text construct contains html or xhtml) its markup. nsidomdocumentfragment createdocumentfragment( in nsidomelement element ); parameters element the element in which to create the new document fragment. re
turn value an nsidocumentfragment containing the text and markup. plaintext() re
turns the text as plain text with all markup stripped and all entities decoded. astring plaintext(); parameters none. re
turn value the plain text version of the text construct's contents. if the type attribute is "text", this method re
turns the value of the text attribute unchanged. remarks if the document type ...
nsIJetpack
in jsval areceiver ); parameters amessagename the name of the message from the jetpack process on which the callback is triggered. areceiver a javascript function. the first argument passed to it is the name of the message, and all arguments following it are either json-serializable types or handles. if the message was sent synchronously from the jetpack process via callmessage(), then the re
turn value of this function is passed back to the jetpack process. unregisterreceiver() this unregisters a callback previously registered with registerreceiver() void unregisterreceiver( in astring amessagename, in jsval areceiver ); parameters amessagename the name of the message on which the callback should no longer be triggered. areceiver the javascript function that should no longer be tri...
... 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 contents of the script to evaluate in the jetpack process. createhandle() this creates an opaque handle that can transparently be exchanged between processes. nsivariant createhandle(); parameters none. re
turn value the new handle. destroy() this terminates the jetpack process. void destroy(); parameters none. special messages if an exception goes uncaught in the jetpack process, it will be reported to the chrome process via a message with the name core:exception. the message comes with one argument, which represents the exception object that was thrown. warning: bug 589308 prevents this message from ...
nsILoadGroup
objects. inherits from: nsirequest last changed in gecko 1.7 method overview void addrequest(in nsirequest arequest, in nsisupports acontext); void removerequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatus); attributes attribute type description activecount unsigned long re
turns the count of "active" requests (that is requests without the load_background bit set). read only. defaultloadrequest nsirequest accesses the default load request for the group. each time a number of requests are added to a group, the defaultloadrequest may be set to indicate that all of the requests are related to a base request. the load group inheri...
...roup's load flags are not changed. groupobserver nsirequestobserver the group observer is notified when requests are added to and removed from this load group. the groupobserver is weak referenced. notificationcallbacks nsiinterfacerequestor notification callbacks for the load group. requests nsisimpleenumerator re
turns the requests contained directly in this group. enumerator element type: nsirequest. read only. methods addrequest() adds a new request to the group. this will cause the default load flags to be applied to the request. if this is a foreground request then the groupobserver's onstartrequest will be called. if the request is the default load request or if the default load request is null, ...
nsIMemoryReporter
ecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by calling nsimemoryreportermanager.registerreporter(). once that has been done, the reporter will be found by any client accessing the enumerator re
turned by nsimemoryreportermanager.enumeratereporters(). this includes the about:memory page. note: this interface is undergoing heavy development, and is subject to rapid changes. attributes attribute type description amount print64 the numeric value reported by the memory reporter, specified in the units indicated by the units attribute. read only. note...
...t is specified as a number of bytes. units_count 1 the amount is an instantaneous count of things currently in existence. for example, the number of tabs currently open. units_count_cumulative 2 the amount contains the number of times some event has occurred since the application started up. for example, the number of times the user has opened a new tab. the amount re
turned must never decrease over the lifetime of the application. units_percentage 3 the amount contains a fraction that should be expressed as a percentage. note: the amount field should be given a value 100 times the actual percentage; this number will be divided by 100 when shown. this allows a fractional percentage to be shown even though amount is an integer. for example ...
nsIMicrosummarySet
toolkit/components/places/public/nsimicrosummaryservice.idlscriptable this interface provides access to sets of microsummaries re
turned from the nsimicrosummaryservice. 1.0 66 introduced gecko 1.8 obsolete gecko 6.0 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void addobserver(in nsimicrosummaryobserver observer); nsisimpleenumerator enumerate(); void removeobserver(in nsimicrosummaryobserver observer); methods addobserver() add a microsummary observer to this microsummary set. adding an observer to a set is the equiva...
...a microsummary observer to this microsummary set. adding an observer to a set is the equivalent of adding it to each constituent microsummary. void addobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to add. enumerate() retrieve an nsisimpleenumerator of microsummaries in the set. nsisimpleenumerator enumerate(); parameters none. re
turn value an enumerator of nsimicrosummary objects. removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. see also nsimicrosummaryservice microsummary topics creating a microsummary ...
nsIMsgDatabase
t. in 4.x, it was mainly used to remove corrupted databases. void forceclosed(); clearcachedhdrs() void clearcachedhdrs(); resethdrcachesize() void resethdrcachesize(in unsigned long size); getmsghdrforkey() nsimsgdbhdr getmsghdrforkey(in nsmsgkey key); parameters key getmsghdrformessageid() nsimsgdbhdr getmsghdrformessageid(in string messageid); parameters messageid containskey() re
turns whether or not this database contains the given key. boolean containskey(in nsmsgkey key); parameters key createnewhdr() must call addnewhdrtodb after creating. the idea is that you create a new header, fill in its properties, and then call addnewhdrtodb. addnewhdrtodb will send notifications to any listeners. nsimsgdbhdr createnewhdr(in nsmsgkey key); addnewhdrtodb() void addnewhdrtodb(i...
... out unsigned long len); comparecollationkeys() [noscript] long comparecollationkeys(in octetptr key1, in unsigned long len1, in octetptr key2, in unsigned long len2); getnewlist() the list of messages currently in the new state. if there are no such messages, null may be re
turned. the caller should free when done using nsmemory.free(). void getnewlist(out unsigned long count, [array, size_is(count)] out nsmsgkey newkeys); getcachedhits() these are used for caching search hits in a database, to speed up saved search folders. nsisimpleenumerator getcachedhits(in string asearchfolderuri); refreshcache() void refreshcache(in string asearchfolderuri, ...
nsIMsgFilterCustomAction
identify this filter action. * recommended form: extensionname@example.com#actionname */ readonly attribute acstring id; /* action name to display in action list. this should be localized. */ readonly attribute astring name; /** * is this custom action valid for a particular filter type? * * @param type the filter type * @param scope the search scope * * @re
turn true if valid */ boolean isvalidfortype(in nsmsgfiltertypetype type, in nsmsgsearchscopevalue scope); /** * after the user inputs a particular action value for the action, determine * if that value is valid. * * @param actionvalue the value entered. * @param actionfolder folder in the filter list * @param filtertype filter type (manual, ...
...olean isvalidfortype(in nsmsgfiltertypetype type, in nsmsgsearchscopevalue scope); /** * after the user inputs a particular action value for the action, determine * if that value is valid. * * @param actionvalue the value entered. ...
nsIMsgThread
the thread. void addchild(in nsimsgdbhdr child, in nsimsgdbhdr inreplyto, in boolean threadinthread, in nsidbchangeannouncer announcer); parameters child the message to add inreplyto the message this should be in reply to threadinthread announcer an nsidbchangeannouncer to receive notification when the change is made. getchildat() re
turns the message at an index. nsimsgdbhdr getchildat(in long index); parameters index the index to get the message from getchildkeyat() nsmsgkey getchildkeyat(in long index); parameters index the index to get the key from getchild() nsimsgdbhdr getchild(in nsmsgkey msgkey); parameters msgkey the index to get the key from getchildhdrat() nsimsgdbhdr getchildhdrat(in lon...
...tchildkeyat() nsmsgkey getchildkeyat(in long index); parameters index the index to get the key from getchild() nsimsgdbhdr getchild(in nsmsgkey msgkey); parameters msgkey the index to get the key from getchildhdrat() nsimsgdbhdr getchildhdrat(in long index); parameters index the index to get the message from. getroothdr() nsimsgdbhdr getroothdr(out long index); re
turn index changed to the index of the root. removechildat() void removechildat(in long index); parameters index the index to remove the message from removechildhdr() void removechildhdr(in nsimsgdbhdr child, in nsidbchangeannouncer announcer); parameters child the message to remove announcer an nsidbchangeannouncer to receive notification when the change is made. markchild...
nsIParentalControlsService
ontrol filters. this method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requesturioverride( in nsiuri atarget, in nsiinterfacerequestor awindowcontext optional ); parameters atarget the uri to be overridden. awindowcontext optional the window generating the event. re
turn value true if the block was successfully overridden, otherwise false. requesturioverrides() requests that a set of uris be allowed through the parental control filters. this method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requesturioverrides( in nsiarray atargets, in ns...
... ...
nsIPipe
null to use the default allocator) remarks the reader and writer of a pipe do not have to be on the same thread. as a result, the pipe is an ideal mechanism to bridge data exchange between two threads. for example, a worker thread might write data to a pipe from which the main thread will read. each end of the pipe can be either blocking or non-blocking. recall that a non-blocking stream will re
turn ns_base_stream_would_block if it cannot be read or written to without blocking the calling thread. for example, 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 ...
...s_base_stream_would_block if it cannot be read or written to without blocking the calling thread. for example, 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 re
turn 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 nsiasyncinputst...
nsIPrivateBrowsingService
of the private browsing feature offered in firefox 3.5 and later. when firefox is in private browsing mode, firefox shouldn't save any potentially private information. the browser itself stops caching, and also doesn't record history information. in addition, temporary, databases are created to be used for cookies and local storage; these databases are thrown away when private browsing mode is
turned off, and the regular databases are re-activated. the temporary cookie and local storage databases start out empty. extensions that record potentially private information should use this interface to detect whether private browsing mode is enabled, and if it is, avoid saving that information. for details on how to do this, see the article supporting private browsing mode. similarly, plug-ins c...
... lastchangedbycommandline boolean indicates whether or not the last private browsing mode transition was performed on the command line (using either the -private or -private-toggle switches) rather than the user interface. read only. privatebrowsingenabled boolean indicates whether or not private browsing mode is currently enabled. you may also
turn private browsing mode on and off by setting the value of this attribute. changing this value while handling one of the notifications generated by the private browsing service throws an ns_error_failure exception. methods removedatafromdomain() removes all data stored for the specified domain, including its subdomains. void removedatafromdomain( in autf8string adomain ); parameters ...
nsIProfile
an existing directory may be used; otherwise, the profile directory will be unique. deleteprofile() deletes the specified profile. void deleteprofile( in wstring name, in boolean candeletefiles ); parameters name the name of the profile to delete. candeletefiles if true, the profile manager will try to delete all of the profile's files and its directory. getprofilelist() re
turns an array of strings indicating the names of all the available profiles. void getprofilelist( out unsigned long length, [retval, array, size_is(length)] out wstring profilenames ); parameters length on re
turn, contains the number of profiles in the profilenames array. profilenames on re
turn, contains an array of all of the available profiles' names. profileexists() determin...
...renameprofile() renames an existing profile. void renameprofile( in wstring oldname, in wstring newname ); parameters oldname the name of the profile to rename. newname the new name to assign to the profile. ...
nsIProperties
ated with a particular name. void get( in string prop, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters prop the property name. iid the desired interface. result the resulting object instance. exceptions thrown ns_error_failure if the property does not exist. ns_error_no_interface if the property exists, but does not support the requested interface. getkeys() re
turns an array of property names. nsmemory.h defines the macro ns_free_xpcom_allocated_pointer_array, which can be used to free akeys when it is no longer needed. void getkeys( out pruint32 count, [array, size_is(count), retval] out string keys ); parameters count the length of the result array. keys the resulting array of keys. has() tests if a property exists. boolean has( in string prop );...
...defines the macro ns_free_xpcom_allocated_pointer_array, which can be used to free akeys when it is no longer needed. void getkeys( out pruint32 count, [array, size_is(count), retval] out string keys ); parameters count the length of the result array. keys the resulting array of keys. has() tests if a property exists. boolean has( in string prop ); parameters prop the property name. re
turn value true if the property exists, false if the property does not exist. set() sets the xpcom object associated with a particular name. void set( in string prop, in nsisupports value ); parameters prop the property name. value the xpcom object value to associate with prop. undefine() undefines a property. void undefine( in string prop ); parameters prop the property name. remarks this...
nsIProtocolProxyCallback
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 re
turned 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 n...
... 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 the reason for the failure and aproxyinfo will be null. the value re
turned from asyncresolve. see also nsicancelable nsiuri nsiproxyinfo nsiprotocolproxyservice ...
nsISSLErrorListener
see also nsisockettransport ...
...uestor socketinfo, in print32 error, in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obtain more information about the active connection. error the code associated with the error. the ssl status object that describes the problem(s). targetsite the site name that was used to open the current connection. re
turn value the consumer shall re
turn true if it wants to suppress the error message related to the error (the connection will still get canceled). see also nsisockettransport ...
nsIScreen
requires gecko 13.0(firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) constant value description rotation_0_deg 0 0° of rotation (that is, no rotation, or default orientation). rotation_90_deg 1 90° of rotation. rotation_180_deg 2 180° of rotation. rotation_270_deg 3 270° of rotation. methods getavailrect() re
turns a rectangle indicating the portion of the screen that is available for use. note: this re
turns a rectangle representing the region of the screen that is available for application use. for example, this would exclude the area occupied by the menu bar and dock on mac os x. void getavailrect( out long left, out long top, out long width, out long height ); parameters left the left ...
... the menu bar and dock on mac os x. void getavailrect( out long left, out long top, out long width, out long height ); parameters left the left edge of the available screen rectangle. top the top edge of the available screen rectangle. width the width of the available screen rectangle. height the height edge of the available screen rectangle. getrect() re
turns a rectangle indicating the entire screen's coordinate space. void getrect( out long left, out long top, out long width, out long height ); parameters left the left edge of the screen's rectangle. top the top edge of the screen's rectangle. width the width of the screen's rectangle. height the height edge of the screen's rectangle. lockminimumbrightness(...
nsIScriptError
category of error that occurred see categories for a list. read only. columnnumber pruint32 the column number where the error occurred. this is used to draw the arrow pointing to the problem character. read only. errormessage astring the error message in a string format without any context/line number information. note: nsiconsolemessage.message will re
turn the error formatted with file/line information. read only. flags pruint32 flags; see flag constants for a list. read only. innerwindowid unsigned long long the inner window id with which the error is associated. this is zero if the error was initialized by calling nsiscripterror.init() instead of initwithwindowid(). read only. linenumber pruint...
... message. there are quite a few category strings and they aren't listed in a single place, so you may need to search the firefox code to find the one you want. see categories for a partial list. innerwindowid the id of the inner window associated with the error. tostring() outputs a string representing the error message described by the object. autf8string tostring(); parameters none. re
turn value a string representing the error message described by the nsiscripterror object. examples logging a message with additional information in this example nsiscripterror, which implements nsiconsolemessage, is used to log information to the console including information about the source file and line number of the error. function mylogtoconsole(amessage, asourcename, asourceline, alinenumb...
nsIScriptableUnescapeHTML
ent a string of html or xml source to parse as a fragment. isxml set this to true if the fragment is an xml string; otherwise set it to false. baseuri pointer to the base uri against which to resolve any uris included in the fragment. this parameter is ignored if isxml is false. element the nsidomelement to be used as the context node for the purposes of the fragment parsing algorithm. re
turn value an nsidomdocumentfragment of the element with the new text appended. exceptions thrown ns_error_failure unable to append the text to the element. unescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils:...
...nescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this method. astring unescape( in astring src ); parameters src the html string to convert into plain text. re
turn value the result of the plain text conversion. exceptions thrown ns_error_failure unable to convert the string. see also nsidomdocumentfragment nsiuri nsidomelement ...
nsIScriptableUnicodeConverter
ed long alen,[array, size_is(alen),retval] out octet adata); nsiinputstream converttoinputstream(in astring astring); attributes attribute type description charset string current character set. throws ns_error_uconv_noconv if the requested charset is not supported. methods convertfromunicode() converts the data from unicode to one charset. re
turns the converted string. after converting, finish should be called and its re
turn value appended to this re
turn value. acstring convertfromunicode( in astring asrc ); finish() re
turns the terminator string. should be called after convertfromunicode() and appended to that function's re
turn value. acstring finish(); converttounicode() converts the data from one charset to unicode. astring ...
...ng acount ); converttobytearray() convert a unicode string to an array of bytes. finish does not need to be called. void converttobytearray(in astring astring, out unsigned long alen, optional [array, size_is(alen),retval] out octet adata ); converttoinputstream() converts a unicode string to an input stream. the bytes in the stream are encoded according to the charset attribute. the re
turned stream is non-blocking. nsiinputstream converttoinputstream( in astring astring ); parameters astring the text to encode to the stream. the text is encoded into the character set specified by the charset attribute. re
turn value an nsiinputstream that will present the text specified in astring as its data. examples see reading textual data and writing textual data for examples. ...
nsISimpleEnumerator
tion of xpcom objects and provides methods to access elements sequentially. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsisupports getnext(); boolean hasmoreelements(); methods getnext() called to retrieve the next element in the enumerator. the "next" element is the first element upon the first call. must be preceded by a call to hasmoreelements() which re
turns pr_true. this method is generally called within a loop to iterate over the elements in the enumerator. nsisupports getnext(); parameters none. re
turn value ns_ok if the call succeeded in re
turning a non-null value through the out parameter. ns_error_failure if there are no more elements to enumerate. hasmoreelements() called to determine whether or not the enumerator has any elements that can b...
..._true. this method is generally called within a loop to iterate over the elements in the enumerator. nsisupports getnext(); parameters none. re
turn value ns_ok if the call succeeded in re
turning a non-null value through the out parameter. ns_error_failure if there are no more elements to enumerate. hasmoreelements() called to determine whether or not the enumerator has any elements that can be re
turned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getnext() calls. does not affect internal state of enumerator. boolean hasmoreelements(); parameters none. re
turn value pr_true if there are remaining elements in the enumerator. pr_false if there are no more elements in the ...
nsIStreamListener
m ainputstream, in unsigned long aoffset, in unsigned long acount); methods ondataavailable() this method is called when the next chunk of data for the ongoing request may be read without blocking the calling thread. the data can be read from the nsiinputstream object passed as the argument to this method. note: your implementation of this method must read exactly acount bytes of data before re
turning. void ondataavailable( in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount ); parameters arequest an nsirequest indicating the source of the data. acontext a user-defined context value. ainputstream an nsiinputstream from which the data is to be read. aoffset number of bytes that were sent in previous on...
...tream an nsiinputstream from which the data is to be read. aoffset number of bytes that were sent in previous ondataavailable() calls for this request. in other words, the sum of all previous count parameters. if that number is greater than or equal to 2^32, this parameter will be pr_uint32_max (2^32 - 1). acount the number of bytes available for reading. you must read all of these bytes before re
turning to the caller. note: throwing an exception will cancel the request. ...
nsIStringBundleOverride
to load. method overview nsisimpleenumerator enumeratekeysinbundle(in autf8string url); astring getstringfromname(in autf8string url, in acstring key); methods enumeratekeysinbundle() get all override keys for a given string bundle. nsisimpleenumerator enumeratekeysinbundle( in autf8string url ); parameters url the url of the original string bundle whose keys are to be overridden. re
turn value an enumeration of nsipropertyelement objects for the keys that are overridden in the given string bundle. note that these keys may not exist in the original string bundle. getstringfromname() get the override value for a particular key in a particular string bundle. astring getstringfromname( in autf8string url, in acstring key ); parameters url the url of the original string bundle w...
...that are overridden in the given string bundle. note that these keys may not exist in the original string bundle. getstringfromname() get the override value for a particular key in a particular string bundle. astring getstringfromname( in autf8string url, in acstring key ); parameters url the url of the original string bundle whose keys are to be overridden. key the key to be overridden. re
turn value the override value. an exception is thrown if the key has not been overridden. however, no exception is thrown if the original string bundle did not have the key. ...
nsIStringEnumerator
xpcom/ds/nsistringenumerator.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview astring getnext(); boolean hasmore(); methods getnext() called to retrieve the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which re
turns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. astring getnext(); parameters none. re
turn value the next string in the enumerator. throws an exception if there are no more strings. hasmore() called to determine whether or not the enumerator has any strings that can be re
turned via getnext(). this method is generally used to determine whethe...
...if there are no more strings. hasmore() called to determine whether or not the enumerator has any strings that can be re
turned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getnext() calls. does not affect internal state of enumerator. boolean hasmore(); parameters none. re
turn value true if there are remaining strings in the enumerator. false if there are no more strings in the enumerator. ...
nsISupports
dref();violates the xpcom interface guidelines void queryinterface(in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); nsrefcnt release();violates the xpcom interface guidelines methods violates the xpcom interface guidelines addref() notifies the object that an interface pointer has been duplicated. nsrefcnt addref(); parameters none. re
turn value an integer value that is generally ignored. queryinterface() the queryinterface method provides runtime type discovery. note: the interface pointer, aresult, re
turned by queryinterface must be released by a call to release() when it is no longer needed. queryinterface is a symmetric, transitive, and reflexive operator. void queryinterface( in nsiidref uuid, [iid_is(uuid),retval] out...
... interface result the resulting interface pointer. exceptions thrown ns_error_no_interface the requested interface is not available. violates the xpcom interface guidelines release() notifies the object that an interface pointer has been destroyed and any resources the object held on behalf of the client can be released. nsrefcnt release(); parameters none. re
turn value an integer value that is generally ignored. remarks the method descriptions above were taken from essential com by don box. the point of those descriptions is to highlight the fact that addref() and release() do not necessarily correspond to incrementing and decrementing a counter, respectively, even though that is how they are usually implemented. on win32 systems, nsisupports is abi-compa...
nsITaskbarWindowPreview
wcontroller.drawpreview() and nsitaskbarpreviewcontroller.drawthumbnail() methods will be called to draw the preview. if false, the operating system draws these for you. constants constant value description num_toolbar_buttons 7 the maximum number of toolbar buttons supported by the windows taskbar api. methods getbutton() re
turns the specified button from the preview's toolbar. note: by default, all buttons are hidden. you must fetch and configure each button that you want to make visible. nsitaskbarpreviewbutton getbutton( in unsigned long index ); parameters index the index into the button array for the nsitaskbarpreviewbutton to retrieve. this value must be at least 0 (the leftmost button) and less t...
...the preview's toolbar. note: by default, all buttons are hidden. you must fetch and configure each button that you want to make visible. nsitaskbarpreviewbutton getbutton( in unsigned long index ); parameters index the index into the button array for the nsitaskbarpreviewbutton to retrieve. this value must be at least 0 (the leftmost button) and less than num_toolbar_buttons. re
turn value an nsitaskbarpreviewbutton describing the requested button. see also nsitaskbarpreview nsitaskbarpreviewcontroller nsitaskbartabpreview nsitaskbarpreviewbutton nsiwintaskbar ...
nsIThreadManager
eady have a nsithread associated with it, one is created and associate with the current prthread. read only. ismainthread boolean this attribute is true if the calling thread is the main thread of the application process. read only. mainthread nsithread the main thread. read only. methods native code only!getthreadfromprthread given a prthread, this method re
turns the corresponding nsithread. re
turns null if there isn't a corresponding nsithread. nsithread getthreadfromprthread( in prthread prthread ); parameters prthread the prthread for which to retrieve the corresponding nsithread. re
turn value the nsithread matching the specified prthread, or null if there is no matching nsithread. newthread() create a new thread. internally, this is a g...
... parameters prthread the prthread for which to retrieve the corresponding nsithread. re
turn value the nsithread matching the specified prthread, or null if there is no matching nsithread. newthread() create a new thread. internally, this is a global user prthread. nsithread newthread( in unsigned long creationflags ); parameters creationflags reserved for future use. pass 0. re
turn value the newly created nsithread. see also the thread manager nsithread nsithreadpool nsithreadinternal nsithreadobserver nsithreadeventfilter prthread ...
nsITraceableChannel
it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, re
turning the listener previously assigned to the channel. nsistreamlistener setnewlistener( in nsistreamlistener alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel. re
turn value the previous listener for the channel. each listener call through to the previous listener for every call, in order to establish a call chain to allow all interested ...
... onstoprequest: function(arequest, acontext, astatuscode) { this.responsebody = this.receivedchunks.join(""); delete this.receivedchunks; this.responsestatus = astatuscode; this.originallistener.onstoprequest(arequest, acontext, astatuscode); this.deferreddone.resolve(); }, queryinterface: function(aiid) { if (aiid.equals(ci.nsistreamlistener) || aiid.equals(ci.nsisupports)) { re
turn this; } throw cr.ns_nointerface; } }; var httpresponseobserver = { observe: function(asubject, atopic, adata) { var newlistener = new tracinglistener(); asubject.queryinterface(ci.nsitraceablechannel); newlistener.originallistener = asubject.setnewlistener(newlistener); /////// end - do not edit newlistener.promisedone.then( function() { // no error happened console.log(...
nsITreeColumn
ecolumns.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void getidconst([shared] out wstring idconst); native code only! nsitreecolumn getnext(); nsitreecolumn getprevious(); void invalidate(); attributes attribute type description atom nsiatom the atom attribute of nsitreecolumn which re
turns an nsiatom for the column, making it fast to do comparisons. read only. native code only! columns nsitreecolumns the nsitreecolumns containing this column. read only. cycler boolean if true, then the column is a cycler column. if the cycler attribute is not set, the column cells are regular text cells. read only. editable boolean if true the nsitreecolumn content is editable. if the edita...
...treecolumn. read only. constants constant value description type_text 1 text column type. type_checkbox 2 checkbox column type. type_progressmeter 3 progress meter column type. methods native code only!getidconst void getidconst( [shared] out wstring idconst ); parameters idconst getnext() get the next column in the nsitreecolumns. nsitreecolumn getnext(); parameters none. re
turn value the next nsitreecolumn in the nsitreecolumns. getprevious() get the previous column in the nsitreecolumn. nsitreecolumn getprevious(); parameters none. re
turn value the previous nsitreecolumn in the nsitreecolumns. invalidate() void invalidate(); parameters none. see also nsitreecolumns ...
nsIURLFormatter
%locale%/ method overview astring formaturl(in astring aformat); astring formaturlpref(in astring apref); methods formaturl() formats a string url. the set of known variables is predefined. if a variable is unknown, it is left unchanged and a non-fatal error is reported. astring formaturl( in astring aformat ); parameters aformat unformatted url as a string. ...
...ables is predefined. if a variable is unknown, it is left unchanged and a non-fatal error is reported. astring formaturl( in astring aformat ); parameters aformat unformatted url as a string. re
turn value the formatted url. formaturlpref() formats a string url stored in a preference. if the preference value cannot be retrieved, a fatal error is reported and the "about:blank" url is re
turned. astring formaturlpref( in astring apref ); parameters apref a string representing the name of the preference from which to fetch the url to format. re
turn value the formatted url re
turned by formaturl(), or "about:blank". ...
nsIWebBrowser
method will be called to register an object to receive nsiwebprogresslistener or nsishistorylistener notifications in which case the the iid is that of the interface. void addwebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be added. aiid the iid of the interface that will be called on the listener as appropriate. re
turn value ns_ok listener was successfully added. ns_error_invalid_arg one of the arguments was invalid or the object did not implement the interface specified by the iid. removewebbrowserlistener() removes a previously registered listener. void removewebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be removed. ...
...of the arguments was invalid or the object did not implement the interface specified by the iid. removewebbrowserlistener() removes a previously registered listener. void removewebbrowserlistener( in nsiweakreference alistener, in nsiidref aiid ); parameters alistener the listener to be removed. aiid the iid of the interface on the listener that will no longer be called. re
turn value ns_ok listener was successfully added. ns_error_invalid_arg one of the arguments was invalid or the object did not implement the interface specified by the iid. see also nsibasewindow nsicontextmenulistener nsidomwindow nsiembeddingsitewindow nsiinterfacerequestor nsishistorylistener nsitooltiplistener nsiuricontentlistener nsiweakreference nsiwebbrowserchrome ...
nsIWebBrowserChrome
hods destroybrowserwindow() asks the implementer to destroy the window associated with this webbrowser object. void destroybrowserwindow(); parameters none. exitmodaleventloop() exit a modal event loop if we're in one. the implementation should also exit out of the loop if the window is destroyed. void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to re
turn from showasmodal(). iswindowmodal() is the window modal (that is, currently executing a modal loop)? boolean iswindowmodal(); parameters none. re
turn value true if it's a modal window. setstatus() called when the status text in the chrome needs to be updated. void setstatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting the text.
...'s a modal window. setstatus() called when the status text in the chrome needs to be updated. void setstatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting the text. status status string. null is an acceptable value meaning no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. re
turn value note: the function error code re
turned by this corresponds to the status value specified in exitmodaleventloop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx new width of the browser. acy new height of the browser. ...
nsIWebBrowserFind
r to match case (case sensitive) when searching. default is false. searchframes boolean whether to search through all frames in the content area. default is true. note: that you can control whether the search propagates into child or parent frames explicitly using nsiwebbrowserfindinframes, but if one, but not both, of searchsubframes and searchparentframes are set, this re
turns false. searchstring wstring the string to search for. this must be non-empty to search. wrapfind boolean whether the search wraps around to the start (or end) of the document if no match was found between the current position and the end (or beginning). works correctly when searching backwards. default is false. methods findnext() finds, highlights, and scroll...
...see also nsiwebbrowserfindinframes ...
nsIWebBrowserPersist
persistflags unsigned long flags governing how data is fetched and saved from the network. it is best to set this value explicitly unless you are prepared to accept the default values. progresslistener nsiwebprogresslistener callback listener for progress notifications. the object that the embbedder supplies may also implement nsiinterfacerequestor and be prepared to re
turn nsiauthprompt or other interfaces that may be required to download data. result unsigned long value indicating the success or failure of the persist operation. read only. constants constant value description persist_flags_none 0 no special persistence behavior. persist_flags_from_cache 1 only use cached data (could result in fail...
...nvert links to absolute links where possible. encode_flags_encode_w3c_entities 256 attempt to encode entities standardized at w3c (html, mathml, and so on.). this is a catch-all flag for documents with mixed contents. beware of interoperability issues. see below for other flags which might likely do what you want. encode_flags_cr_linebreaks 512 output with carriage re
turn line breaks. may also be combined with encode_flags_lf_linebreaks and if neither is specified, the platform default format is used. encode_flags_lf_linebreaks 1024 output with linefeed line breaks. may also be combined with encode_flags_cr_linebreaks and if neither is specified, the platform default format is used. encode_flags_noscript_content 2048 for plain text ou...
nsIWorkerFactory
dom/interfaces/threads/nsidomworkers.idlscriptable creates and re
turns a new worker 1.0 66 introduced gecko 2.0 obsolete gecko 8.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface was removed in gecko 8.0. you don't need to use it anymore to create workers from chrome. instead, you can just do new worker or new chromeworker. implemented by: threads/workerfactory;1. ...
...stead, you can just do new worker or new chromeworker. implemented by: threads/workerfactory;1. to create an instance, use: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); method overview nsiworker newchromeworker(in domstring ascripturl); methods newchromeworker() re
turns a new chromeworker that will run a specified script. nsiworker newchromeworker( in domstring ascripturl ); parameters ascripturl the url of the script to load into the new worker. re
turn value an nsiworker object representing the new chromeworker. see also using web workers worker sharedworker ...
nsIXFormsModelElement
exceptions thrown domexception if there is no matching instance data. rebuild() signals the xforms processor to rebuild any internal data structures used to track computational dependencies within the given xforms model. void rebuild(); parameters none. recalculate() signals the xforms processor to perform a full recalculation of the given xforms model. note...
...hanged in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview nsidomdocument getinstancedocument(in domstring instanceid); void rebuild(); void recalculate(); void refresh(); void revalidate(); methods getinstancedocument() nsidomdocument getinstancedocument( in domstring instanceid ); parameters instanceid the id of the instance element to be re
turned. re
turn value an nsidomdocument. exceptions thrown domexception if there is no matching instance data. rebuild() signals the xforms processor to rebuild any internal data structures used to track computational dependencies within the given xforms model. void rebuild(); parameters none. recalculate() signals the xforms processor to perform a full recalculation of the given xforms model. note: script in...
nsIXULTemplateResult
the action body from a template as the replacement text. for instance, if the text ?name appears in an attribute within the action body, it will be replaced with the result of this method. the question mark is considered part of the variable name, thus avar should be ?name and not simply name. astring getbindingfor( in nsiatom avar ); parameters avar the variable to look up. re
turn value the value for the variable or a null string if it has no value. getbindingobjectfor() get an object value for a variable such as ?name for this result. this method may re
turn null for a variable, even if getbindingfor() re
turns a non-null value for the same variable. this method is provided as a convenience when sorting results. nsisupports getbindingobjectfor( in nsiatom avar ); paramet...
...hasbeenremoved() indicate that the output for a result has been removed and that the result is no longer being used by the builder. void hasbeenremoved(); parameters none. ...
nsIXULWindow
his case.) aalert true to move the window to an alert position, generally centered horizontally and 1/3 down from the top. createnewwindow() create a new window. nsixulwindow createnewwindow( in print32 achromeflags, in nsiappshell aappshell ); parameters achromeflags see nsiwebbrowserchrome. aappshell the app shell passed to nsiappshellservice's createtoplevelwindow method. re
turn value the newly minted window. in the case of a content window, the function creates a browser window and waits for it to load. you can then load a document into the window's primary content shell. getcontentshellbyid() the content shell specified by the supplied id. note: that this is a docshell tree item and therefore can not be assured of what object it is. it could be an editor, a docshel...
...be assured of what object it is. it could be an editor, a docshell, or a browser object. or down the road any other object that supports being a docshelltreeitem query accordingly to determine the capabilities. nsidocshelltreeitem getcontentshellbyid( in wstring id ); parameters id the id of the content shell, which is the same as the "type" attribute on the containing frame element. re
turn value the tree item corresponding to the given id, if any. removechildwindow() tell this window that it has lost a child xul window. note that xul windows do not currently track child xul windows. void removechildwindow( in nsixulwindow achild ); parameters achild the child window being removed. showmodal() shows the window as a modal window. that is, ensures that it is visible and...
NS_CStringContainerInit2
pt data passed into ns_cstringcontainerinit2 is not copied. instead, the string takes ownership over the data pointer. the caller must have allocated the data array using the xpcom memory allocator. this flag should not be combined with ns_cstring_container_init_depend. ns_cstring_container_init_substring data passed into ns_cstringcontainerinit2 is a substring that is not null-terminated. re
turn values the ns_cstringcontainerinit function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks after a nscstringcontainer object has been initialized via ns_cstringcontainerinit2, it may be used as an ordinary nsacstring object. when the string object is no longer needed, it should be passed to ns_cstringcontainerfinish to free any extra memory that the string object ma...
...nerally better to use one of the helper classes, such as nscstring, instead of coding directly to ns_cstringcontainerinit2 because those classes take care of cleaning up the string object when it goes out of scope. when ns_cstringcontainerinit2 is told to copy adata, the copy it creates is null-terminated. this is significant as it allows the programmer to be certain that ns_cstringgetdata will re
turn a null-terminated character array. the ns_cstringcontainerinit function is equivalent to calling ns_cstringcontainerinit with adata=nsnull and aflags=0. history this function was finalized for mozilla 1.8. see bug 264274 for details. see also ns_cstringcontainerinit, ns_cstringcontainerfinish ...
NS_CStringGetData
ringgetdata( const nsacstring& astring, const char** adata, prbool* aterminated = nsnull ); parameters astring [in] a nsacstring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. it may be null if the caller is not interested in this information. re
turn values the ns_cstringgetdata function re
turns the length of adata, measured in storage units (bytes). example code // count the number of times a particular character appears in a string. pruint32 countchar(const nsacstring& str, char c) { const char* data; pruint32 len = ns_cstringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ...
...see bug 239123 for details. ...
NS_StringGetData
er. this is a low-level api. #include "nsstringapi.h" pruint32 ns_stringgetdata( const nsastring& astring, const prunichar** adata, prbool* aterminated ); parameters astring [in] a nsastring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. ...
...stringapi.h" pruint32 ns_stringgetdata( const nsastring& astring, const prunichar** adata, prbool* aterminated ); parameters astring [in] a nsastring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. re
turn values the ns_stringgetdata function re
turns the length of adata, measured in storage units (bytes). example code pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* data; pruint32 len = ns_stringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } re
turn count; } history this function was frozen for mozilla 1.7. ...
XPCOM string functions
xpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions. ns_cstringappenddatathe ns_cstringappenddata function appends data to the existing value of a nsacstring instance. ...
...n of the string's internal buffer. this is a low-level api.ns_cstringtoutf16the ns_cstringtoutf16 function converts the value of a nsacstring instance to utf-16 and stores the result in a nsastring instance. ns_stringappenddatathe ns_stringappenddata function appends data to the existing value of a nsastring instance. this is a low-level api.ns_stringclonedatathe ns_stringclonedata function re
turns a null-terminated, heap allocated copy of the string's internal buffer.ns_stringcontainerfinishthe ns_stringcontainerfinish function releases any memory allocated by a nsstringcontainer instance. this is a low-level api.ns_stringcontainerinitthe ns_stringcontainerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api.ns_stringcopythe ns_stringcopy ...
wrappedJSObject
edjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating one. for simplicity we omit the component registration code. suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function helloworld() { }; helloworld.prototype = { hello: function() { re
turn "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns_error_no_interface; re
turn this; } }; xpconnect wrapping now let's get a reference to our component. in this example we use getservice, but as long as we get the reference from xp...
...nderlying js object directly using the wrapper.wrappedjsobject property if the wrapped object allows this. more specifically, as xpconnect source comments say, you can get comp.wrappedjsobject if three conditions are met: comp really is an xpconnect wrapper around a js object. wrappers around non-js objects don't have this property. the underlying object has a wrappedjsobject property that re
turns a js object. nsixpcsecuritymanager allows access (see the source code comments for details; this is usually not an issue for mozilla extensions and applications) this means that in order to access the js object implementing our component directly, we must modify the component. for example: function helloworld() { this.wrappedjsobject = this; }; now we can get the component directly: var...
Autoconfiguration in Thunderbird
luded. this allows to autoconfigure almost 50% of our user's email accounts. it was added because we cannot assume that all big isps (including microsoft) will set up a configuration server for thunderbird. configuration server at isp isps have the option to provide their configuration information themselves directly to users, by setting up a web server at autoconfig.<domain>, which simply re
turns a static xml file with the configuration, as described below. for more complicated setups, for example when the login name does not appear in the email address, the xml file can also be generated by the isp. in such complicated cases, this is the only way to allow an automatic setup. configuration file on harddisk local administrators may place a configuration file in the thunderbird installa...
...toconfig/ servername autoconfig.hoster.com <directory /var/www/autoconfig> order allow,deny allow from all </directory> </virtualhost> if you use nginx, you can easily add a subdomain to all your domains, which does the same as above. either, you can redirect them to a common hostname: server { listen 10.2.3.4:80; #use your server's public ip here! server_name autoconfig.*; re
turn 301 http://autoconfig.hoster.com$request_uri; } or serve them directly from a common directory: server { listen 10.2.3.4:80; #again, use your server's public ip here! server_name autoconfig.*; location / { root /var/www/autoconfig; } } ssl https was added in june 2019 to the spec. please use https whenever possible. former versions of this spec defined http only. http is still support...
Mail composition back end
notified of the progress and completion of the copy operation. nsimsgsendlistener the following describes the methods of the nsimsgsendlistener interface: onstartsending the onstartsending interface is called when the sending operation has begun. this is called after messages creation has completed. if message creation fails, the nsimsgsend operation will re
turn an ns_failed() re
turn code. ns_imethod onstartsending(const char *amsgid, - the message id for the message being sent pruint32 amsgsize) = 0; - the total message size for the message being sent onprogress the onprogress interface is called with progress notification on the send operation. ns_imethod onprogress(const char *amsgid, - the messa...
.... this will be called in the case of both success and failure. ns_imethod onstopsending(const char *amsgid, - the message id for the message being sent nsresult astatus, - the resulting status for the send operation const prunichar *amsg, - a message concerning the status of the send operation nsifilespec *re
turnfilespec) = 0; - an nsifilespec which will specify the file that was created (this is used if the dont_deliver_p argument is set to pr_true) nsimsgcopyservicelistener the nsimsgcopyservicelistener interface will notify the implementor or the progress and completion of the copy operation that follows successful send operations. onstartcopy the onstartcopy...
Using C struct and pointers
ype() factory method of the ctypes object to create a ctype object that represents the c struct named st_t. the first parameter of this method is the name of the type, which corresponds to the name of the c struct. the second parameter is an array of field descriptors. each field descriptor contains the name and field type of the corresponding field of the c struct. ...
...in the js-ctypes context, you can only operate on buffers of known capacity. therefore, the size of the buffer must be specified. ...
Declaring and Calling Functions
functions are declared using the library object's declare() method. once declared, functions can be called using standard function syntax. prerequiste understanding see abi. example: no input parameters in this example, we declare the libc clock() function, which re
turns the elapsed time since system startup, then fetch and output that value. const clock = lib.declare("clock", ctypes.default_abi, ctypes.unsigned_long); console.log("clocks since startup: " + clock()); the clock() function requires no input parameters; it simply re
turns an unsigned long. example: multiple input parameters this example declares the libc asctime() function, which converts a time structure into a string. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); for a m...
...ters; it simply re
turns an unsigned long. example: multiple input parameters this example declares the libc asctime() function, which converts a time structure into a string. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); for a more complete version of this example (including the implementation of the struct_tm type), see the structures example. re
turned values if the re
turn type can fit into a javascript number without loss (that is, it's a number 32 bits or smaller, or is a double or float), then the function just re
turn a javascript number. for everything else it re
turns a ctypes object representing the re
turn value (including 64-bit integers). ...
ctypes.open
art of js-ctypes is the ctypes.open() function. this must be called before any work can commence. there are two options: custom native file (dll, so, dylib, etc.) standard os libraries custom native file for this method, a native file must be created. a native file for use on unix systems is an so file, which is created and a c function called add() is written. int add(int a, int b) { re
turn a + b; } to make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fpic -c mycfuntionsforunix.c gcc -shared -o mycfuntionsforunix.so mycfuntionsforunix.o a file named mycfuntionsforunix.so is successfully created. this native file can be placed in any folder of an addon and then loaded from js-ctypes. they can also be loade...
...\asynczip@jetpack" var filepath_mylib = os.path.join(filepath_folder, 'mysubfolder', 'mycfunctionsforunix.so'); var jarpath_mylib = jarpath_folder + 'mysubfolder/mycfunctionsforunix.so'; } this can then be opened and the c functions within can be used from js-ctypes. ...
Scripting plugins - Plugins
e plugin control the origin of the calling code, so that the plugin can specify the origin of calls that come from internally loaded code from other origins. this way such code can be executed with only the privileges of the origin of the code, and not the privileges of the plugin page's origin. ...
...dow that loaded the plugin can do this by getting the npobject for the browser's window object, or the dom element that loaded the plugin. this is done by using an extension to npn_getvalue. the extensions are two additions to the npnvariables enumeration; the new enumerations are npnvwindownpobject and npnvpluginelementnpobject. calling npn_getvalue() with either of those new enumerations will re
turn an npobject representing the browser object, and from there, the functions in this api can be used to get and set properties, and to call methods on those browser objects. and as always when working with reference counted npobjects, the caller is responsible for calling npn_releaseobject on the npobject to drop the reference. the new npnvariable enumerations are defined in npapi.h as: npnvwind...
Search - Firefox Developer Tools
searching for files to search for a particular file, press control + p (or command + p on a mac) and type the search term. the source pane will display a list of all matching files as you type. you can use the up and down arrows to move through the list, and re
turn to open the file you want: searching within a file to search for a particular substring in the file currently loaded into the source pane, press control + f (or command + f on a mac) while the source pane is focused. press re
turn to search. the debugger will display the number of matches in the code and highlight each result: using the outline tab if you are searching for a specific function within the current javascript file, you can use the outline tab in the debugger to find it quickly. the outline tab lists the functio...
...hen you are searching through a file with dozens of functions, it comes in handy. searching in all files you can also search for a string in all of the files included in the currently opened project. press shift + ctrl + f (windows and linux) or shift + cmd + f (macos) and then enter the string you are trying to find. if the string exists in any of the files in the project, the search will re
turn a list showing a list by file and line number. click on any entry in the list to go directly to the line in the file where the string occurs. ...
Step through code - Firefox Developer Tools
can step through it using four buttons in the toolbar: in order, the buttons are: play: run to the next breakpoint step over: advance to the next line in the same function. step in: advance to the next line in the function, unless on a function call, in which case enter the function being called step out: run to the end of the current function, in which case, the debugger will skip the re
turn value from a function, re
turning execution to the caller split console when paused, you can press the esc key to open and close the split console to gain more insight into errors and variables: pause on breakpoints overlay since firefox 70, when your code is paused on a breakpoint an overlay appears on the viewport of the tab you are debugging. this lets you know what kind of breakpoi...
...ging. this lets you know what kind of breakpoint the code is paused on (breakpoint, event breakpoint, etc.), and also provides a step button and a play button. the thinking here is that if you've got your devtools open in a separate window, as many people do, it can be easier to have the buttons available right there to move the code forward while you are looking at the result. if you want to
turn this feature off, since firefox 71 you can do so by going to about:config in a new tab, setting the devtools.debugger.features.overlay pref to false, and restarting the browser. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more informati...
DOM allocation example - Firefox Developer Tools
this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
...of dom nodes: var toolbarbuttoncount = 20; var toolbarcount = 200; function getrandomint(min, max) { re
turn math.floor(math.random() * (max - min + 1)) + min; } function createtoolbarbutton() { var toolbarbutton = document.createelement("span"); toolbarbutton.classlist.add("toolbarbutton"); // stop spidermonkey from sharing instances toolbarbutton[getrandomint(0,5000)] = "foo"; re
turn toolbarbutton; } function createtoolbar() { var toolbar = document.createelement("div"); // stop spidermonkey from sharing instances toolbar[getrandomint(0,5000)] = "foo"; for (var i = 0; i < toolbarbuttoncount; i++) { var toolbarbutton = createtoolbarbutton(); toolbar.appendchild(toolbarbutton); } re
turn toolbar; } function createtoolbars() { var container = document.gete...
Monster example - Firefox Developer Tools
this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
... = 48; function monster() { function randomint(min, max) { re
turn math.floor(math.random() * (max - min + 1)) + min; } function randomname() { var chars = "abcdefghijklmnopqrstuvwxyz"; var namelength = randomint(min_name_length, max_name_length); var name = ""; for (var j = 0; j < namelength; j++) { name += chars[randomint(0, chars.length-1)]; } re
turn name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = randomint(0, 250); } function makemonsters() { var monsters = { "friendly": [], "fierce": [], "undecided": [] }; for (var i = 0; i < monster_count; i++) { monsters.friendly.push(new monster()); } for (var i = 0; i < monster_count; i++) { monsters.fierce.push(new...
Examine and edit CSS - Firefox Developer Tools
ates of the button may be difficult to distinguish visually. they typically produce a similar effect. examine computed css to see the complete computed css for the selected element, select the computed panel in the righthand pane. this panel shows the calculated value that each css property has for the selected element. (this calculated value is exactly the same as what getcomputedstyle would re
turn.) you can tab through the styles to select them, and you can find more information about each property — pressing f1 on a selected property will open up its mdn reference page. clicking the arrow next to the property name (or pressing enter or space while it is selected) shows the rule that set this value, along with a link to the source filename and line number: by default, this view on...
...e page. clicking the arrow next to the property name (or pressing enter or space while it is selected) shows the rule that set this value, along with a link to the source filename and line number: by default, this view only shows values that have been explicitly set by the page: to see all values, click the "browser styles" box. you can tab through the filenames/line numbers; pressing enter/re
turn will open up the relevant file at that point in the style editor. typing in the search box performs a live filtering of the list, so, for example, if you just want to see font-related settings, you can type "font" in the search box, and only properties with "font" in the name will be listed. you can also search for the values of properties: to find the rule responsible for setting the font to "l...
Examine and edit HTML - Firefox Developer Tools
ou open the inspector on a page that includes custom elements, you can view the class definition for the custom element in the debugger: inspect the element click on the word custom the source for the element's class will be displayed in the debugger. whitespace-only text nodes web developers don’t write all their code in just one line of text. they use white space such as spaces, re
turns, or tabs between their html elements because it makes markup more readable. usually this white space seems to have no effect and no visual output, but in fact, when a browser parses html it will automatically generate anonymous text nodes for elements not contained in a node. this includes white space (which is after all a type of text). if these auto generated text nodes are inline level, bro...
..."reveal" link alongside it. clicking the "reveal" link will highlight the element with the slot attribute as it exists outside the shadow dom this is very useful when you've got a <slot> element and you can't find the source of its content. note: shadow dom inspection was implemented in firefox 61, but was hidden behind the dom.webcomponents.shadowdom.enabled pref until firefox 63. it is now
turned on by default. element popup context menu you can perform certain common tasks on a specific node using a popup context menu. to activate this menu, context-click the element. the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create new node duplicate node delete node attributes add at...
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
bove and below screenshots should give you further hints on how to get to this. grid options the grid section of the layout view looks like this: you'll see a number of options contained within: overlay grid: contains a checkbox for each grid present on the page, along with various options. allows overlay views to be toggled on and off. grid display settings: display line numbers:
turn the line numbers shown for each grid overlay on and off (on by default). display area names:
turn area names on and off, in the case of grids with named grid areas (on by default, where relevant). extend lines infinitely: by default, grid lines/tracks are only shown inside the element with display: grid set on it; when toggling this option on, the grid lines extend to the edge of the viewpo...
...ry for the subgrid is indented under its parent in the overlay grid section. when you select the checkbox for the subgrid, the lines for the parent grid are displayed also displayed; if the checkbox for the parent grid is unselected, then its lines are translucent. display line numbers by default, the line numbers are displayed on the grid overlay. unchecking the "display line numbers" box
turns them off. display area names in a grid with named areas, the area names are shown on the grid overlay by default. unchecking the "display area names" box
turns them off. extend lines infinitely by default, the grid lines/tracks are only shown inside the element with display: grid set on it. when you check the "extend lines infinitely" option, the grid lines extend to the edge of th...
Console messages - Firefox Developer Tools
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 collection of invalidating changes and recalculate their effect at once. however, if some javascript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to re
turn. for example, code like this will cause an immediate, synchronous, reflow, when it calls window.getcomputedstyle(thing).height: var thing = document.getelementbyid("the-thing"); thing.style.display = "inline-block"; var thingheight = window.getcomputedstyle(thing).height; because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the do...
... input to the interpreter, and its value appears as a response. copy object copies the selected object to the clipboard. filtering and searching filtering by category you can use the toolbar along the top to constrain the results displayed. to see only messages of particular categories, click the button labeled with that category (errors, css, and so on). for errors and warnings, when you
turn off display of the category, a number appears next to the button text to indicate how many messages of that type are available. for example, "warnings (25)". network requests with response codes in the 400-499 (client error) or 500-599 (server error) ranges are considered errors. their display is controlled by the errors button, not the requests button. filtering by text to see only messages t...
AddressErrors.organization - Web APIs
an object based on addresserrors includes an organization property when the address's organization property couldn't be validated. the re
turned string explains the error and should offer suggestions for how to correct it. syntax var organizationerror = addresserrors.organization; value if the value specified in the paymentaddress object's organization property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. ...
...resserrors.organization; value if the value specified in the paymentaddress object's organization property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. for example, if validation simply ensures that only permitted characters are included in the organization's name, this might re
turn a string such as "the organization name may only contain the letters a-z, digits, spaces, and commas." if the organization value was validated successfully, this property is not included in the addresserrors object. specifications specification status comment payment request apithe definition of 'addresserrors.organization' in that specification. candidate recommenda...
AddressErrors - Web APIs
the addresserrors dictionary is used by the payment request api to to report validation errors in a physical address (typically a billing address or a shipping address). any members which is present indicates that a validation error occurred for the member of the same name in an address described using paymentaddress. addresserrors is the type of the object re
turned by shippingaddresserrors in the paymentdetailsupdate passed into paymentrequestupdateevent.updatewith() by the shippingaddresschange event handler if a change to the address resulted in a validation error occurring. see the examples below to see how this works. properties addressline a domstring which, if present, indicates that the addressline property of the paymentaddress could not be validated. the contents of the strin...
...properties' values are taken from defaultpaymentdetails. the final step is to call the event's updatewith() method, passing along the updatedetails object. this lets the payment request api know to present the specified error or errors but to allow the user to keep trying to edit the address. setting up the donate now button this code creates a handler for the load event on the window which in
turn adds the needed click event handler to the "donate now" button so that clicking it starts the payment process. window.addeventlistener("load", function(ev) { document.getelementbyid("pay").addeventlistener("click", process, false); }, false); see addeventlistener() for information about event handlers and how they work. html here's the simple html for this example. <p>donate us $65 to ou...
AnalyserNode.getByteTimeDomainData() - Web APIs
han the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. ...
...hould be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data re
turned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to. if the array has fewer elements than the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. re
turn value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). ...
AnalyserNode.getFloatFrequencyData() - Web APIs
t precision, you can use analysernode.getbytefrequencydata() instead, which works on a uint8array. syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.frequencybincount); // float32array should be the same length as the frequencybincount void analyser.getfloatfrequencydata(dataarray); // fill the float32array with data re
turned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to. for any sample which is silent, the value is -infinity. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. re
turn value none. example const audioctx = new ...
...de.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. re
turn value none. example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data re
turned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode. while the audio is playing, we collect the frequency data repeatedly with requestanimationframe() and draw a "winamp bargraph style" to a <canvas> element. for more complete applie...
Animation.finish() - Web APIs
nterface sets the current playback time to the end of the animation corresponding to the current playback direction. that is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its reverse() method called), it sets the playback time to 0. syntax animation.finish(); parameters none. re
turn value none. exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof in...
... working draft ...
Animation.finished - Web APIs
the animation.finished read-only property of the web animations api re
turns a promise which resolves once the animation has finished playing. every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property. the new promise will resolve once the new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
...e new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { re
turn animation.finished } ) ).then( function() { re
turn elem.remove(); } ); specifications specification status comment web animationsthe definition of 'animation.finished' in that specification. working draft editor's draft. ...
AnimationEvent() - Web APIs
syntax animationevent = new animationevent(type, {animationname: apropertyname, elapsedtime : afloat, pseudoelement: apseudoelementname}); parameters the animationevent() constructor also inherits arguments from event(). type a domstring representing the name of the type of the animationevent. it is case-sensitive and can be: 'animationstart', 'animationend', or 'animationiteration'. animationname optional a domstring containing the value of the animation-name css property associated with the transition. it defaults to "". ...
...ere was a negative value for animation-delay, in which case the event will be fired with elapsedtime containing (-1 * delay). it defaults to 0.0. pseudoelement optional is a domstring, starting with "::", containing the name of the pseudo-element the animation runs on. if the animation doesn't run on a pseudo-element but on the element itself, specify an empty string: "". it defaults to "". re
turn value a new animationevent, initialized per any provided options. specifications specification status comment css animationsthe definition of 'animationevent()' in that specification. working draft initial definition. ...
Attr.localName - Web APIs
example the following example shows "id" in an alert dialog. html content <button id="example">click me</button> javascript content const element = document.queryselector("#example"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon. ...
...le"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon. qualified names are typically used in xml as part of the namespace(s) of the particular xml documents. note: in gecko 1.9.2 and earlier, the property re
turns the upper-cased version of the local name for html attributes in html doms (as opposed to xhtml attributes in xml doms). in later versions, in compliance with html5, the property re
turns in the case of the internal dom storage, which is lower case for both html attributes in html doms and xhtml attributes in xml doms. specifications specification status comment dom...
AudioContext.createMediaStreamTrackSource() - Web APIs
the createmediastreamtracksource() method of the audiocontext interface creates and re
turns a mediastreamtrackaudiosourcenode which represents an audio source whose data comes from the specified mediastreamtrack. this differs from createmediastreamsource(), which creates a mediastreamaudiosourcenode whose audio comes from the audio track in a specified mediastream whose id is first, lexicographically (alphabetically). syntax var audioctx = new audiocontext(); var track = audioctx.createmediastreamtracksource(track); parameters track the mediastreamtrack to use as the source of all audio data for the new node. re
turn value a mediastreamtrackaudiosourcenode object which acts as a source for audio data found in the specified audio track. example in this example, getusermedia() i...
...audiosourcenode object which acts as a source for audio data found in the specified audio track. example in this example, getusermedia() is used to request access to the user's microphone. once that access is attained, an audio context is established and a mediastreamtrackaudiosourcenode is created using createmediastreamtracksource(), taking its audio from the first audio track in the stream re
turned by getusermedia(). then a biquadfilternode is created using createbiquadfilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source. the output from the microphone is then routed into the new biquad filter, and the filter's output is in
turn routed to the audio context's destination. navigator.mediadevices.getusermedia ({audio: true, video: false}...
AudioContext.getOutputTimestamp() - Web APIs
the two values are as follows: audiotimestamp.contexttime: the time of the sample frame currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as the context's audiocontext.currenttime. basically, this is the time after the audio context was first created. audiotimestamp.performancetime: an estimation of the moment when the sample frame corresponding to the stored contexttime value was rendered by the audio output device, in the same units and origin as performance.now(). ...
...st created. audiotimestamp.performancetime: an estimation of the moment when the sample frame corresponding to the stored contexttime value was rendered by the audio output device, in the same units and origin as performance.now(). this is the time after the document containing the audio context was first rendered. syntax var timestamp = audiocontext.getoutputtimestamp() parameters none. re
turns an audiotimestamp object, which has the following properties. contexttime: a point in the time coordinate system of the currenttime for the baseaudiocontext; the time after the audio context was first created. performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered examples in the follo...
AudioContext - Web APIs
top"><rect x="151" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">audiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audiocontext() creates and re
turns a new audiocontext object. properties also inherits properties from its parent interface, baseaudiocontext. audiocontext.baselatency read only re
turns the number of seconds of processing latency incurred by the audiocontext passing the audio from the audiodestinationnode to the audio subsystem. audiocontext.outputlatency read only re
turns an estimation of the output latency of the...
...iocontext.createmediastreamdestination() creates a mediastreamaudiodestinationnode associated with a mediastream representing an audio stream which may be stored in a local file or sent to another computer. audiocontext.createmediastreamtracksource() creates a mediastreamtrackaudiosourcenode associated with a mediastream representing an media stream track. audiocontext.getoutputtimestamp() re
turns a new audiotimestamp object containing two audio timestamp values relating to the current audio context. audiocontext.resume() resumes the progression of time in an audio context that has previously been suspended/paused. audiocontext.suspend() suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process. exa...
AudioNode.connect() - Web APIs
tiple inputs by calling connect() repeatedly. this makes fan-out possible. the default value is 0. inputindex optional an index describing which input of the destination you want to connect the current audionode to; the default is 0. the index numbers are defined according to the number of input channels (see audio channels). ...
...are defined according to the number of input channels (see audio channels). it is possible to connect an audionode to another audionode, which in
turn connects back to the first audionode, creating a cycle. this is allowed only if there is at least one delaynode in the cycle. otherwise, a notsupportederror exception is thrown. this parameter is not allowed if the destination is an audioparam. re
turn value if the destination is a node, connect() re
turns a reference to the destination audionode object, allowing you to chain multiple connect() calls. in some browsers, older implementations of this interface re
turn undefined. if the destination is an audioparam, connect() re
turns undefined. exceptions indexsizeerror the value specified as outputindex or inputindex doesn't correspond to an...
AudioProcessingEvent - Web APIs
ent? playbacktime read only double the time when the audio will be played, as defined by the time of audiocontext.currenttime inputbuffer read only audiobuffer the buffer containing the input audio data to be processed. the number of channels is defined as a parameter, numberofinputchannels, of the factory method audiocontext.createscriptprocessor(). ...
...ethod audiocontext.createscriptprocessor(). note the the re
turned audiobuffer is only valid in the scope of the onaudioprocess function. outputbuffer read only audiobuffer the buffer where the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the re
turned audiobuffer is only valid in the scope of the onaudioprocess function. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scr...
AudioScheduledSourceNode.start() - Web APIs
ffset optional a floating-point number indicating the offset, in seconds, into the audio buffer where playback should begin. if 0 is passed then the playback will start from the beginning. duration optional a floating-point number indicating the duration, in seconds, to be played. if no value is passed then the duration will be equal to the length of the audio buffer minus the offset value re
turn value undefined exceptions invalidstatenode the node has already been started. this error occurs even if the node is no longer running because of a prior call to stop(). rangeerror the value specified for when is negative. example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. the times ar...
...error occurs even if the node is no longer running because of a prior call to stop(). rangeerror the value specified for when is negative. example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. the times are calculated by adding the desired number of seconds to the context's current time stamp re
turned by audiocontext.currenttime. context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* schedule the start and stop times for the oscillator */ osc.start(context.currenttime + 2); osc.stop(context.currenttime + 3); specifications specification status comment web audio apithe definition of 'start()' in that specification. ...
AudioWorkletGlobalScope.registerProcessor - Web APIs
ssorctor the constructor of a class derived from audioworkletprocessor. note: a key-value pair { name: constructor } is saved internally in the audioworkletglobalscope once the processor is registered. the name is to be referred to when creating an audioworkletnode based on the registered processor. a new processor by the given name is internally created and associated with the new node. re
turn value undefined exceptions notsupportederror the name is an empty string, or a constructor under the given name is already registered. registering the same name twice is not allowed. typeerror the processorctor is not a callable constructor, or the parameterdescriptors property of the constructor exists and doesn't re
turn an array of audioparamdescriptor-based objects. ...
... doesn't re
turn an array of audioparamdescriptor-based objects. examples in this example we create a custom audioworkletnode that outputs silence. first, we need to define a custom audioworkletprocessor and register it. note that this should be done in a separate file. // test-processor.js class testprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { re
turn true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode — passing it the processor name that we used when calling registerprocessor — and connect it to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const node = new au...
AudioWorkletNode.port - Web APIs
it can be used to communicate between the node and its associated audioworkletprocessor. note: the port at the other end of the channel is available under the port property of the processor. syntax audioworkletnodeinstance.port; value the messageport object that is connecting the audioworkletnode and its associated audioworkletprocessor. examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode. first, we need to define a custom audioworkletprocessor, and register it. ...
...ed to define a custom audioworkletprocessor, and register it. note that that this should be done in a separate file. // ping-pong-processor.js class pingpongprocessor extends audioworkletprocessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { re
turn true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('ping-pong-processor.js') const pingpongnode = new audioworkletnode(audio...
AudioWorkletProcessor() - Web APIs
y additional data that can be used for custom initialization of the underlying audioworkletprocessor. note that there are default values for the first two properties, so even if there are no options object passed to the audioworkletnode constructor, the options object passed by the node to the audioworkletprocessor constructor will exist and at minimum have numberofinputs and numberofoutputs. re
turn value the newly constructed audioworkletprocessor instance. example in this example we pass custom options to the audioworkletnode constructor and observe how a structured clone of them gets passed to our audioworkletprocessor constructor. first, we need to define a custom audioworkletprocessor and register it. note that this should be done in a separate file. // test-processor.js class test...
...nstructor. first, we need to define a custom audioworkletprocessor and register it. note that this should be done in a separate file. // test-processor.js class testprocessor extends audioworkletprocessor { constructor (options) { super() console.log(options.numberofinputs) console.log(options.processoroptions.someusefulvariable) } process (inputs, outputs, parameters) { re
turn true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor and options object. in the options object we pass processoroptions with a map instance under someusefulvariable key. we don't pass numberofinputs and see how it gets its default value. const audiocont...
AudioWorkletProcessor.port - Web APIs
it can be used to communicate between the processor and the audioworkletnode to which it belongs. note: the port at the other end of the channel is available under the port property of the node. syntax audioworkletprocessorinstance.port; value the messageport object that is connecting the audioworkletprocessor and the associated audioworkletnode. examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode. ...
...ed to define a custom audioworkletprocessor, and register it. note that that this should be done in a separate file. // ping-pong-processor.js class pingpongprocessor extends audioworkletprocessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { re
turn true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph. const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('ping-pong-processor.js') const pingpongnode = new audioworkletnode(audio...
AuthenticatorAttestationResponse.getTransports() - Web APIs
gettransports() is a method of the authenticatorattestationresponse interface that re
turns an array containing strings describing the different transports which may be used by the authenticator. such transports may be usb, nfc, ble or internal (applicable when the authenticator is not removable from the device). note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create(). note: this method may only be used in top-level contexts and will not be available in an <iframe> for example. syntaxe arrtransports = authenticatorattestationresponse.gettransports() parameters none. ...
...nticator is not removable from the device). note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create(). note: this method may only be used in top-level contexts and will not be available in an <iframe> for example. syntaxe arrtransports = authenticatorattestationresponse.gettransports() parameters none. re
turn value an array containing the different transports supported by the authenticator or nothing if this information is not available.of the processing of the different extensions by the client. the elements of this array are supposed to be in lexicographical order. their values may be : "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over ...
AuthenticatorAttestationResponse - Web APIs
this response should be sent to the relying party's server to complete the creation of the credential. this interface inherites from authenticatorresponse. note: this interface is restricted to top-level contexts. use from within an <iframe> element will not have any effect. properties authenticatorattestationresponse.clientdatajson secure contextread only client data for the authentication, such as origin and challenge. ...
...client data for the authentication, such as origin and challenge. the clientdatajson property is inherited from the authenticatorresponse. authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a newly-created key pair. methods authenticatorattestationresponse.gettransports()secure context re
turns an array of strings describing which transport methods (e.g. usb, nfc) are believed to be supported with the authenticator. the array may be empty if the information is not available. examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", display...
BaseAudioContext.createWaveShaper() - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. ...
...); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } re
turn curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe definition of 'createwaveshaper()' in that specification. working draft ...
BaseAudioContext.decodeAudioData() - Web APIs
e decoding successfully finishes. the single argument to this callback is an audiobuffer representing the decodeddata (the decoded pcm audio data). usually you'll want to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want. errorcallback an optional error callback, to be invoked if an error occurs when the audio data is being decoded. ...
...when the audio data is being decoded. re
turn value void, or a promise object that fulfills with the decodeddata. example in this section we will first cover the older callback-based system and then the newer promise-based syntax. older callback syntax in this example, the getdata() function uses xhr to load an audio track, setting the responsetype of the request to arraybuffer so that it re
turns an array buffer as its response that we then store in the audiodata variable . we then pass this buffer into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop. the buttons in the example simply ru...
BatteryManager.dischargingTime - Web APIs
this value is infinity if the battery is currently charging rather than discharging, or if the system is unable to report the remaining discharging time. ...
...this value is infinity if the battery is currently charging rather than discharging, or if the system is unable to report the remaining discharging time. ...
Beacon API - Web APIs
sues. global context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server in the global browsing context. the method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method re
turns "true" and re
turns "false" otherwise. worker context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server from the worker global scope. the method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the req...
...erwise. worker context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server from the worker global scope. the method takes two arguments, the url and the data to send in the request. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method re
turns "true" and otherwise re
turns "false". ...
BeforeInstallPromptEvent - Web APIs
as,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeinstallpromptevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor beforeinstallpromptevent() creates a new beforeinstallpromptevent. properties inherits properties from its parent, event. ...
...beforeinstallpromptevent.platforms read only re
turns an array of domstring items containing the platforms on which the event was dispatched. this is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between a web version or an android version. beforeinstallpromptevent.userchoice read only re
turns a promise that resolves to a domstring containing either "accepted" or "dismissed". methods beforeinstallpromptevent.prompt() allows a developer to show the install prompt at a time of their own choosing. this method re
turns a promise. example window.addeventlistener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.pl...
Blob() - Web APIs
the content of the blob consists of the concatenation of the values given in the parameter array. syntax var newblob = new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob. usvstring objects are encoded as utf-8. options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret newline characters (\n) within the contents, if the data is text. ...
...he mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret newline characters (\n) within the contents, if the data is text. the default value, transparent, copies newline characters into the blob without changing them. to convert newlines to the host system's native convention, specify the value native. re
turn value a new blob object containing the specified data. example var afileparts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single domstring var omyblob = new blob(afileparts, {type : 'text/html'}); // the blob specification specification status comment file apithe definition of 'blob()' in that specification. working draft initial defi...
Blob.arrayBuffer() - Web APIs
the arraybuffer() method in the blob interface re
turns a promise that resolves with the contents of the blob as binary data contained in an arraybuffer. syntax var bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none. re
turns a promise that resolves with an arraybuffer that contains the blob's data in binary form. exceptions while this method doesn't throw exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an exception. any exceptions thrown while getting the data will be converted into rejections. ...
...ffer that contains the blob's data in binary form. exceptions while this method doesn't throw exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an exception. any exceptions thrown while getting the data will be converted into rejections. usage notes while similar to the filereader.readasarraybuffer() method, arraybuffer() re
turns a promise rather than being an event-based api, as is the case with the filereader interface's method. specifications specification status comment file apithe definition of 'blob.arraybuffer()' in that specification. working draft ...
Blob.stream() - Web APIs
the blob interface's stream() method re
turns a readablestream which upon reading re
turns the data contained within the blob. syntax var stream = blob.stream(); parameters none. re
turns a readablestream which, upon reading, re
turns the contents of the blob. usage notes with stream() and the re
turned readablestream, you gain several interesting capabilities: call getreader() on the re
turned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method. call the re
turned stream's pipeto() method to pipe the blob's data to a writable stream. call the re
turned stream's tee() method to tee the readable stream. ...
...ablestream, you gain several interesting capabilities: call getreader() on the re
turned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method. call the re
turned stream's pipeto() method to pipe the blob's data to a writable stream. call the re
turned stream's tee() method to tee the readable stream. this re
turns an array containing two new readablestream objects, each of which re
turns the contents of the blob. call the re
turned stream's pipethrough() method to pipe the stream through a transformstream or any other readable and writable pair. specifications specification status comment file apithe definition of 'blob.stream()' in that specification. working draft ...
readValue() - Web APIs
specifications specification status comment web bluetooththe definition of 'readvalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
... specifications specification status comment web bluetooththe definition of 'readvalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
writeValue() - Web APIs
specifications specification status comment web bluetooththe definition of 'writevalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
... specifications specification status comment web bluetooththe definition of 'writevalue()' in that specification. draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
BluetoothRemoteGATTDescriptor - Web APIs
r information about a characteristic’s value. interface interface bluetoothremotegattdescriptor { readonly attribute bluetoothgattcharacteristic characteristic; readonly attribute uuid uuid; readonly attribute arraybuffer? value; promise<arraybuffer> readvalue(); promise<void> writevalue(buffersource value); }; properties bluetoothremotegattdescriptor.characteristicread only re
turns the bluetoothremotegattcharacteristic this descriptor belongs to. bluetoothremotegattdescriptor.uuidread only re
turns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor. bluetoothremotegattdescriptor.valueread only re
turns the currently cached descriptor value. this value gets updated when the ...
...criptor.uuidread only re
turns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor. bluetoothremotegattdescriptor.valueread only re
turns the currently cached descriptor value. this value gets updated when the value of the descriptor is read. methods bluetoothremotegattdescriptor.readvalue() re
turns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported. otherwise it throws an error. bluetoothremotegattdescriptor.writevalue() sets the value property to the bytes contained in an arraybuffer and re
turns a promise. specifications specification status comment web bluetooththe definition of 'bluetoothremo...
BluetoothRemoteGATTServer.getPrimaryService() - Web APIs
parameters bluetoothserviceuuid a bluetooth service universally unique identifier for a specified device. ...
... parameters bluetoothserviceuuid a bluetooth service universally unique identifier for a specified device. ...
BluetoothRemoteGATTServer - Web APIs
it can be false while the user agent is physically connected. bluetoothremotegattserver.deviceread only a reference to the bluetoothdevice running the server. methods bluetoothremotegattserver.connect() causes the script execution environment to connect to this.device. bluetoothremotegattserver.disconnect() caus...
...ysically connected. bluetoothremotegattserver.deviceread only a reference to the bluetoothdevice running the server. methods bluetoothremotegattserver.connect() causes the script execution environment to connect to this.device. bluetoothremotegattserver.disconnect() causes the script execution environment to disconnect from this.device. bluetoothremotegattserver.getprimaryservice() re
turns a promise to the primary bluetoothgattservice offered by the bluetooth device for a specified bluetoothserviceuuid. bluetoothremotegattserver.getprimaryservices() re
turns a promise to a list of primary bluetoothgattservice objects offered by the bluetooth device for a specified bluetoothserviceuuid. specifications specification status comment web bluetooththe definit...
getCharacteristics() - Web APIs
parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. ...
... parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic. ...
Body.blob() - Web APIs
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. ...
... example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. ...
Body.bodyUsed - Web APIs
e a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this re
turns false before and true afterwards, as at that point the body has been read. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = respo...
...he body has been read. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = response.blob(); console.log(response.bodyused); re
turn res; }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'bodyused' in that specification. living standard ...
Body.formData() - Web APIs
example tbd. ...
...ect. note: this is mainly relevant to service workers. if a user submits a form and a service worker intercepts the request, you could for example call formdata() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally). syntax response.formdata() .then(function(formdata) { // do something with your formdata }); parameters none. re
turn value a promise that resolves with a formdata object. example tbd. specifications specification status comment fetchthe definition of 'formdata()' in that specification. living standard ...
Body.json() - Web APIs
this object could be anything that can be represented by json — an object, an array, a string, a number... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. ...
...this object could be anything that can be represented by json — an object, an array, a string, a number... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. ...
Body.text() - Web APIs
the text() method of the body mixin takes a response stream and reads it to completion. it re
turns a promise that resolves with a usvstring object (text). the response is always decoded using utf-8. syntax response.text().then(function (text) { // do something with the text response }); parameters none. re
turn value a promise that resolves with a usvstring. example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a new request using the request() construc...
... living standard ...
BudgetService.getBudget() - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
BudgetService.getCost() - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
BudgetService.reserve() - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
BudgetState - Web APIs
methods none. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... methods none. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
exceptions none. examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... ...
... exceptions none. examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... ...
ByteLengthQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... ...
... examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... ...
CSS numeric factory functions - Web APIs
the css numeric factory functions, such as css.em() and css.
turn() are methods that re
turn cssunitvalues with the value being the numeric argument and the unit being the name of the method used. these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor. ...
...ength> css.em(number); css.ex(number); css.ch(number); css.ic(number); css.rem(number); css.lh(number); css.rlh(number); css.vw(number); css.vh(number); css.vi(number); css.vb(number); css.vmin(number); css.vmax(number); css.cm(number); css.mm(number); css.q(number); css.in(number); css.pt(number); css.pc(number); css.px(number); // <angle> css.deg(number); css.grad(number); css.rad(number); css.
turn(number); // <time> css.s(number); css.ms(number); // <frequency> css.hz(number); css.khz(number); // <resolution> css.dpi(number); css.dpcm(number); css.dppx(number); // <flex> css.fr(number); examples we use the css.vmax() numeric factory function to create a cssunitvalue: let height = css.vmax(50); console.log( height ); // cssunitvalue {value: 50, unit: "vmax"} console.log( heigh...
CSSKeyframesRule - Web APIs
ponds to the contents of a whole @keyframes at-rule. it implements the cssrule interface with a type value of 7 (cssrule.keyframes_rule). properties as a cssrule, csskeyframesrule also implements the properties of these interfaces. it has two properties : csskeyframesrule.name represents the name of the animation, used by the animation-name property. csskeyframesrule.cssrules read only re
turns a cssrulelist of the css rules in the media rule. methods as a cssrule, csskeyframesrule also implements the methods of that interface. it has three specific methods: csskeyframesrule.appendrule() inserts a new keyframe rule into the current csskeyframesrule. the parameter is a domstring containing a keyframe in the same format as an entry of a @keyframes at-rule. if it contains more than...
...yframe in the same format as an entry of a @keyframes at-rule. if it contains more than one keyframe rule, a domexception with a syntax_err is thrown. csskeyframesrule.deleterule() deletes a keyframe rule from the current csskeyframesrule. the parameter is the index of the keyframe to be deleted, expressed as a domstring resolving as a number between 0% and 100%. csskeyframesrule.findrule() re
turns a keyframe rule corresponding to the given key. the key is a domstring containing an index of the keyframe to be re
turned, resolving to a percentage between 0% and 100%. if no such keyframe exists, findrule re
turns null. specification specification status comment css animationsthe definition of 'csskeyframesrule' in that specification. working draft initial d...
CSSMathValue.operator - Web APIs
syntax var astring = cssmathvalue.operator; value a string. ...
... specifications specification status comment css typed om level 1the definition of 'cssmathvalue.operator' in that specification. working draft initial definition. ...
CSSNumericValue.equals() - Web APIs
exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. ...
... exceptions none. examples as stated earlier, all passed values must be of the same type and value and must be in the same order. some of the following examples illustrate what happens when they are not. ...
CSSNumericValue.max() - Web APIs
exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
... exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
CSSNumericValue.min() - Web APIs
exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
... exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
CSSPrimitiveValue.getFloatValue() - Web APIs
alue() method of the cssprimitivevalue interface is used to get a float value in a specified unit. if this css value doesn't contain a float value or can't be converted into the specified unit, a domexception is raised. syntax var floatvalue = cssprimitivevalue.getfloatvalue(unit); parameters unittype an unsigned short representing the code for the unit type, in which the value should be re
turned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> in ex units. cs...
... the value is a simple <number>. css_pc the value is a <length> in picas. css_percentage the value is a <percentage>. css_pt the value is a <length> in points. css_px the value is a <length> in pixels. css_rad the value is an <angle> in radians. css_s the value is a <time> in seconds. re
turn value a float value in the specified unit. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a float value or if the float value can't be converted into the specified unit. example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("margin-top"); console.log(cssvalue.
CSSPrimitiveValue.setFloatValue() - Web APIs
d of the cssprimitivevalue interface is used to set a float value. if the property attached to this value can't accept the specified unit or the float value, the value will be unchanged and a domexception will be raised. syntax cssprimitivevalue.setfloatvalue(unittype, floatvalue); parameters unittype an unsigned short representing the code for the unit type, in which the value should be re
turned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> in ex units. cs...
... the value is a <length> in picas. css_percentage the value is a <percentage>. css_pt the value is a <length> in points. css_px the value is a <length> in pixels. css_rad the value is an <angle> in radians. css_s the value is a <time> in seconds. floatvalue a float representing the new float value. re
turn value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a float value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object m...
CSSStyleDeclaration.item() - Web APIs
the cssstyledeclaration.item() method interface re
turns a css property name from a cssstyledeclaration by index. this method doesn't throw exceptions as long as you provide arguments; the empty string is re
turned if the index is out of range and a typeerror is thrown if no argument is provided. syntax var propertyname = style.item(index); parameters index is the index of the node to be fetched. the index is zero-based. re
turn value propertyname is a domstring that is the name of the css property at the specified index. ...
...e node to be fetched. the index is zero-based. re
turn value propertyname is a domstring that is the name of the css property at the specified index. javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - re
turns the second style listed specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.item()' in that specification. working draft document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration' in that specification. obsolete ...
CSSStyleDeclaration.setProperty() - Web APIs
not specified, treated as the empty string. note: value must not contain "!important" -- that should be set using the priority parameter. priority optional is a domstring allowing the "important" css priority to be set. if not specified, treated as the empty string. the following values are accepted: string value "important" keyword undefined string empty value "" re
turn value undefined exceptions domexception (nomodificationallowederror): if the property or declaration block is read only. if priority can be omitted, javascript has a special simpler syntax for setting a css property on a style declaration object: style.csspropertyname = 'value'; examples in this example we have three buttons, which can be pressed to dynamically alter our box paragrap...
... 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; } javascript const borderbtn = document.queryselector('.border'); const bgcolorbtn = document.queryselector('.bgcolor'); const colorbtn = document.queryselector('.color'); const box = document.queryselector('.box'); function random(min,max) { const num = math.floor(math.random()*(max-min)) + min; re
turn num; } function randomcolor() { re
turn 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.stylesheets[1]; let boxpararule; for(let i = 0; i < stylesheet.cssrules.length; i++) { if(stylesheet.cssrules[i].selectortext === '.box p') { boxpararule = stylesheet.cssrules[i]; } } function setrandomborder() { const newborder = random...
CSSUnparsedValue.keys() - Web APIs
specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
CSSUnparsedValue.values() - Web APIs
specifications specification status comment css typed om level 1the definition of 'values()' in that specification. ...
... specifications specification status comment css typed om level 1the definition of 'values()' in that specification. ...
CSSUnparsedValue - Web APIs
t model api represents property values that reference custom properties. it consists of a list of string fragments and variable references. custom properties are represented by cssunparsedvalue and var() references are represented using cssvariablereferencevalue. constructor cssunparsedvalue.cssunparsedvalue() creates a new cssunparsedvalue object. properties cssunparsedvalue.length re
turns the number of items in the cssunparsedvalue object. methods cssunparsedvalue.entries() re
turns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each ele...
... cssunparsedvalue.entries() re
turns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object. cssunparsedvalue.keys() re
turns a new array iterator object that contains the keys for each index in the cssunparsedvalue object. cssunparsedvalue.values() re
turns a new array iterator object that contains the values for each index in the cssunparsedvalue object. specifications specification status comment css typed om level 1the definition of 'cssunparsedvalue' in that specification. working dr...
Using dynamic styling information - Web APIs
e style property is given on the dom css properties list page. to modify styles to a document using css syntax, one can insert rules or insert <style> tags whose innerhtml property is set to the desired css. modify an element's style the element style property (see also the section "dom style object" below) can also be used to get and set the styles on an element. however, this property only re
turns style attributes that have been set in-line (e.g, <td style="background-color: lightblue"> re
turns the string "background-color:lightblue", or directly for that element using element.style.propertyname, even though there may be other styles on the element from a stylesheet). also, when you set this property on an element, you override any styles that have been set elsewhere for that element's p...
...> </head> <body> <!-- passes a reference to the element's object as parameter 'this'. --> <p id="p1" onclick="alterstyle(this);"> click here to change background color. </p> <!-- passes the 'p1' id of another element's style to modify. --> <button onclick="resetstyle('p1');">reset background color</button> </body> </html> the getcomputedstyle() method on the document.defaultview object re
turns all styles that have actually been computed for an element. see example 6: getcomputedstyle in the examples chapter for more information on how to use this method. dom style object the style object represents an individual style statement. unlike the individual rules available from the document.stylesheets collection, the style object is accessed from the document or from the elements to which...
Cache.delete() - Web APIs
if no cache entry is found, it resolves to false. syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); parameters request the request you are looking to delete. this can be a request object or a url. options optional an object whose properties control how matching is done in the delete operation. ...
...o false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of whether the response object has a vary header. it defaults to false. cachename: a domstring that represents a specific cache to search within. note that this option is ignored by cache.delete(). re
turn value a promise that resolves to true if the cache entry is deleted, or false otherwise. examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someuiupdatefunction(); }); }) specifications specification status comment service workersthe definition of 'cache: delete' in that specification. working draft...
Cache.matchAll() - Web APIs
syntax cache.matchall(request, {options}).then(function(response) { // do something with the response array }); parameters request optional the request for which you are attempting to find responses in the cache. this can be a request object or a url. if this argument is omitted, you will get a copy of all responses in this cache. options optional an options object allowing you to set specific control options for the matching performed. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. ...
... set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of the response object having a vary header or not. it defaults to false. re
turn value a promise that resolves to an array of all matching responses in the cache object. note: cache.match() is basically identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). examples caches.open('v1').then(function(cache) { cache.matchall('/images/').then(functio...
CanvasRenderingContext2D.createLinearGradient() - Web APIs
to be applied to a shape, the gradient must first be assigned to the fillstyle or strokestyle properties. note: gradient coordinates are global, i.e., relative to the current coordinate space. when applied to a shape, the coordinates are not relative to the shape's coordinates. ...
...nates. syntax canvasgradient ctx.createlineargradient(x0, y0, x1, y1); the createlineargradient() method is specified by four parameters defining the start and end points of the gradient line. parameters x0 the x-axis coordinate of the start point. y0 the y-axis coordinate of the start point. x1 the x-axis coordinate of the end point. y1 the y-axis coordinate of the end point. re
turn value canvasgradient a linear canvasgradient initialized with the specified line. examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient() method. three color stops between the gradient's start and end points are then created. finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangl...
CanvasRenderingContext2D.createPattern() - Web APIs
this method doesn't draw anything to the canvas directly. the pattern it creates must be assigned to the canvasrenderingcontext2d.fillstyle or canvasrenderingcontext2d.strokestyle properties, after which it is applied to any subsequent drawing. syntax canvaspattern ctx.createpattern(image, repetition); parameters image a canvasimagesource to be used as the pattern's image. ...
...lcanvaselement (<canvas>) imagebitmap offscreencanvas repetition a domstring indicating how to repeat the pattern's image. possible values are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) if repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used. re
turn value canvaspattern an opaque object describing a pattern. examples creating a pattern from an image this example uses the createpattern() method to create a canvaspattern with a repeating source image. once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. the original image looks like this: html <canvas id="canvas" width="300" height="3...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
to be applied to a shape, the gradient must first be assigned to the fillstyle or strokestyle properties. note: gradient coordinates are global, i.e., relative to the current coordinate space. when applied to a shape, the coordinates are not relative to the shape's coordinates. ...
...ient's start circle, and three defining the end circle. parameters x0 the x-axis coordinate of the start circle. y0 the y-axis coordinate of the start circle. r0 the radius of the start circle. must be non-negative and finite. x1 the x-axis coordinate of the end circle. y1 the y-axis coordinate of the end circle. r1 the radius of the end circle. must be non-negative and finite. re
turn value canvasgradient a radial canvasgradient initialized with the two specified circles. examples filling a rectangle with a radial gradient this example initializes a radial gradient using the createradialgradient() method. three color stops between the gradient's two circles are then created. finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle.
Manipulating video using canvas - Web APIs
eo and computing the visual effect. the timer callback the timer callback is called initially when the video starts playing (when the "play" event occurs), then takes responsibility for establishing itself to be called periodically in order to launch the keying effect for each frame. processor.timercallback = function timercallback() { if (this.video.paused || this.video.ended) { re
turn; } this.computeframe(); let self = this; settimeout(function() { self.timercallback(); }, 0); }, the first thing the callback does is check to see if the video is even playing; if it's not, the callback re
turns immediately without doing anything. then it calls the computeframe() method, which performs the chroma-keying effect on the current video frame. the las...
... note that you can simply pass the video element into the context's drawimage...
ChildNode.replaceWith() - Web APIs
ymbol.unscopables for more information. ...
...efined polyfill you can polyfill the replacewith() method in internet explorer 10+ and higher with the following code: function replacewithpolyfill() { 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length, currentnode; if (!parent) re
turn; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and re
turns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){ currentnode = this.ownerdocument.createtextnode(currentnode); } else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode =...
Client.postMessage() - Web APIs
r. syntax client.postmessage(message[, transfer]); client.postmessage(message[, { transfer }]); parameters message the message to send to the client. this can be any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. re
turn 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) re
turn; // get the client. const client = await clients.get(event.clientid); // exit early if we don't get the cli...
...rom 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) re
turn; // 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) re
turn; // send a message to the client. client.postmessage({ msg: "hey i just got a fetch from you!", url: event.request.url }); }()); }); receiving that message: navigator.serviceworker.addeventlistener('message', event => { console.log(event.data.msg, event.data.url); }); specifications specification status comment service workersthe de...
CloseEvent - Web APIs
the following values are permitted status codes. ...
... 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. available for registration at the iana via first-come, first-serve. 4000–4999 available for use by applications. closeevent.reason read only re
turns a domstring indicating the reason the server closed the connection. this is specific to the particular server and sub-protocol. closeevent.wasclean read only re
turns a boolean that indicates whether or not the connection was cleanly closed. methods this interface also inherits methods from its parent, event. closeevent.initcloseevent() initializes the value of a closeevent created.
console.count() - Web APIs
called. note: this feature is available in web workers. syntax console.count([label]); parameters label optional a string. if supplied, count() outputs the number of times it has been called with that label. if omitted, count() behaves as though it was called with the "default" label. examples for example, given code like this: let user = ""; function greet() { console.count(); re
turn "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" the label is displayed as default because no explicit label was supplied. if we pass the user variable as the label argument to the first invocation of count(), and the string "alice" to the second: let us...
... greet(); greet(); console.count(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" the label is displayed as default because no explicit label was supplied. if we pass the user variable as the label argument to the first invocation of count(), and the string "alice" to the second: let user = ""; function greet() { console.count(user); re
turn "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count("alice"); we will see output like this: "bob: 1" "alice: 1" "alice: 2" "alice: 3" we're now maintaining separate counts based only on the value of label. specifications specification status comment console apithe definition of 'console.count()' in that specification. livi...
Console.countReset() - Web APIs
resets counter used with console.count(). note: this feature is available in web workers. syntax console.countreset([label]); parameters label optional a string. if supplied, countreset() resets the count for that label to 0. if omitted, countreset() resets the default counter to 0. examples for example, given code like this: let user = ""; function greet() { console.count(); re
turn "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console.countreset(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the call to console.counterreset() resets the value of the default counter to zero. if we pass the user variable as the label argument with the string "bob" to ...
... look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the call to console.counterreset() resets the value of the default counter to zero. if we pass the user variable as the label argument with the string "bob" to the first invocation of count(), and the string "alice" to the second: let user = ""; function greet() { console.count(user); re
turn "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.countreset("bob"); console.count("alice"); we will see output like this: "bob: 1" "alice: 1" "alice: 2" "bob: 0" "alice: 3" resetting the value of the counter "bob" only changes the value of that counter. the value of "alice" is unchanged. specifications specification status comment ...
ContentIndex.add() - Web APIs
the category of content. can be: '' an empty string, this is the default. homepage article video audio icons: optional 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. re
turn value re
turns 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 asyn...
... // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid...
ContentIndexEvent() - Web APIs
tentindexevent(type, contentindexeventinit); parameters type a domstring indicating the event which occurred. for contentindexevent, this is always delete. eventinitdict optional an options object containing any initialization data you want to populate the contentindexevent object with. the options are: id: the id of the indexed content you want the contentindexevent to remove. ...
...e options are: id: the id of the indexed content you want the contentindexevent to remove. re
turn value a contentindexevent object configured using the given inputs. examples this examples constructs a new contentindexevent with the relevant id. var removedata = { id : 'unique-content-id' } var cievent = new contentindexevent('contentdelete', removedata); cievent.id; // should re
turn 'unique-content-id' specifications specification status comment unknownthe definition of 'contentindexevent' in that specification. unknown initial definition. ...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
exceptions none. examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... ...
... exceptions none. examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... ...
CountQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... ...
... examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... ...
Credential - Web APIs
valid values are password, federated and public-key. ...
...valid values are password, federated and public-key. ...
CredentialsContainer.create() - Web APIs
this method is restricted to top-level contexts. calls to it within an <iframe> element will resolve without effect. syntax var promise = credentialscontainer.create([options]) parameters options an object of type credentialcreationoptions that contains options for the requested new credentials object. it must include one of the options "password", "federated", or "publickey". the options are: password: optional either an htmlformelement, or a passwordcredentialdata object. ...
...rated credentials. the available options are: id: (required) usvstring inherited from credentialdata. name: optional usvstring tbd iconurl: optional usvstring tbd provider: (required) usvstring tbd protocol: optional usvstring tbd publickey: optional an publickeycredentialcreationoptions object that describes the options for creating a webauthn credential. re
turns a promise that resolves with a credential instance, such as passwordcredential, federatedcredential, or publickeycredential. specifications specification status comment credential management level 1the definition of 'get()' in that specification. working draft initial definition. web authentication: an api for accessing public key credentials level 1 ...
CredentialsContainer.preventSilentAccess() - Web APIs
for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. mediation varies by origin, and is an added check point of browser stored credentials, informing a user of an account login status. ...
...ser of an account login status. this method is typically called after a user signs out of a website, ensuring this user's login information is not automatically passed on the next site visit. earlier versions of the spec called this method requireusermediation(). see browser compatibility for support details. syntax var promise = credentialscontainer.preventsilentaccess() parameters none. re
turns an empty promise. specifications specification status comment credential management level 1the definition of 'preventsilentaccess()' in that specification. working draft initial definition. ...
CustomElementRegistry.define() - Web APIs
ions); parameters name name for the new custom element. note that custom element names must contain a hyphen. constructor constructor for the new custom element. options optional object that controls how the element is defined. one option is currently supported: extends: string specifying the name of a built-in element to extend. used to create a customized built-in element. re
turn value void. exceptions exception description notsupportederror the customelementregistry already contains an entry with the same name or the same constructor (or is otherwise already defined), or extends is specified and it is a valid custom element name, or extends is specified but the element it is trying to extend is an unknown element. syntaxerror th...
...en from our word-count-web-component example (see it live also). ...
CustomElementRegistry.get() - Web APIs
the get() method of the customelementregistry interface re
turns the constructor for a previously-defined custom element. syntax constructor = customelements.get(name); parameters name the name of the custom element whose constructor you want to re
turn a reference to. re
turn value the constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
...e is no custom element definition with that name. examples customelements.define('my-paragraph', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } }) // re
turn a reference to the my-paragraph constructor let ctor = customelements.get('my-paragraph'); specifications specification status comment html living standardthe definition of 'customelements.get()' in that specification. living standard initial definition. ...
CustomElementRegistry - Web APIs
the customelementregistry interface provides methods for registering custom elements and querying registered elements. to get an instance of it, use the window.customelements property. methods customelementregistry.define() defines a new custom element. customelementregistry.get() re
turns the constuctor for the named custom element, or undefined if the custom element is not defined. customelementregistry.upgrade() upgrades a custom element directly, even before it is connected to its shadow root. customelementregistry.whendefined() re
turns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the re
turned promise is immediately fulfilled. examples the following code is taken from our word-count-web-...
...() method to define the custom element after creating its class. ...
DOMImplementation.createDocument() - Web APIs
syntax var doc = document.implementation.createdocument(namespaceuri, qualifiednamestr, documenttype); parameters namespaceuri is a domstring containing the namespace uri of the document to be created, or null if the document doesn't belong to one. qualifiednamestr is a domstring containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documenttype optional is the documenttype of the document to be created. it defaults to null. ...
...); var body = document.createelementns('http://www.w3.org/1999/xhtml', 'body'); body.setattribute('id', 'abc'); doc.documentelement.appendchild(body); alert(doc.getelementbyid('abc')); // [object htmlbodyelement] specifications specification status comment domthe definition of 'domimplementation.createdocument' in that specification. living standard modified the re
turn type of createdocument() from document to xmldocument. the third argument of createdocument(), doctype, is now optional and default to null. document object model (dom) level 3 core specificationthe definition of 'domimplementation.createdocument' in that specification. obsolete no change from document object model (dom) level 2 core specification document object model...
DOMImplementation - Web APIs
the domimplementation interface represents an object providing methods which are not dependent on any particular document. such an object is re
turned by the document.implementation property. property this interface has no specific property and doesn't inherit any. methods no inherited method. domimplementation.createdocument() creates and re
turns an xmldocument. domimplementation.createdocumenttype() creates and re
turns a documenttype. domimplementation.createhtmldocument() creates and re
turns an html document. domimplementation.hasfeature() re
turns a boolean indicating if a given feature is supported or not. this function is unreliable and kept for compatibility purpose alone: except for svg-related queries, it always re
turns true. old browsers are very inconsistent in their be...
... document object model (dom) level 3 core specificationthe definition of 'domimplementation' in that specification. obsolete added the getfeature() method (never implemented by any user agent). ...
DOMImplementationList - Web APIs
specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'domimplementationlist' in that specification. obsolete initial definition. ...
... specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'domimplementationlist' in that specification. obsolete initial definition. ...
DOMMatrixReadOnly.flipX() - Web APIs
the original matrix is not modified. examples this svg contains two paths in the shape of a triangle, both drawn to the same position. ...
... the original matrix is not modified. examples this svg contains two paths in the shape of a triangle, both drawn to the same position. ...
DOMPointReadOnly() - Web APIs
syntax point = new dompointreadonly(x, y, z, w); parameters x optional the value of the horizontal coordinate, x, as a floating point number. the default value is 0. y optional the value of the vertical coordinate, y, as a floating point number. the default value is 0. z optional the value of the depth coordinate, z, as a floating point number. the default value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. ...
...r. the default value is 0. z optional the value of the depth coordinate, z, as a floating point number. the default value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. in addition to any finite floating-point value, you may use special values such as ±infinity and nan. re
turn value a new dompointreadonly object representing the specified location in space. examples the following code demonstrates creating both 2d and 3d points. var point2d = new dompointreadonly(50, 25); var point3d = new dompointreadonly(50, 0, 10); var perspectivepoint3d = new dompointreadonly(50, 50, 25, 0.5); specifications specification status comment geometry interf...
DOMTokenList.contains() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent. ...
... examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent. ...
DOMTokenList.item() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent. ...
... examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent. ...
DOMTokenList.replace() - Web APIs
the replace() method of the domtokenlist interface replaces an existing token with a new token. if the first token doesn't exist, replace() re
turns false immediately, without adding the new token to the token list. syntax tokenlist.replace(oldtoken, newtoken); parameters oldtoken a domstring representing the token you want to replace. newtoken a domstring representing the token you want to replace oldtoken with. re
turn value a boolean value, which is true if oldtoken was successfully replaced, or false if not. note: in older browsers, replace() re
turns void. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'s node.textconte...
...lly'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class. the following code will only work with ie10-11. to use with earlier versions of ie, refer to the polyfill at element.classlist#polyfill domtokenlist.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); re
turn true; } re
turn false; } specifications specification status comment domthe definition of 'replace()' in that specification. living standard initial definition ...
DataTransfer.mozCursor - Web APIs
example this example shows the use of the mozcursor property. ...
...uring tab drags. the possible values are: auto uses the default system behavior. default uses the default gecko behavior, which is to set the cursor to an arrow during the drag operation. note: if any value other than default is set, auto is assumed. note: this property is currently only implemented on windows. note: this property is gecko-specific. syntax datatransfer.mozcursor; re
turn value a domstring representing one of the values listed above. example this example shows the use of the mozcursor property. function drop_handler(event) { var dragdata = event.datatransfer; console.log("mozcursor = " + dragdata.mozcursor); } specifications this property is not defined in any web standard. ...
DataTransfer.types - Web APIs
each format is string. if the drag operation included no data, this list will be empty. if any files are included in the drag operation, then one of the types will be the string files. ...
...ray of the drag data formats (as strings) that were set in the dragstart event. the order of the formats is the same order as the data included in the drag operation. the formats are unicode strings giving the type or format of the data, generally given by a mime type. some values that are not mime types are special-cased for legacy reasons (for example "text"). syntax datatransfer.types; re
turn value an array of the data formats used in the drag operation. each format is string. if the drag operation included no data, this list will be empty. if any files are included in the drag operation, then one of the types will be the string files. example this example shows the use of the types and items properties. <!doctype html> <html lang=en> <title>examples of datatransfer.{types,items}...
DataTransfer - Web APIs
the datatransfer object is used to hold the data that is being dragged during a drag and drop operation. it may hold one or more data items, each of one or more data types. for more information about drag and drop, see html drag and drop api. this object is available from the datatransfer property of all drag events. constructor datatransfer() creates and re
turns a new datatransfer object. properties standard properties datatransfer.dropeffect gets the type of drag-and-drop operation currently selected or sets the operation to a new type. the value must be none, copy, link or move. datatransfer.effectallowed provides all of the types of operations that are possible. must be one of none, copy, copylink, copymove, link, linkmove, move, all or uninitialized. datatransfer.files c...
...nt in which case an existing item is modified, or equal to mozitemcount in which case a new item is added, and the mozitemcount is incremented by one. removed in firefox 71. datatransfer.moztypesat() holds a list of the format types of the data that is stored for an item at the specified index. if the index is not in the range from 0 to the number of items minus one, an empty string list is re
turned. removed in firefox 71. examples every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. specifications specification status comment html living standardthe definition of 'datatransfer' in that specification. living standard mozcursor,...
DataTransferItemList.add() - Web APIs
the datatransferitemlist.add() method creates a new datatransferitem using the specified data and adds it to the drag data list. the item may be a file or a string of a given type. if the item is successfully added to the list, the newly-created datatransferitem object is re
turned. syntax datatransferitem = datatransferitemlist.add(data, type); datatransferitem = datatransferitemlist.add(file); parameters data a string representing the drag item's data. type a string of the drag item's type. some example types are text/html and text/plain. file a file object. no type needs to be given in this case. re
turn value a datatransferitem containing the specified data. if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is...
...meters data a string representing the drag item's data. type a string of the drag item's type. some example types are text/html and text/plain. file a file object. no type needs to be given in this case. re
turn value a datatransferitem containing the specified data. if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is re
turned. exceptions notsupportederror a string data parameter was provided, and the list already contains an item whose kind is "plain unicode string" and whose type is equal to the specified type parameter. example this example shows the use of the add() method. html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select th...
DedicatedWorkerGlobalScope - Web APIs
nterface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.name read only the name that the worker was (optionally) given when it was created using the worker() constructor. this is mainly useful for debugging purposes. properties inherited from workerglobalscope workerglobalscope.self re
turns an object reference to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only re
turns the console associated with the worker. workerglobalscope.location read only re
turns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navig...
...ce to the dedicatedworkerglobalscope object itself. workerglobalscope.console read only re
turns the console associated with the worker. workerglobalscope.location read only re
turns the workerlocation associated with the worker. workerlocation is a specific location object, mostly a subset of the location for browsing scopes, but adapted to workers. workerglobalscope.navigator read only re
turns the workernavigator associated with the worker. workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. workerglobalscope.performance read only re
turns the performance object associated with the worker, which is a regular performance object, but with a subset of its properties and methods available. event handlers this...
DirectoryReaderSync - Web APIs
h(entry.tourl()); // if this is a directory, traverse. if (entry.isdirectory) { getallentries(entry.createreader()); } } } // forward the error to main app. function onerror(e) { postmessage('error: ' + e.tostring()); } self.onmessage = function(e) { var data = e.data; // ignore everything else except our 'list' command. if (!data.cmd || data.cmd != 'list') { re
turn; } try { var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); getallentries(fs.root.createreader()); self.postmessage({entries: paths}); } catch (e) { onerror(e); } }; method overview entrysync readentries () raises (fileexception); method readentries() re
turns a lost of entries from a specific directory. call this method until an empty arr...
... try { var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); getallentries(fs.root.createreader()); self.postmessage({entries: paths}); } catch (e) { onerror(e); } }; method overview entrysync readentries () raises (fileexception); method readentries() re
turns a lost of entries from a specific directory. call this method until an empty array is re
turned. entrysync readentries ( ) raises (fileexception); re
turns parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. invalid_state_err the directory has been modified since the first call to readentries was processed. security_err the brows...
DisplayMediaStreamConstraints.video - Web APIs
the displaymediastreamconstraints dictionary's video property is used to configure the video track in the stream re
turned by getdisplaymedia(). this value may simply be a boolean, where true specifies that a default selection of input source be made (typically the entire display area of the device in use, spanning every screen in a multiple screen configuration). since a video track must always be included, a value of false results in a typeerror exception being thrown. more precise control over the format of the re
turned video track may be exercised by instead providing a mediatrackconstraints object, which is used to process the video data after obtaining it from the device but prior to adding it to the stream. syntax displaymediastreamconstraints.video = allowvideoflag; displaymediastre...
... adding it to the stream. syntax displaymediastreamconstraints.video = allowvideoflag; displaymediastreamconstraints.video = mediatrackconstraints; displaymediastreamconstraints = { video: allowvideoflag | mediatrackconstraints; } value the value may be either a boolean or a mediatrackconstraints object. if a boolean is specified, a value of true (the default) indicates that the stream re
turned by getdisplaymedia() should be in whatever format the user agent feels is best. a value of false is not permitted and will throw a typeerror. if a mediatrackconstraints object is given instead, the video track will be processed to match the settings given in the constraints object. constraints specific to screen sharing these constraints apply to mediatrackconstraints objects specified as pa...
Document.anchors - Web APIs
syntax nodelist = document.anchors; value an htmlcollection. ...
... specifications specification status comment html living standardthe definition of 'document.anchors' in that specification. living standard obsoleted. document object model (dom) level 2 html specificationthe definition of 'document.an...
Document.caretRangeFromPoint() - Web APIs
null, if x or y are negative, outside viewport, or there is no text entry node. example basic demo: when clicking in a paragraph insert a line break at the caret position: html <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...
... null, if x or y are negative, outside viewport, or there is no text entry node. example basic demo: when clicking in a paragraph insert a line break at the caret position: html <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...
Document.createAttribute() - Web APIs
exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. ...
... exceptions invalid_character_err if the parameter contains invalid characters for xml attribute. ...
Document.createProcessingInstruction() - Web APIs
the new node usually will be inserted into an xml document in order to accomplish anything with it, such as with node.insertbefore. syntax pinode = document.createprocessinginstruction(target, data) parameters pinode is the resulting processinginstruction node. target is a string containing the first part of the processing instruction (i.e., <?target … ?>) data is a string containing any information the processing instruction should carry, after the target. the data is up to you, but it can't contain ?>, since that closes the processing instruction. ...
...dded more explicit definition of how the data parameter is validated. document object model (dom) level 3 core specificationthe definition of 'createprocessinginstruction()' in that specification. obsolete added note that the namespace of the target name is not checked whether it is well-formed, defined what is considered an illegal character for the target name and specified the re
turned processinginstruction object more precisely. document object model (dom) level 2 core specificationthe definition of 'createprocessinginstruction()' in that specification. obsolete no change document object model (dom) level 1 specificationthe definition of 'createprocessinginstruction()' in that specification. obsolete initial definition ...
Document.createTouch() - Web APIs
syntax var touch = documenttouch.createtouch(view, target, identifier, pagex, pagey, screenx, screeny); parameters note: all parameters are optional. view the window in which the touch occurred. target the eventtarget for the touch. identifier the value for touch.identifier. pagex the value for touch.pagex. pagey the value for touch.pagey. screenx the value for touch.screenx. screeny the value for touch.screeny. ...
...those parameters are not included in either of the standards listed below. consequently, these parameters should be considered deprecated and not used. clientx the value for touch.clientx. clienty the value for touch.clienty. radiusx the value for touch.radiusx. radiusy the value for touch.radiusy. rotationangle the value for touch.rotationangle. force the value for touch.force. re
turn value touch a touch object configured as described by the input parameters. example this example illustrates using the document.createtouch() method to create touch objects. in following code snippet, two touch objects are created for the target element. var target = document.getelementbyid("target"); var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = doc...
Document.createTouchList() - Web APIs
example this example illustrates using the document.createtouchlist() method to create touchlist objects. ...
... example this example illustrates using the document.createtouchlist() method to create touchlist objects. ...
Document.evaluate() - Web APIs
it will be used to resolve prefixes within the xpath itself, so that they can be matched with the document. null is common for html documents or when no namespace prefixes are used. ...
...lt = document.evaluate( xpathexpression, contextnode, namespaceresolver, resulttype, result ); xpathexpression is a string representing the xpath to be evaluated. contextnode specifies the context node for the query (see the xpath specification). it's common to pass document as the context node. namespaceresolver is a function that will be passed any namespace prefixes and should re
turn a string representing the namespace uri associated with that prefix. it will be used to resolve prefixes within the xpath itself, so that they can be matched with the document. null is common for html documents or when no namespace prefixes are used. resulttype is an integer that corresponds to the type of result xpathresult to re
turn. use named constant properties, such as xpathresult.any_type,...
Document.execCommand() - Web APIs
urrent editable region, such as form inputs or contenteditable elements. most commands affect the document's selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting). when using contenteditable, execcommand() affects the currently active editable element. syntax document.execcommand(acommandname, ashowdefaultui, avalueargument) re
turn value a boolean that is false if the command is unsupported or disabled. note: only re
turns true if part of a user interaction. don't try using the re
turn value to verify browser support before calling a command. parameters acommandname a domstring specifying the name of the command to execute. see commands for a list of possible commands. ashowdefaultui a boolean indicating whether th...
...ion. (not supported by internet explorer.) increasefontsize adds a <big> tag around the selection or at the insertion point. (not supported by internet explorer.) indent indents the line containing the selection or insertion point. in firefox, if the selection spans multiple lines at different levels of indentation, only the least indented lines in the selection will be indented. insertbronre
turn controls whether the enter key inserts a <br> element, or splits the current block element into two. (not supported by internet explorer.) inserthorizontalrule inserts a <hr> element at the insertion point, or replaces the selection with it. inserthtml inserts an html string at the insertion point (deletes selection). requires a valid html string as a value argument. (not supported by intern...
Document.getAnimations() - Web APIs
examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate. ...
... examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate. ...
Document.hasFocus() - Web APIs
example this example checks whether the document has focus every 300 milliseconds. ...
...t has focus. this method can be used to determine whether the active element in a document has focus. when viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. for example, an active element within a popup window that is not the foreground doesn't have focus. syntax var focused = document.hasfocus(); re
turn value false if the active element in the document has no focus; true if the active element in the document has focus. example this example checks whether the document has focus every 300 milliseconds. to test the functionality of hasfocus(), click on the button to open a new window, and try switching between the two pages. html <p id="log">awaiting focus check.</p> <button onclick="openwindo...
Document.hasStorageAccess() - Web APIs
if the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call apis that require user activation. ...
... if the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call apis that require user activation. ...
Document.images - Web APIs
the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif". ...
...the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif". ...
Document.queryCommandSupported() - Web APIs
the document.querycommandsupported() method reports whether or not the specified editor command is supported by the browser. syntax issupported = document.querycommandsupported(command); parameters command the command for which to determine support. re
turn value re
turns a boolean which is true if the command is supported and false if the command isn't. ...
...the document.querycommandsupported() method reports whether or not the specified editor command is supported by the browser. syntax issupported = document.querycommandsupported(command); parameters command the command for which to determine support. re
turn value re
turns a boolean which is true if the command is supported and false if the command isn't. ...
Document.referrer - Web APIs
inside an <iframe>, the document.referrer will initially be set to the same value as the href of the parent window's window.location. ...
... inside an <iframe>, the document.referrer will initially be set to the same value as the href of the parent window's window.location. ...
Document.title - Web APIs
or sets the current title of the document. syntax var doctitle = document.title; doctitle is a string containing the document's title. if the title was overridden by setting document.title, it contains that value. otherwise, it contains the title specified in the markup (see the notes below). document.title = newtitle; newtitle is the new title of the document. the assignment affects the re
turn value of document.title, the title displayed for the document (e.g. in the titlebar of the window or tab), and it also affects the dom of the document (e.g. the content of the <title> element in an html document). example <!doctype html> <html> <head> <title>hello world!</title> </head> <body> <script> alert(document.title); // displays "hello world!" document.title = "goodbye worl...
.../html> notes this property applies to html, svg, xul, and other documents in gecko. for html documents the initial value of document.title is the text content of the <title> element. for xul it's the value of the title attribute of the <xul:window> or other top-level xul element. in xul, accessing document.title before the document is fully loaded has undefined behavior: document.title may re
turn an empty string and setting document.title may have no effect. specifications specification status comment html living standardthe definition of 'document.title' in that specification. living standard ...
DocumentFragment.querySelector() - Web APIs
the documentfragment.queryselector() method re
turns the first element, or null if no matches are found, within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors. if the selector matches an id and this id is erroneously used several times in the document, it re
turns the first matching element. if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. syntax element = documentfragment.queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. ...
...ing element. if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. syntax element = documentfragment.queryselector(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is re
turned: var el = documentfragment.queryselector(".myclass"); css syntax and the method's argument the string argument pass to queryselector must follow the css syntax. to match id or selectors that do not follow the css syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: <div id="foo\bar"></div> <div id="foo:bar"...
DocumentFragment.querySelectorAll() - Web APIs
the documentfragment.queryselectorall() method re
turns a nodelist of elements within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors. if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. note: the definition of this api was moved to the parentnode interface. syntax elementlist = documentfragment.queryselectorall(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. ...
...cified group of selectors. if the selectors specified in parameter are invalid a domexception with a syntax_err value is raised. note: the definition of this api was moved to the parentnode interface. syntax elementlist = documentfragment.queryselectorall(selectors); parameters selectors is a domstring containing one or more css selectors separated by commas. examples this example re
turns a list of all div elements within the documentfragment with a class of either "note" or "alert": var matches = documentfrag.queryselectorall("div.note, div.alert"); specifications specification status comment selectors api level 1the definition of 'documentfragment.queryselectorall' in that specification. obsolete initial definition. ...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
example this example inserts line breaks wherever you click. the code for it is below the demo. demo html content <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...
... example this example inserts line breaks wherever you click. the code for it is below the demo. demo html content <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. ...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
the elementfrompoint() method—available on both the document and shadowroot objects—re
turns the topmost element at the specified coordinates (relative to the viewport). if the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is re
turned (the <iframe> itself). if the element at the given point is anonymous or xbl generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is re
turned. elements with pointer-events set to none will be ignored, and the element below it will be re
turned. if the method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the method is being called. if ...
...dinate is negative, the result is null. if you need to find the specific position inside the element, use document.caretpositionfrompoint(). syntax const element = document.elementfrompoint(x, y) parameters x the horizontal coordinate of a point, relative to the left edge of the current viewport. y the vertical coordinate of a point, relative to the top edge of the current viewport. re
turn value the topmost element object located at the specified coordinates. example this example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2). javascript function changecolor(newcolor) { elem = document.elementfrompoint(2, 2); elem.style.color = newcolor; } the changecolor() method simply obtains the element located at ...
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
the mselementsfromrect method re
turns the node list of elements that are under a rectangle defined by left, top, width, and height. this proprietary method is specific to internet explorer and microsoft edge. syntax object.mselementsfromrect(left, top, width, height, retval) parameters left [in] type: floating-point top[in] type: floating-point width[in] type: floating-point height [in] type: floating-point retval [out, reval] type: nodelist example to find all of the elements under a given point, use mselementsfrompoint(x, y). to find all of the elements which intersect a rectangle, use mselementsfromrect(top, left, width, height). ...
...ting-point height [in] type: floating-point retval [out, reval] type: nodelist example to find all of the elements under a given point, use mselementsfrompoint(x, y). to find all of the elements which intersect a rectangle, use mselementsfromrect(top, left, width, height). var nodelist = document.mselementsfromrect(x,y,width,height) var nodelist = document.mselementsfrompoint(x,y) the re
turned nodelist is sorted by z-index so that you can tell the relative stacking order of the elements. see also advanced hit testing apis demo for mselementsfrompoint() and mselementsfromrect() microsoft api extensions ...
Events and the DOM - Web APIs
't support this method, offering a similar eventtarget.attachevent api instead. for cross-browser compatibility, use one of the many javascript libraries available. more details can be found on the eventtarget.addeventlistener reference page. html attribute <button onclick="alert('hello world!')"> the javascript code in the attribute is passed the event object via the event parameter. the re
turn value is treated in a special way, described in the html specification. warning: this method should be avoided! it inflates the markup, and makes it less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a button element mybutton.onclick = function(event){alert('hello world')} the functio...
...e html specification. warning: this method should be avoided! it inflates the markup, and makes it less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a button element mybutton.onclick = function(event){alert('hello world')} the function can be defined to take an event parameter. the re
turn value is treated in a special way, described in the html specification. the problem with this method is that only one handler can be set per element and per event. accessing event interfaces event handlers may be attached to various objects (including dom elements, document, the window object, etc.). when an event occurs, an event object is created and passed sequentially to the event listener...
Examples of web and XML development using the DOM - Web APIs
you can access these stylesheets and their rules individually using the stylesheet, style, and cssrule objects, as demonstrated in this example, which prints out all of the style rule selectors to the console. var ss = document.stylesheets; for(var i = 0; i < ss.length; i++) { for(var j = 0; j < ss[i].cssrules.length; j++) { ...
...le this example demonstrates how the window.getcomputedstyle method can be used to get the styles of an element that are not set using the style attribute or with javascript (e.g., elt.style.backgroundcolor="rgb(173, 216, 230)"). these latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the dom css properties list. getcomputedstyle() re
turns a computedcssstyledeclaration object, whose individual style properties can be referenced with this object's getpropertyvalue() method, as the following example document shows. <!doctype html> <html lang="en"> <head> <title>getcomputedstyle example</title> <script> function cstyles() { var refdiv = document.getelementbyid("d1"); var txtheight = document.getelementbyid("t1"); var h_style...
Locating DOM elements using selectors - Web APIs
ent nodes from the dom by matching against a set of selectors. this is much faster than past techniques, wherein it was necessary to, for example, use a loop in javascript code to locate the specific items you needed to find. the nodeselector interface this specification adds two new methods to any objects implementing the document, documentfragment, or element interfaces: queryselector() re
turns the first matching element node within the node's subtree. if no matching node is found, null is re
turned. queryselectorall() re
turns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist re
turned by queryselectorall() is not live, which means that changes in the dom are not reflected in the collection. th...
...tree. if no matching node is found, null is re
turned. queryselectorall() re
turns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist re
turned by queryselectorall() is not live, which means that changes in the dom are not reflected in the collection. this is different from other dom querying methods that re
turn live node lists. you may find examples and details by reading the documentation for the element.queryselector() and element.queryselectorall() methods, as well as in the article code snippets for queryselector. selectors the selector methods accept one or more comma-separated selectors to determine what element or elements should be re
turned. for example, to select all paragraph (p) elements i...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ... ...
... examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ... ...
EffectTiming.delay - Web APIs
the effecttiming dictionary's delay property in the web animations api represents the number of milliseconds to delay the start of the animation. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including delay. the value of delay corresponds directly to effecttiming.delay in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { delay: delayinmilliseconds }; timingproperties.delay = delayinmilliseconds; value a number specifying the delay, in milliseconds, from the start of the animation's play cycle to the beginning of its active interval (the time index at which actual animation begins). defaults to 0. examples in the pool of tears examp...
...delayinmilliseconds; value a number specifying the delay, in milliseconds, from the start of the animation's play cycle to the beginning of its active interval (the time index at which actual animation begins). defaults to 0. ...
EffectTiming.duration - Web APIs
effecttiming in the web animations api specifies the duration in milliseconds that a single iteration (from beginning to end) the animation should take to complete. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including duration. the value of duration corresponds directly to animationeffecttimingreadonly.duration in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { duration: durationinmilliseconds | "auto" }; timingproperties.duration = durationinmilliseconds | "auto"; value the number of milliseconds long a single beginning-to-end iteration of the animation should take. the default is "auto". this value must not be negative; otherwise, it can ...
...hild effects. consider using "auto" rather than 0 if that makes sense. exceptions typeerror the specified value is either a string other than "auto", a number less than zero, nan, or some other type of object entirely. ...
Element.animate() - Web APIs
elements can have multiple animations applied to them. you can get a list of the animations that affect an element by calling element.getanimations(). syntax var animation = element.animate(keyframes, options); parameters keyframes either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over. see keyframe formats for more details. ...
... value but result in translatex(-200px) rotate(20deg). accumulate is similar but a little smarter: blur(2) and blur(5) become blur(7), not blur(2) blur(5). replace overwrites the previous value with the new one. iterationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. re
turn value re
turns an animation. examples in the demo down the rabbit hole (with the web animation api), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely. notice the array of objects passed as keyframes and also the timing options block. document.getelementbyid("tunnel").animate([ // keyframes { transf...
Element: auxclick event - Web APIs
ick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
...r changes the button foreground (text) color. you also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
Element.getAnimations() - Web APIs
the getanimations() method of the element interface (specified on the animatable mixin) re
turns an array of all animation objects affecting this element or which are scheduled to do so in future. it can optionally re
turn animation objects for descendant elements too. note: this array includes css animations, css transitions, and web animations. syntax const animations = element.getanimations(options); parameters options optional an options object containing the following property: subtree a boolean value which, if true, causes animations that target descendants of element to be re
turned as well. ...
... const animations = element.getanimations(options); parameters options optional an options object containing the following property: subtree a boolean value which, if true, causes animations that target descendants of element to be re
turned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. re
turn value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree...
Element.getElementsByTagName() - Web APIs
therefore, there is no need to call element.getelementsbytagname() with the same element and arguments repeatedly if the dom changes in between calls. when called on an html element in an html document, getelementsbytagname lower-cases the argument before searching for it. this is undesirable when trying to match camel-cased svg elements (such as <lineargradient>) in an html document. ...
...ent.getelementbyid('forecast-table'); const cells = table.getelementsbytagname('td'); for (let cell of cells) { let status = cell.getattribute('data-status'); if (status === 'open') { // grab the data } } specifications specification status comment domthe definition of 'element.getelementsbytagname()' in that specification. living standard changed the re
turn value from nodelist to htmlcollection document object model (dom) level 3 core specificationthe definition of 'element.getelementsbytagname()' in that specification. obsolete no change from document object model (dom) level 2 core specification document object model (dom) level 2 core specificationthe definition of 'element.getelementsbytagname()' in that specification. ...
Element.getElementsByTagNameNS() - Web APIs
it is similar to document.getelementsbytagnamens, except that its search is restricted to descendants of the specified element. syntax elements = element.getelementsbytagnamens(namespaceuri, localname) elements is a live htmlcollection of found elements in the order they appear in the tree. element is the element from where the search should start. note that only the descendants of this element are included in the search, not the node itself. namespaceuri is the namespace uri of elements to look for (see element.namespaceuri and attr.namespaceuri). ...
...table.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "td"); for (var i = 0; i < cells.length; i++) { var axis = cells[i].getattribute("axis"); if (axis == "year") { // grab the data } } specifications specification status comment domthe definition of 'element.getelementsbytagnamens()' in that specification. living standard changed the re
turn value from nodelist to htmlcollection. document object model (dom) level 3 core specificationthe definition of 'element.getelementsbytagnamens()' in that specification. obsolete no change from document object model (dom) level 2 core specification. document object model (dom) level 2 core specificationthe definition of 'element.getelementsbytagnamens()' in that specificati...
Element.hasAttribute() - Web APIs
the element.hasattribute() method re
turns a boolean value indicating whether the specified element has the specified attribute or not. syntax var result = element.hasattribute(name); result holds the re
turn value true or false. name is a string representing the name of the attribute. ...
...ttribute or not. syntax var result = element.hasattribute(name); result holds the re
turn value true or false. name is a string representing the name of the attribute. ...
Element.innerHTML - Web APIs
use node.textcontent to get a raw copy of these text nodes' contents. to insert the html into the document rather than replace the contents of an element, use the method insertadjacenthtml(). ...
...o a node whose parent is a document. usage notes the innerhtml property can be used to examine the current html source of the page, including any changes that have been made since the page was initially loaded. reading the html contents of an element reading innerhtml causes the user agent to serialize the html or xml fragment comprised of the element's descendants. the resulting string is re
turned. let contents = myelement.innerhtml; this lets you look at the html markup of the element's content nodes. note: the re
turned html or xml fragment is generated based on the current contents of the element, so the markup and formatting of the re
turned fragment is likely not to match the original page markup. replacing the contents of an element setting the value of innerhtml lets you easi...
Element.matches() - Web APIs
exceptions syntax_err the specified selector string is invalid. ...
...ie9+ support). if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatchesselector || element.prototype.webkitmatchesselector; } specification specification status ...
Element: mousewheel event - Web APIs
ttom or toward the right, and positive values indicating scrolling to the top or left. note: on macos, the scroll distance (and therefore the value of detail) is computed based on the accelerated scroll distance. on linux, 2 or -2 is set per native wheel event. wheeldelta, wheeldeltax and wheeldeltay value the wheeldelta attribute value is an abstract value which indicates how far the wheel
turned. if the wheel has rotated away from the user, it's positive, otherwise negative. this means that the delta value sign is different from dom level 3 event's wheel. however, the meaning of the amount of these values is not the same between browsers. see following explanation for the detail. ie and opera (presto) only support wheeldelta attribute and do not support horizontal scroll. the wheelde...
...oll, i.e., the value is the same as ie on windows. on linux, the value is 120 or -120 per native wheel event. this makes the same behavior as ie and chrome for windows. on mac, the value is complicated. the value is changed if the device that causes the native wheel event supports continuous scroll. if the device supports continuous scroll (e.g., trackpad of macbook or mouse wheel which can be
turned smoothly), the value is computed from accelerated scroll amount. in this case, the value is the same as safari. if the device does not support continuous scroll (typically, old mouse wheel which cannot be
turned smoothly), the value is computed from non-accelerated scroll amount (120 per notch). in this case, the value is different from safari. this difference makes a serious issue for web ap...
Element.outerHTML - Web APIs
describing the element including its descendants. it can also be set to replace the element with nodes parsed from the given string. to only obtain the html representation of the contents of an element, or to replace the contents of an element, use the innerhtml property instead. syntax var content = element.outerhtml; element.outerhtml = htmlstring; value reading the value of outerhtml re
turns a domstring containing an html serialization of the element and its descendants. setting the value of outerhtml replaces the element and all of its descendants with a new dom tree constructed by parsing the specified htmlstring. exceptions syntaxerror an attempt was made to set outerhtml using an html string which is not valid. nomodificationallowederror an attempt was made to set outerht...
...ole.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodename); // shows: "p" p.outerhtml = "<div>this div replaced a paragraph.</div>"; console.log(p.nodename); // still "p"; the re
turned value will contain html escaped attributes: var anc = document.createelement("a"); anc.href = "https://developer.mozilla.org?a=b&c=d"; console.log(anc.outerhtml); // output: "<a href='https://developer.mozilla.org?a=b&c=d'></a>" specification specification status comment dom parsing and serializationthe definition of 'element.outerhtml' in that specification.
Element.scrollHeight - Web APIs
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom problems and solutions determine if an element has been totally scrolled the following equivalence re
turns true if an element is at the end of its scroll, false if it isn't. element.scrollheight - element.scrolltop === element.clientheight when the container does not scroll, but has overflowing children, these checks determine if the container can scroll: window.getcomputedstyle(element).overflowy === 'visible' window.getcomputedstyle(element).overflowy !== 'hidden' scrollheight demo associate...
..."thank you." : "please, scroll and read the following text."; } onload = function () { var otoberead = document.getelementbyid("rules"); checkr...
Event.composed - Web APIs
the read-only composed property of the event interface re
turns a boolean which indicates whether or not the event will propagate across the shadow dom boundary into the standard dom. note: this property was formerly named scoped. syntax const iscomposed = event.composed; value a boolean which is true if the event will cross from the shadow dom into the standard dom after reaching the shadow root. (that is, the first node in the shadow dom in which the event began to propagate.) all ua-dispatched ui events are composed (click/touch/mouseover/copy/paste, etc.). most other types of events are not composed, and so will re
turn false. for example, this includes synthetic events that are created without their composed option wil set to true. propagation only occurs if the bubbles property i...
...> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.log(e.composed); console.log(e.composedpath()); }); when you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. the composed property re
turns true beause the click event is always able to propagate across shadow boundaries. you'll notice a difference in the value of composedpath for the two elements. the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element's com...
EventTarget() - Web APIs
the eventtarget() constructor creates a new eventtarget object instance. syntax var myeventtarget = new eventtarget(); parameters none. re
turn value an instance of the eventtarget object. ...
... the eventtarget() constructor creates a new eventtarget object instance. syntax var myeventtarget = new eventtarget(); parameters none. re
turn value an instance of the eventtarget object. ...
EventTarget.dispatchEvent() - Web APIs
eventlisteners in the appropriate order. the normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchevent(). syntax cancelled = !target.dispatchevent(event) parameter event is the event object to be dispatched. target is used to initialize the event.target and determine which event listeners to invoke. re
turn value the re
turn value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault(). otherwise it re
turns true. the dispatchevent() method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. exceptions ex...
...ers 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 re
turn 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. see also the event object reference. example see creating and triggering events. specifications specification status c...
EventTarget.removeEventListener() - Web APIs
usecapture optional specifies whether the eventlistener to be removed is registered as a capturing listener or not. if this parameter is absent, a default value of false is assumed. if a listener is registered twice, one with capture and one without, remove each one separately. removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa. re
turn value undefined matching event listeners for removal given an event listener previously added by calling addeventlistener(), you may eventually come to a point at which you need to remove it. obviously, you need to specify the same type and listener parameters to removeeventlistener(). but what about the options or usecapture parameters? while addeventlistener() will let you add the same list...
...t call fails because the value of usecapture doesn't match. the second succeeds, since usecapture matches up. now consider this: element.addeventlistener("mousedown", handlemousedown, { passive: true }); here, we specify an options object in which passive is set to true, while the other options are left to the default value of false. now look at each of these calls to removeeventlistener() in
turn. any of them in which capture or usecapture is true fail; all others succeed. only the capture setting matters to removeeventlistener(). element.removeeventlistener("mousedown", handlemousedown, { passive: true }); // succeeds element.removeeventlistener("mousedown", handlemousedown, { capture: false }); // succeeds element.removeeventlistener("mousedown", handlemousedown, { capture: tru...
EventTarget - Web APIs
ttarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = null; eventtarget.prototype.addeventlistener = function(type, callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(callback); }; eventtarget.prototype.removeeventlistener = function(type, callback) { if (!(type in this.listeners)) { re
turn; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback){ stack.splice(i, 1); re
turn; } } }; eventtarget.prototype.dispatchevent = function(event) { if (!(event.type in this.listeners)) { re
turn true; } var stack = this.listeners[event.type].slice(); for (var i = 0, l = stack.length; i < l; i++) { ...
... living standard no change. ...
ExtendableEvent.waitUntil() - Web APIs
es, so other events can rely on a completely upgraded state. the waituntil() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274). syntax extendableevent.waituntil(promise); parameters a promise. ...
...settle. note: the behaviour described in the above paragraph was fixed in firefox 43 (see bug 1180274). syntax extendableevent.waituntil(promise); parameters a promise. re
turn 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'); re
turn 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 ...
ExtendableEvent - Web APIs
self.addeventlistener('install', function(event) { var urlstoprefetch = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
... = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customlogo.gif' ]; console.log('handling install event. ...
ExtendableMessageEvent - Web APIs
worker (when a message is received on the serviceworkerglobalscope from another context) — extends the lifetime of such events. this interface inherits from the extendableevent interface. constructor extendablemessageevent() creates a new extendablemessageevent object instance. properties inherits properties from its parent, extendableevent. extendablemessageevent.data read only re
turns the event's data. it can be any data type. extendablemessageevent.origin read only re
turns the origin of the client that sent the message. extendablemessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. this is an empty string. extendablemessageevent.source read only re
turns a reference to the client object that sent the message. e...
... methods inherits methods from its parent, extendableevent. examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. ...
FeaturePolicy.features() - Web APIs
example the followin example logs all the supported directives in the console. ...
... example the followin example logs all the supported directives in the console. ...
FeaturePolicy - Web APIs
the featurepolicy interface of the feature policy api represents the set of policies applied to the current execution context. featurepolicy methods featurepolicy.allowsfeature re
turns a boolean that indicates whether or not a particular feature is enabled in the specified context. featurepolicy.features re
turns a list of names of all features supported by the user agent. feature whose name appears on the list might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. featurepolicy.allowedfeatures re
turns a list of names of all features supported by the user agent and allowed by the feature policy. note that features appearing on this list might still be behind a user permission. featurepolicy.getallow...
...might not be allowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. featurepolicy.allowedfeatures re
turns a list of names of all features supported by the user agent and allowed by the feature policy. note that features appearing on this list might still be behind a user permission. featurepolicy.getallowlistforfeature re
turns the allow list for the specified feature. specification specification status comment feature policy editor's draft initial definition. ...
FetchEvent.preloadResponse - Web APIs
syntax var expectedresponse = fetchevent.preloadresponse; value a promise that resolves to a response or otherwise to undefined. example this code snippet is from the navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. ...
...dwith(). 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) re
turn cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) re
turn response; // else try the network. re
turn fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'preloadresponse' in that specification. working draft ini...
FetchEvent.navigationPreload - Web APIs
the navigationpreload read-only property of the fetchevent interface re
turns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration. syntax var promise = fetchevent.navigationpreload value a promise that resolves to the instance of navigationpreloadmanager. example the following example shows the implementation of a fetch event that uses a preloaded response. ...
...ionpreload 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) re
turn cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) re
turn response; // else try the network. re
turn fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'navigationpreload' in that specification. working draft ...
Fetch API - Web APIs
parate definitions elsewhere. for making a request and fetching a resource, use the windoworworkerglobalscope.fetch() method. it is implemented in multiple interfaces, specifically window and workerglobalscope. this makes it available in pretty much any context you might want to fetch resources in. the fetch() method takes one mandatory argument, the path to the resource you want to fetch. it re
turns a promise that resolves to the response to that request, whether it is successful or not. you can also optionally pass in an init options object as the second argument (see request). once a response is retrieved, there are a number of methods available to define what the body content is and how it should be handled (see body). you can create a request and response directly using the request() ...
...see body). you can create a request and response directly using the request() and response() constructors, but it's uncommon to do this directly. instead, these are more likely to be created as results of other api actions (for example, fetchevent.respondwith() from service workers). differences from jquery the fetch specification differs from jquery.ajax() in three main ways: the promise re
turned from fetch() won’t reject on http error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites...
Using files from web applications - Web APIs
this is done by adding listeners for the dragenter, dragover, and drop events. we don't actually need to do anything with the dragenter and dragover events in our case, so these functions are both simple. they just stop propagation of the event and prevent the default action from occurring: function dragenter(e) { e.stoppropagation(); e...
...= 0; i < files.length; i++) { const file = files[i]; if (!file.type.startswith('image/')){ continue } const img = document.createelement("img"); img.classlist.add("obj"); img.file = file; preview.appendchild(img); // assuming that "preview" is the div output where the content will be displayed. const reader = new filereader(); reader.onload = (function(aimg) { re
turn function(e) { aimg.src = e.target.result; }; })(img); reader.readasdataurl(file); } } here our loop handling the user-selected files looks at each file's type attribute to see if its mime type begins with the string "image/"). for each file that is an image, we create a new img element. css can be used to establish any pretty borders or shadows and to specify the size of the image, so tha...
File.lastModified - Web APIs
syntax const time = instanceoffile.lastmodified; value a number that represents the number of milliseconds since the unix epoch. ...
...low: dynamically created files if a file is created dynamically, the last modified time can be supplied in the new file() constructor function. if it is missing, lastmodified inherits the current time from date.now() at the moment the file object gets created. const filewithdate = new file([], 'file.bin', { lastmodified: new date(2017, 1, 1), }); console.log(filewithdate.lastmodified); //re
turns 1485903600000 const filewithoutdate = new file([], 'file.bin'); console.log(filewithoutdate.lastmodified); //re
turns current time reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodified might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaul...
File.type - Web APIs
syntax var name = file.type; value a string, containing the media type(mime) indicating the type of the file, for example "image/png" for png images example <input type="file" multiple onchange="showtype(this)"> function showtype(fileinput) { var files = fileinput.files; for (var i = 0; i < files.length; i++) { var name = files[i].name; var type = files[i].type; alert("filename: " + name + " , type: " + type); } } note: based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. it is assumed based on the file extension; a png image file renamed to .txt would give "text/plain" and not "image/png". ...
...} } note: based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type. it is assumed based on the file extension; a png image file renamed to .txt would give "text/plain" and not "image/png". moreover, file.type is generally reliable only for common file types like images, html documents, audio and video. uncommon file extensions would re
turn an empty string. client configuration (for instance, the windows registry) may result in unexpected values even for common types. developers are advised not to rely on this property as a sole validation scheme. specifications specification status comment file apithe definition of 'type' in that specification. working draft initial definition. ...
FileEntrySync - Web APIs
concepts to write content to file, create a filewriter object by calling createwriter(). method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (fileexception); parameter none. ...
...y represents. void createwriter ( ) raises (fileexception); parameter none. re
turns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() re
turns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. re
turns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason o...
FileList - Web APIs
it's also used for a list of files dropped into web content when using the drag and drop api; see the datatransfer object for details on this usage. note: prior to gecko 1.9.2, the input element only supported a single file being selected at a time, meaning that the filelist would contain only one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. ...
...fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list. methods item() re
turns a file object representing the file at the specified index in the file list. file item( index ); parameters index the zero-based index of the file to retrieve from the list. re
turn value the file representing the requested file. example this example iterates over all the files selected by the user using an input element: // fileinput is an html input element: <input type="file"...
FileReader.error - Web APIs
specifications specification status comment file apithe definition of 'filereader: error' in that specification. ...
... specifications specification status comment file apithe definition of 'filereader: error' in that specification. ...
FileSystemDirectoryEntry - Web APIs
ch make it possible to access and manipulate the files in a directory, as well as to access the entries within the directory. basic concepts you can create a new directory by calling getdirectory(). if you want to create subdirectories, create each child directory in sequence. if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is re
turned. so create the hierarchy by recursively adding a new path after creating the parent directory. example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; window.directoryentry = window.directoryentry || window.webkitdirectoryentry; ...
...tem(temporary, 1024*1024 /*1mb*/, onfs, onerror); properties this interface has no properties of its own, but inherits properties from its parent interface, filesystementry. methods this interface inherits methods from its parent interface, filesystementry. createreader() creates a filesystemdirectoryreader object which can be used to read the entries in this directory. getdirectory() re
turns a filesystemdirectoryentry object representing a directory located at a given path, relative to the directory on which the method is called. getfile() re
turns a filesystemfileentry object representing a file located within the directory's hierarchy, given a path relative to the directory on which the method is called. obsolete methods removerecursively() deletes a directory and all of it...
FileSystemEntry.fullPath - Web APIs
the read-only fullpath property of the filesystementry interface re
turns a usvstring specifying the full, absolute path from the file system's root to the file represented by the entry. this can also be thought of as a path which is relative to the root directory, with a "/" prepended to it to make it absolute. syntax var fullpath = filesystementry.fullpath; value a usvstring indicating the entry's full path. example this example shows a function which is called with a file system; it then gets a filesystemfileentry for a file named data.json and re
turns its full path. ...
...lue a usvstring indicating the entry's full path. example this example shows a function which is called with a file system; it then gets a filesystemfileentry for a file named data.json and re
turns its full path. function gotfilesystem(fs) { let path = ""; fs.root.getfile("data.json", { create: true, exclusive: true }, function(entry) { path = fullpath; }, handleerror(error)); re
turn path; } obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it. specifications specification status comment file and directory entries apithe definition of 'fullpath' in that specification. draft initial specification.
FileSystemEntry.getParent() - Web APIs
been retrieved. the callback receives a single input parameter: a filesystemdirectoryentry object representing the parent directory. the parent of the root directory is considered to be the root directory, itself, so be sure to watch for that. errorcallback optional an optional callback which is executed if an error occurs. there's a single parameter: a fileerror describing what went wrong. re
turn value undefined. errors fileerror.invalid_state_err the operation failed because the file system's state doesn't permit it. this can happen, for example, if the file system's cached state differs from the actual state of the file system. fileerror.not_found_err the specified path could not be found. fileerror.security_err security restrictions prohibit obtaining the parent directory's i...
...; }); this is accomplished by first obtaining a filesystemdirectoryentry object representing the directory the file is currently located in. then moveto() is used to rename the file within that directory. using promises currently, there isn't a promise-based version of this method. you can, however, create a simple helper function to adapt it, like this: function getparentpromise(entry) { re
turn new promise((resolve, reject) => { entry.getparent(resolve, reject); }); } a similar approach can be taken elsewhere in the file and directory entries api. specifications specification status comment file and directory entries apithe definition of 'getparent()' in that specification. draft initial specification. browser compatibility the compatib...
FileHandle API - Web APIs
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 filehandle api allows for the manipulating of files, including creating files and modifying their content (unlike the file api). because the files manipulated through that api can be physically stored on the device, the editing part uses a
turn-based locking mechanism in order to avoid race issues. api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces. basic operations create a filehandle becau...
...ized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the file object. var mysnapshot = null; var request = myfilehandle.getfile(); request.onsuccess = function () { mysnapshot = this.result; } managing progress all the methods from the lockedfile interface re
turn a filerequest object. such an object is basically a domrequest with an extra power: it allows to monitor the progress of an operation. sometimes writing and reading operations can be very long, therefore it is a good idea to monitor the operation to provide feedback to the user. such monitoring can be done using the filerequest.onprogress event handler. var progress = document.queryselector('pro...
Introduction to the File and Directory Entries API - Web APIs
each of the apis adds different functionality. ...
...es api comes with asynchronous and synchronous versions. both versions of the api offer the same capabilities and features. in fact, they are almost alike, except for a few differences. webworkers. the asynchronous api can be used in either the document or webworkers context, while the synchronous api is for use with webworkers only. callbacks. the asynchronous api doesn't give you data by re
turning values; instead, you have to pass a callback function. you send requests for operations to happen, and get notified by callbacks. in contrast, the synchronous api does not use callbacks because the api methods re
turn values. global methods of the asynchronous and synchronous apis. the asynchronous api has the following global methods: requestfilesystem() and resolvelocalfilesystemurl(). these...
File and Directory Entries API - Web APIs
ecification 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 re
turn the values you desire. the asynchronous api will not block and functions and the api will not re
turn 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; there is no support for creating files. only for accessing files which are selected by the user in a file <in...
...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 finished executing, and simply re
turn 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. f...
FontFace.load - Web APIs
exceptions networkerror indicates that the attempt to load the font failed. ...
... exceptions networkerror indicates that the attempt to load the font failed. ...
FormData.get() - Web APIs
the get() method of the formdata interface re
turns the first value associated with a given key from within a formdata object. if you expect multiple values and want all of them, use the getall() method instead. note: this method is available in web workers. syntax formdata.get(name); parameters name a usvstring representing the name of the key you want to retrieve. re
turn value a formdataentryvalue containing the value. if the key doesn't exist, the method re
turns null. ...
...y you want to retrieve. re
turn value a formdataentryvalue containing the value. if the key doesn't exist, the method re
turns null. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only re
turn the first username value appended: formdata.get('username'); // re
turns "chris" specifications specification status comment xmlhttprequestthe definition of 'get()' in that specification. living standard ...
FormData.getAll() - Web APIs
the getall() method of the formdata interface re
turns all the values associated with a given key from within a formdata object. note: this method is available in web workers. syntax formdata.getall(name); parameters name a usvstring representing the name of the key you want to retrieve. re
turns an array of formdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method re
turns an empty list. ...
...rmdataentryvalues whose key matches the value passed in the name parameter. if the key doesn't exist, the method re
turns an empty list. example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will re
turn both username values in an array: formdata.getall('username'); // re
turns ["chris", "bob"] specifications specification status comment xmlhttprequestthe definition of 'getall()' in that specification. living standard ...
FormData.has() - Web APIs
the has() method of the formdata interface re
turns a boolean stating whether a formdata object contains a certain key. note: this method is available in web workers. syntax formdata.has(name); parameters name a usvstring representing the name of the key you want to test for. re
turns a boolean. ...
...name a usvstring representing the name of the key you want to test for. re
turns a boolean. example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // re
turns false formdata.append('username', 'chris'); formdata.has('username'); // re
turns true specifications specification status comment xmlhttprequestthe definition of 'has()' in that specification. living standard ...
FormData - Web APIs
s equivalent to for (var p of myformdata.entries()). note: this feature is available in web workers. constructor formdata() creates a new formdata object. methods formdata.append() appends a new value onto an existing key inside a formdata object, or adds the key if it does not already exist. formdata.delete() deletes a key/value pair from a formdata object. formdata.entries() re
turns an iterator allowing to go through all key/value pairs contained in this object. formdata.get() re
turns the first value associated with a given key from within a formdata object. formdata.getall() re
turns an array of all the values associated with a given key from within a formdata. formdata.has() re
turns a boolean stating whether a formdata object contains a certain key. formdata.keys() ...
...n iterator allowing to go through all key/value pairs contained in this object. formdata.get() re
turns the first value associated with a given key from within a formdata object. formdata.getall() re
turns an array of all the values associated with a given key from within a formdata. formdata.has() re
turns a boolean stating whether a formdata object contains a certain key. formdata.keys() re
turns an iterator allowing to go through all keys of the key/value pairs contained in this object. formdata.set() sets a new value for an existing key inside a formdata object, or adds the key/value if it does not already exist. formdata.values() re
turns an iterator allowing to go through all values contained in this object. specifications specification status comment x...
Gamepad.hand - Web APIs
the controller is held in both hands, or would be fine in either. ...
...the controller is held in both hands, or would be fine in either. ...
Gamepad.id - Web APIs
this information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. ...
... this information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. ...
Gamepad - Web APIs
properties gamepad.axes read only an array representing the controls with axes present on the device (e.g. analog thumb sticks). ...
... properties gamepad.axes read only an array representing the controls with axes present on the device (e.g. analog thumb sticks). ...
GamepadEvent - Web APIs
examples the gamepad property being called on a fired window.gamepadconnected event. ...
... examples the gamepad property being called on a fired window.gamepadconnected event. ...
GeolocationCoordinates.longitude - Web APIs
the geolocationcoordinates interface's read-only longitude property is a double-precision floating point value which represents the longitude of a geographical position, specified in decimal degrees. together with a domtimestamp indicating a time of measurement, the geolocationcoordinates object is part of the geolocationposition interface, which is the object type re
turned by geolocation api functions that obtain and re
turn a geographical position. syntax let longitude = geolocationcoordinatesinstance.longitude value the value in longitude is the geographical longitude of the location on earth described by the coordinates object, in decimal degrees. the value is defined by the world geodetic system 1984 specification (wgs 84). note: the zero meridian (also known as the prime...
... not precisely the same as the greenwhich meridian that most people think of. it is, instead, the iers reference meridian, which is located 5.3 arcseconds (102 meters / 335 feet) east of the greenwich meridian. this is the same standard used by the global positioning system (gps). examples in this simple example, we fetch the user's location and display the resulting coordinates once they're re
turned. javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude"); button.addeventlistener("click", function() { navigator.geolocation.getcur...
GeolocationPosition.coords - Web APIs
it also contains accuracy information about these values. syntax let coord = geolocationpositioninstance.coords value a geolocationcoordinates object instance. ...
...it also contains accuracy information about these values. syntax let coord = geolocationpositioninstance.coords value a geolocationcoordinates object instance. ...
GeolocationPositionError - Web APIs
the geolocationpositionerror interface represents the reason of an error occurring when using the geolocating device. properties the geolocationpositionerror interface doesn't inherit any property. geolocationpositionerror.code read only secure context re
turns an unsigned short representing the error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position re
turned an internal error. 3 timeout the time allowed to acquire the geolocation,...
...specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. ...
GlobalEventHandlers.onerror - Web APIs
message, source, lineno, colno, error) { ... }; function parameters: message: error message (string). available as event (sic!) in html onerror="" handler. source: url of the script where the error was raised (string) lineno: line number where error was raised (number) colno: column number for the line where the error occurred (number) error: error object (object) when the function re
turns true, this prevents the firing of the default event handler. window.addeventlistener('error') window.addeventlistener('error', function(event) { ... }) event of type errorevent contains all the information about the event and the error. element.onerror element.onerror = function(event) { ... } element.onerror accepts a function with a single argument of type event. a good example for th...
...in browsers that have not implemented this requirement, they can still be obtained via arguments[0] through arguments[2]. specifications specification status comment html l...
GlobalEventHandlers.onkeypress - Web APIs
cument.queryselector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression. ...
... noffset = 0; document.onkeypress = function(opevt) { let oevent = opevt || window.event, nchr = oevent.charcode, snodetype = oevent.target.nodename.touppercase(); if (nchr === 0 || oevent.target.contenteditable.touppercase() === "true" || snodetype === "textarea" || snodetype === "input" && oevent.target.type.touppercase() === "text") { re
turn true; } if (nchr !== ssecret.charcodeat(noffset)) { noffset = nchr === ssecret.charcodeat(0) ? 1 : 0; } else if (noffset < ssecret.length - 1) { noffset++; } else { noffset = 0; /* do something here... */ alert("yesss!!!"); location.assign("https://developer.mozilla.org/"); } re
turn true; }; })(); note: a more complete framework fo...
HTMLCanvasElement.getContext() - Web APIs
to get a different drawing context object you need to pass a different contexttype or call the method on a different canvas element. syntax var ctx = canvas.getcontext(contexttype); var ctx = canvas.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. ...
...emultipliedalpha: boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. stencil: boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. re
turn value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is re
turned. examples given this <canvas> element: <canvas id="canvas" width="300" height="300...
HTMLCanvasElement.mozGetAsFile() - Web APIs
the file's data is entirely located in memory until such time as it is explicitly written to disk. ...
...ting the image contained in the canvas. syntax canvas.mozgetasfile(name, type); parameters name a domstring indicating the file name to give the file representing the image file in memory. type optional a domstring which specifies the image file format to use when creating the new image file. the default type is image/png. for other options, see our image file type and format guide. re
turn value a file object representing the image contained in the canvas. the file's data is entirely located in memory until such time as it is explicitly written to disk. examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file. html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="lin...
HTMLDialogElement.show() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show() method. from there you can click the cancel button to close the dialog (via the htmldialogelement.close() method), or submit the form via the submit button. ...
...l</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.re
turnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes ...
HTMLDialogElement.showModal() - Web APIs
exceptions if the dialog is already open (i.e. ...
...l</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.re
turnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes ...
HTMLDialogElement - Web APIs
mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldialogelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmldialogelement.open a boolean reflecting the open html attribute, indicating whether the dialog is available for interaction. htmldialogelement.re
turnvalue a domstring that sets or re
turns the re
turn value for the dialog. methods inherits methods from its parent, htmlelement. htmldialogelement.close() closes the dialog. an optional domstring may be passed as an argument, updating the re
turnvalue of the the dialog. htmldialogelement.show() displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialo...
...l</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.re
turnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes ...
HTMLElement.offsetHeight - Web APIs
this property will round the value to an integer. ...
...red). it does not include the height of pseudo-elements such as ::before or ::after. for the document body object, the measurement includes total linear content height instead of the element's css height. floated elements extending below other linear content are ignored. if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is re
turned. this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var intelemoffsetheight = element.offsetheight; intelemoffsetheight is a variable storing an integer corresponding to the offsetheight pixel value of the element. the offsetheight property is read-only. example the example image above shows a scro...
HTMLElement.offsetWidth - Web APIs
syntax var intelemoffsetwidth = element.offsetwidth; intelemoffsetwidth is a variable storing an integer corresponding to the offsetwidth pixel value of the element. the offsetwidth property is a read-only. this property will round the value to an integer. ...
...e layout width of an element as an integer. typically, offsetwidth is a measurement in pixels of the element's css width, including any borders, padding, and vertical scrollbars (if rendered). it does not include the width of pseudo-elements such as ::before or ::after. if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is re
turned. syntax var intelemoffsetwidth = element.offsetwidth; intelemoffsetwidth is a variable storing an integer corresponding to the offsetwidth pixel value of the element. the offsetwidth property is a read-only. this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). example specification specification status ...
HTMLFormControlsCollection.namedItem() - Web APIs
the htmlformcontrolscollection.nameditem() method re
turns the radionodelist or the element in the collection whose name or id match the specified name, or null if no node matches. note that this version of nameditem() hides the one inherited from htmlcollection. like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring re
turn value item is a radionodelist , element, or null. ...
...avascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring re
turn value item is a radionodelist , element, or null. example html <form> <input id="my-form-control" type="textarea"> </form> javascript // re
turns the htmlinputelement representing #my-form-control elem1 = document.forms[0]['my-form-control']; specifications specification status comment html living standardthe definition of 'htmlformcontrolscollection.nameditem()' in that specification. living standard html5the definition of 'htmlformcontrolscollection' in that specification. recommendation ...
HTMLFormControlsCollection - Web APIs
this interface replaces one method from htmlcollection, on which it is based. ...
...ale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlformcontrolscollection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface inherits the properties of its parent, htmlcollection. methods this interface inherits the methods of its parent, htmlcollection. htmlformcontrolscollection.nameditem() re
turns the radionodelist or the element in the collection whose name or id matches the specified name, or null if no nodes match. note that this version of nameditem() hide the one inherited from htmlcollection. like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value"). specifications specification ...
HTMLFormElement.length - Web APIs
the htmlformelement.length read-only property re
turns the number of controls in the <form> element. you can access the list of the form's controls using the elements property. this includes both elements that are descendents of the <form> element as well as elements that are made members of the form using their form property. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list re
turned by elements, which makes it an excellent way to get at the elements most important when processing forms. syntax numcontrols = form.length; value ...
...easons) <object> <output> <select> <textarea> no other elements are included in the list re
turned by elements, which makes it an excellent way to get at the elements most important when processing forms. syntax numcontrols = form.length; value numcontrols is the number of form controls within the <form>. this is the same as the number of the elements in the htmlformcontrolscollection re
turned by the elements property. example if (document.getelementbyid('form1').length > 1) { // more than one form control here } specifications specification status comment html living standardthe definition of 'htmlformelement: length' in that specification. living standard ...
HTMLHyperlinkElementUtils.toString() - Web APIs
the htmlhyperlinkelementutils.tostring() stringifier method re
turns a usvstring containing the whole url. it is a read-only version of htmlhyperlinkelementutils.href. ...
...ingifier method re
turns a usvstring containing the whole url. it is a read-only version of htmlhyperlinkelementutils.href. ...
HTMLHyperlinkElementUtils - Web APIs
es utility methods and properties to work with htmlanchorelement and htmlareaelement. these utilities allow to deal with common features like urls. there are no objects of this type, but several objects such as htmlanchorelement and htmlareaelement implement it. properties note: this interface doesn't inherit any property. htmlhyperlinkelementutils.href this a stringifier property that re
turns a usvstring containing the whole url, and allows the href to be updated. htmlhyperlinkelementutils.protocol this is a usvstring containing the protocol scheme of the url, including the final ':'. htmlhyperlinkelementutils.host this is a usvstring containing the host, that is the hostname, and then, if the port of the url is not empty (which can happen because it was not specified or because ...
...htmlhyperlinkelementutils.hash this is a usvstring containing a '#' followed by the fragment identifier of the url. htmlhyperlinkelementutils.username this is a usvstring containing the username specified before the domain name. htmlhyperlinkelementutils.password this is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only this re
turns a usvstring containing the origin of the url (that is its scheme, its domain and its port). methods note: this interface doesn't inherit any method. htmlhyperlinkelementutils.tostring() this re
turns a usvstring containing the whole url. it is a synonym for htmlhyperlinkelementutils.href, though it can't be used to modify the value. specifications specification status c...
HTMLIFrameElement.contentWindow - Web APIs
specifications specification status comment html living standardthe definition of 'htmliframeelement: contentwindow' in that specification. ...
...eelement. you can use this window object to access the iframe's document and its internal dom. this attribute is read-only, but its properties can be manipulated like the global window object. example of contentwindow var x = document.getelementsbytagname("iframe")[0].contentwindow; //x = window.frames[0]; x.document.getelementsbytagname("body")[0].style.backgroundcolor = "blue"; // this would
turn the 1st iframe in document blue. specifications specification status comment html living standardthe definition of 'htmliframeelement: contentwindow' in that specification. living standard ...
HTMLIFrameElement - Web APIs
ttribute. the default value is src. htmliframeelement.allowfullscreen is a boolean indicating whether the inline frame is willing to be placed into full screen mode. see using full-screen mode for details. htmliframeelement.allowpaymentrequest is a boolean indicating whether the payment request api may be invoked inside a cross-origin iframe. htmliframeelement.contentdocument read only re
turns a document, the active document in the inline frame's nested browsing context. htmliframeelement.contentwindow read only re
turns a windowproxy, the window proxy for the nested browsing context. htmliframeelement.csp specifies the content security policy that an embedded document must agree to enforce upon itself. htmliframeelement.frameborder is a domstring that indicates whether to cre...
...ains the uri of a long description of the frame. htmliframeelement.marginheight is a domstring being the height of the frame margin. htmliframeelement.marginwidth is a domstring being the width of the frame margin. htmliframeelement.name is a domstring that reflects the name html attribute, containing a name by which to refer to the frame. htmliframeelement.featurepolicy read only re
turns the featurepolicy interface which provides a simple api for introspecting the feature policies applied to a specific document. htmliframeelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the linked resource. htmliframeelement.sandbox is a domsettabletokenlist that reflects the sandbox html attribute, indicat...
HTMLImageElement.decode() - Web APIs
the decode() method of the htmlimageelement interface re
turns a promise that resolves when the image is decoded and it is safe to append the image to the dom. this can be used to initiate loading of the image prior to attaching it to an element in the dom (or adding it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom. this, in
turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. re
turn value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. usage notes one potential use cas...
...ts source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. at that time, you can then replace the low-resolution image with the full-resolution one that's now available. examples the following example shows how to use the decode() method to control when an image is appended to the dom. without a promise-re
turning method, you would add the image to the dom in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler. const img = new image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendchild(img); }) .catch((encodingerror) => { // do something with the error. }) specifications specification st...
HTMLImageElement.naturalHeight - Web APIs
this is the height the image is if drawn with nothing constraining its height; if you don't specify a height for the image, or place the image inside a container that either limits or expressly specifies the image height, it will be rendered this tall. syntax let naturalheight = htmlimageelement.naturalheight; value an integer value indicating the intrinsic height, in css pixels, of the image. this is the height at which the image is naturally drawn when no constraint or specific value is established for the image. ...
...naturally drawn when no constraint or specific value is established for the image. this natural height is corrected for the pixel density of the device on which it's being presented, unlike height. if the intrinsic height is not available—either because the image does not specify an intrinsic height or because the image data is not available in order to obtain this information, naturalheight re
turns 0. example this example simply displays both the natural, density-adjusted size of an image as well as its rendered size as altered by the page's css and other factors. html <div class="box"> <img src="/files/16797/clock-demo-400px.png" class="image"> </div> <div class="output"> </div> the html features a 400x398 pixel image which is placed inside a <div>. css .box { width: 200px; h...
HTMLMediaElement.audioTracks - Web APIs
once you have a reference to the list, you can monitor it for changes to detect when new audio tracks are added or existing ones removed. see event handlers in audiotracklist to learn more about watching for changes to a media element's track list. ...
...once you have a reference to the list, you can monitor it for changes to detect when new audio tracks are added or existing ones removed. see event handlers in audiotracklist to learn more about watching for changes to a media element's track list. ...
HTMLMediaElement.captureStream() - Web APIs
example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. ...
... example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. ...
HTMLMediaElement.load() - Web APIs
generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. re
turn value undefined. usage notes calling load() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the pr...
...nvolving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the process of aborting any ongoing activities will cause any outstanding promises re
turned by play() being resolved or rejected as appropriate based on their status before the loading of new media can begin. pending play promises are aborted with an "aborterror" domexception. appropriate events will be sent to the media element itself as the load process proceeds: if the element is already in the process of loading media, that load process is aborted and the abort event is sent. ...
HTMLMediaElement.seekToNextFrame() - Web APIs
e, 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). possible uses for this method include filtering and editing of video content. this method re
turns immediately, re
turning a promise, whose fulfillment handler is called when the seek operation is complete. in addition, a seeked event is sent to let interested parties know that a seek has taken place. if the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event. if there is no video on the media element, or the media isn't see...
... is sent to let interested parties know that a seek has taken place. if the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event. if there is no video on the media element, or the media isn't seekable, nothing happens. syntax var seekcompletepromise = htmlmediaelement.seektonextframe(); htmlmediaelement.seektonextframe(); re
turn value a promise which is fulfilled once the seek operation has completed. firefox 49 re
turns undefined instead of a promise, and performs the seek operation synchronously. specifications not part of any specification. ...
HTMLMediaElement.seekable - Web APIs
syntax var seekable = audioorvideo.seekable; value a timeranges object. examples var video = document.queryselector("video"); var timerangesobject = video.seekable; var timeranges = []; //go through the object and output an array for (let count = 0; count < timerangesobject.length; count ++) { timeranges.push([timerangesobject.start(count), timerangesobject.end(count)]); } specifications specification status comment html living standardthe definition of 'htmlmediaelement' in that specification. ...
...tandardthe definition of 'htmlmediaelement' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement' in that specification. recommendation initial definition. media source extensionsthe definition of 'htmlmediaelement extensions, like for seekable' in that specification. recommendation specifies a new algorithm for re
turning the seekable time range of a media element whose source is a mediasource object. ...
HTMLMediaElement.setMediaKeys() - Web APIs
specifications specification status comment encrypted media extensionsthe definition of 'setmediakeys()' in that specification. recommendation initial definition. ...
... specifications specification status comment encrypted media extensionsthe definition of 'setmediakeys()' in that specification. recommendation initial definition. ...
HTMLMediaElement.setSinkId() - Web APIs
parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
... parameters sinkid the mediadeviceinfo.deviceid of the audio output device. ...
HTMLMediaElement.sinkId - Web APIs
syntax var sinkid = htmlmediaelement.sinkid specifications specification status comment audio output devices apithe definition of 'sinkid' in that specification. candidate recommendation initial definition. ...
... syntax var sinkid = htmlmediaelement.sinkid specifications specification status comment audio output devices apithe definition of 'sinkid' in that specification. candidate recommendation initial definition. ...
HTMLSelectElement.item() - Web APIs
the htmlselectelement.item() method re
turns the element corresponding to the htmloptionelement whose position in the options list corresponds to the index given in the parameter, or null if there are none. in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index). syntax var item = collection.item(index); var item = collection[index]; parameters index is an unsigned long. re
turn value item is a htmloptionelement. ...
...elt[index] is equivalent to selectelt.nameditem(index). syntax var item = collection.item(index); var item = collection[index]; parameters index is an unsigned long. re
turn value item is a htmloptionelement. examples html <form> <select id="myformcontrol" type="textarea"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript // re
turns the htmloptionelement representing #o2 elem1 = document.forms[0]['myformcontrol'][1]; specifications specification status comment html living standardthe definition of 'htmlselectelement.item()' in that specification. living standard no change since the latest snapshot, html5. html5the definition of 'htmlselectelement.item()' in that specification. re...
HTMLSelectElement.namedItem() - Web APIs
the htmlselectelement.nameditem() method re
turns the htmloptionelement corresponding to the htmloptionelement whose name or id match the specified name, or null if no option matches. in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring. re
turn value item is a htmloptionelement. ...
...electelt.nameditem("value"). syntax var item = collection.nameditem(str); var item = collection[str]; parameters str is a domstring. re
turn value item is a htmloptionelement. example html <form> <select id="myformcontrol"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript elem1 = document.forms[0]['myformcontrol']['o1']; // re
turns the htmloptionelement representing #o1 specifications specification status comment html living standardthe definition of 'htmlselectelement.nameditem()' in that specification. living standard no change since the latest snapshot, html5. html5the definition of 'htmlselectelement.nameditem()' in that specification. recommendation initial definition, s...
HTMLSlotElement - Web APIs
the htmlslotelement interface of the shadow dom api enables access to the name and assigned nodes of an html <slot> element. properties htmlslotelement.name domstring: can be used to get and set the slot's name. methods htmlslotelement.assignednodes() re
turns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot. if no assigned nodes are found, it re
turns the slot's fallback content. ...
...slotelement.name domstring: can be used to get and set the slot's name. methods htmlslotelement.assignednodes() re
turns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot. if no assigned nodes are found, it re
turns the slot's fallback content. htmlslotelement.assignedelements() re
turns a sequence of the elements assigned to this slot (and no other nodes). if the flatten option is set to true, it also re
turns the assigned elements of any other slots that are descendants of this slot. if no assigned nodes are found, it re
turns the slot's fallback content. events slotchange fired on an htmlslotelement instance (<slot> element) when the node(s) contained in that slot change.
HTMLTableElement.insertRow() - Web APIs
if a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. to insert the row into a specific <tbody>: let specific_tbody = document.getelementbyid(tbody_id); let row = specific_tbody.insertrow(index) note: insertrow() inserts the row directly into the table. the row does not need to be appended separately as would be the case if document.createelement() had been used to create the new <tr> element. syntax var newrow = htmltableelement.insertrow(index); htmltableelement is a reference to an html <table> element. ...
...ement. syntax var newrow = htmltableelement.insertrow(index); htmltableelement is a reference to an html <table> element. parameters index optional the row index of the new row. if index is -1 or equal to the number of rows, the row is appended as the last row. if index is greater than the number of rows, an indexsizeerror exception will result. if index is omitted it defaults to -1. re
turn value newrow is an htmltablerowelement that references the new row. example this example uses insertrow(-1) to append a new row to a table. we then use htmltablerowelement.insertcell() to insert a new cell in the new row. (to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild(). html <table i...
HTMLTableRowElement.insertCell() - Web APIs
note: insertcell() inserts the cell directly into the row. the cell does not need to be appended separately with node.appendchild() as would be the case if document.createelement() had been used to create the new <td> element. you can not use insertcell() to create a new <th> element though. syntax var newcell = htmltablerowelement.insertcell(index); htmltablerowelement is a reference to an html <tr> element. parameters index optional index is the cell index of the new cell. ...
...tmltablerowelement.insertcell(index); htmltablerowelement is a reference to an html <tr> element. parameters index optional index is the cell index of the new cell. if index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. if index is greater than the number of cells, an indexsizeerror exception will result. if index is omitted it defaults to -1. re
turn value newcell is an htmltablecellelement that references the new cell. example this example uses htmltableelement.insertrow() to append a new row to a table. we then use insertcell(0) to insert a new cell in the new row. (to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild(). html <table id...
HTMLTrackElement - Web APIs
e of the text track data. htmltrackelement.label is a domstring that reflects the label html attribute, indicating a user-readable title for the track. htmltrackelement.default a boolean reflecting the default attribute, indicating that the track is to be enabled if the user's preferences do not indicate that another track would be more appropriate. htmltrackelement.readystate read only re
turns an unsigned short that show the readiness state of the track: constant value description none 0 indicates that the text track's cues have not been obtained. loading 1 indicates that the text track is loading and there have been no fatal errors encountered so far. further cues might still be added to the track by the parser. ...
...ill be added to the track by the parser. loaded 2 indicates that the text track has been loaded with no fatal errors. error 3 indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. some or all of the cues are likely missing and will not be obtained. htmltrackelement.track read only re
turns texttrack is the track element's text track data. methods no specific method; inherits methods from its parent, htmlelement. events the following events may be fired on a <track> element, in addition to any that may be fired at its parent, htmlelement. cuechange sent when the underlying texttrack has changed the currently-presented cues. this event is always sent to the texttrack but is...
File drag and drop - Web APIs
s). define the drop zone the target element of the drop event needs an ondrop global event handler. the following code snippet shows how this is done with a <div> element: <div id="drop_zone" ondrop="drophandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> typically, an application will include a dragover event handler on the drop target element and that handler will
turn off the browser's default drag behavior. to add this handler, you need to include a ondragover global event handler: <div id="drop_zone" ondrop="drophandler(event);" ondragover="dragoverhandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> lastly, an application may want to style the drop target element to visually indicate the element is a drop zone. in this example, ...
...onsole.log('... file[' + i + '].name = ' + file.name); } } } else { // use datatransfer interface to access the file(s) for (var i = 0; i < ev.datatransfer.files.length; i++) { console.log('... file[' + i + '].name = ' + ev.datatransfer.files[i].name); } } } prevent the browser's default drag behavior the following dragover event handler calls preventdefault() to
turn off the browser's default drag and drop handler. function dragoverhandler(ev) { console.log('file(s) in drop zone'); // prevent default behavior (prevent file from being opened) ev.preventdefault(); } see also html drag and drop api drag operations html5 living standard: drag and drop ...
Headers() - Web APIs
iteral with bytestring values; or an existing headers object. in the last case, the new headers object inherits its data from the existing headers object. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // re
turns 'image/jpeg' or you can add the headers you want as the headers object is created. in the following snippet we create a new headers object, adding some headers by passing the constructor an init object as an argument: var httpheaders = { 'content-type' : 'image/jpeg', 'accept-charset' : 'utf-8', 'x-my-custom-header' : 'zeke are cool' }; var myheaders = new headers(httpheaders); you can now c...
... living standard ...
Headers.append() - Web APIs
the new value onto the end of the set of values. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. value the value of the http header you want to add. re
turns void. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using append(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // re
turns 'image/jpeg' if the specified header already exists, append() will change its value to the specified value. if the specified header already exist...
... specifications specification status comment fetchthe definition of 'append()' in that specification. ...
Headers.delete() - Web APIs
the value of the name parameter is not the name of an http header. the value of guard is immutable. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. ...
...eader names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. re
turns void. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // re
turns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // re
turns null, as it has been deleted specifications specification status comment fetchthe definition of 'delete()' in that specification. living standard ...
Headers.has() - Web APIs
the has() method of the headers interface re
turns a boolean stating whether a headers object contains a certain header. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.has(name); parameters name the name of the http header you want to test for. if the given name is not a valid http header name, this method throws a typeerror. re
turns a boolean. ...
...or. if the given name is not a valid http header name, this method throws a typeerror. re
turns a boolean. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // re
turns true myheaders.has('accept-encoding'); // re
turns false specifications specification status comment fetchthe definition of 'has()' in that specification. living standard ...
Headers.set() - Web APIs
ity reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a new value. if the given name is not the name of an http header, this method throws a typeerror. value the new value you want to set. re
turns void. example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value ...
...tent-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified value. if the specified header does already exist and does accept multiple values, set() will overwrite the existing value with the new one: myheaders.set('accept-encoding', 'deflate'); myheaders.set('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // re
turns 'gzip' you'd need headers.append to append the new value onto the values, not overwrite it. specifications specification status comment fetchthe definition of 'set()' in that specification. living standard ...
IDBCursor.delete() - Web APIs
the result attribute is set to undefined. ...
...the record at the cursor's position, without changing the cursor's position. once the record is deleted, the cursor's value is set to null. be aware that you can't call delete() (or idbcursor.update()) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax myidbcursor.delete(); re
turns an idbrequest object on which subsequent events related to this operation are fired. the result attribute is set to undefined. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbcursor's transaction is inactive. readonlyerror the transaction mode is read-only. i...
IDBDatabase.createObjectStore() - Web APIs
the method takes the name of the store as well as a parameter object that lets you define important optional properties. you can use the property to uniquely identify individual objects in the store. as the property is an identifier, it should be unique to every object, and every object should have that property. this method can be called only within a versionchange transaction. note: this feature is available in web workers. syntax idbdatabase.createobjectstore(name); idbdatabase.createobjectstore(name, options); parameters name the name of the new object store to be created. ...
... attribute description keypath the key path to be used by the new object store. if empty or not specified, the object store is created without a key path and uses out-of-line keys. you can also pass in an array as a keypath. autoincrement if true, the object store has a key generator. defaults to false. unknown parameters are ignored. re
turns a new idbobjectstore. exceptions this method may raise a domexception with a domerror of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction callback. for older webkit browsers, you must call first. transactioninactiveerror occurs if a request is made on a source data...
IDBDatabase.transaction() - Web APIs
note: this feature is available in web workers. syntax idbdatabase.transaction(storenames); idbdatabase.transaction(storenames, mode); parameters "durability" -- the durability constrints for the transction. valid values are: "default", "strict", and "relaxed". storenames the names of object stores that are in the scope of the new transaction, declared as an array of strings. specify only the object stores that you need to access. ...
...can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. details optional dictionary of other settings, supported only by chrome: re
turn value an idbtransaction object. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the close() method has previously been called on this idbdatabase instance. notfounderror an object store specified in in the storenames parameter has been deleted or removed. typeerror ...
IDBFactory.cmp() - Web APIs
as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent). this throws an exception if either of the values is not a valid key. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. second the second key to compare. ...
... non-numeric arrays are treated as equivalent). this throws an exception if either of the values is not a valid key. syntax var result = indexeddb.cmp(first, second); parameters first the first key to compare. second the second key to compare. re
turn value an integer that indicates the result of the comparison; the table below lists the possible values and their meanings: re
turned value description -1 1st key is less than the 2nd key 0 1st key is equal to the 2nd key 1 1st key is greater than the 2nd key exceptions this method may raise a domexception of the following types: attribute description dataerror one of the supplied keys was not a valid key. example var a = 1; var b = 2; var result ...
databases - Web APIs
name the database name. version the database version. ...
... name the database name. version the database version. ...
IDBFactorySync - Web APIs
ntroduced in the future if there is enough demand from web developers. the idbfactorysync interface of the indexeddb api provide a synchronous means of accessing the capabilities of indexed databases. method overview idbdatabasesync open (in domstring name, in domstring description, in optional boolean modifydatabase) raises (idbdatabaseexception); methods open() opens and re
turns a connection to a database. blocks the calling thread until the connection object is ready to re
turn. if there is already a database with the specified name, it uses that one; otherwise, it creates the database using the specified name and description. idbdatabasesync open ( in domstring name, in domstring description ) raises (idbdatabaseexception); parameters name the name for the d...
... exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid. a valid name is any string including the empty string. ...
IDBIndex.get() - Web APIs
the get() method of the idbindex interface re
turns an idbrequest object, and, in a separate thread, finds either the value in the referenced object store that corresponds to the given key or the first corresponding value, if key is set to an idbkeyrange. if a value is found, then a structured clone of it is created and set as the result of the request object: this re
turns the record the key is associated with. note: this feature is available in web workers. syntax var request = myindex.get(key); parameters key optional a key or idbkeyrange that identifies the record to be retrieved. if this value is null or missing, the browser will use an unbound key range. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method...
... invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. myindex.get('bungle') is then used to retrieve the record with an lname of bungle, and the result of that request is logged to the console when its success callback re
turns. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the exa...
IDBIndex.getKey() - Web APIs
the getkey() method of the idbindex interface re
turns an idbrequest object, and, in a separate thread, finds either the primary key that corresponds to the given key in this index or the first corresponding primary key, if key is set to an idbkeyrange. if a primary key is found, it is set as the result of the request object. note that this doesn't re
turn the whole record as idbindex.get does. note: this feature is available in web workers. syntax var request = myindex.getkey(key); parameters key optional a key or idbkeyrange that identifies a record to be retrieved. if this value is null or missing, the browser will use an unbound key range. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a dome...
... invalidstateerror the idbindex has been deleted or removed. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. myindex.getkey('bungle') is then used to retrieve the primary key of the record with an lname of bungle, and the result of that request is logged to the console when its success callback re
turns. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example d...
IDBIndex.locale - Web APIs
the locale read-only property of the idbindex interface re
turns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) note that this property always re
turns the current locale being used in this index, in other words, it never re
turns "auto". syntax var myindex = objectstore.index('index'); console.log(myindex.locale); value a domstring. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. ...
...jectstore.index('index'); console.log(myindex.locale); value a domstring. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the locale value is logged to the console. function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.locale); myindex.opencursor().onsu...
IDBIndex.multiEntry - Web APIs
this is decided when the index is created, using the idbobjectstore.createindex method. this method takes an optional options parameter whose multientry property is set to true/false. note: this feature is available in web workers. syntax var ismultientry = myindex.multientry; value a boolean: value effect true there is one record in the index for each item in an array of keys. false there is one record for each key that is an array. ...
... false there is one record for each key that is an array. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the multi-entry status of the index is logged to the console: it should be re
turned as false. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var ...
IDBIndex.objectStore - Web APIs
the objectstore property of the idbindex interface re
turns the name of the object store referenced by the current index. note: this feature is available in web workers. syntax var myidbobjectstore = myindex.objectstore; value an idbobjectstore. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor. this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. ...
...n and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor. this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the current object store is logged to the console: it should be re
turned something like this: idbobjectstore { name: "contactslist", keypath: "id", indexnames: domstringlist[7], transaction: idbtransaction, autoincrement: false } finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; v...
IDBIndex.unique - Web APIs
this is decided when the index is created, using the idbobjectstore.createindex method. this method takes an optional parameter, unique, which if set to true means that the index will not be able to accept duplicate entries. note: this feature is available in web workers. syntax var isunique = idbindex.unique; value a boolean: value effect true the current index does not allow duplicate values for a key. false the current index allows duplicate key values. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. ...
...key. false the current index allows duplicate key values. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the unique status of the index is logged to the console: it should be re
turned as false. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var trans...
IDBKeyRange - Web APIs
loweropen is false. the upper value of the key range is one of the following: undefined greater than key value equal to key value if upperopen is false. note: this feature is available in web workers. properties idbkeyrange.lower read only lower bound of the key range. idbkeyrange.upper read only upper bound of the key range. idbkeyrange.loweropen read only re
turns false if the lower-bound value is included in the key range. idbkeyrange.upperopen read only re
turns false if the upper-bound value is included in the key range. methods static methods idbkeyrange.bound() creates a new key range with upper and lower bounds. idbkeyrange.only() creates a new key range containing a single value. idbkeyrange.lowerbound() creates a new key range with on...
... value is included in the key range. methods static methods idbkeyrange.bound() creates a new key range with upper and lower bounds. idbkeyrange.only() creates a new key range containing a single value. idbkeyrange.lowerbound() creates a new key range with only a lower bound. idbkeyrange.upperbound() creates a new upper-bound key range. instance methods idbkeyrange.includes() re
turns a boolean indicating whether a specified key is inside the key range. examples the following example illustrates how you'd use a key range. here we declare a keyrangevalue as a range between values of "a" and "f". we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. this mea...
IDBObjectStore.add() - Web APIs
the add() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. to determine if the add operation has completed successfully, listen for the transaction’s complete event in addition to the idbobjectstore.add request’s success event, because the transaction may still fail after the success event fires. in other words, the success event is only triggered when the transaction has been successfully queued. the add method is an insert only method. if a record already exists in the object store with the key parameter as its key, then an error constrainerror event is fired on the re
turned request object. for upd...
... exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. ...
IDBObjectStore.createIndex() - Web APIs
it creates a new field/column defining a new data point for each database record to contain. bear in mind that indexeddb indexes can contain any javascript data type; indexeddb uses the structured clone algorithm to serialize stored objects, which allows for storage of simple and complex objects. note that this method must be called only from a versionchange transaction mode callback. note: this feature is available in web workers. ...
...locale (see locale-aware sorting.) you can specify its value in one of three ways: string: a string containing a specific locale code, e.g. en-us, or pl. auto: the platform default locale will be used (may be changed by user agent settings.) null or undefined: if no locale is specified, normal javascript sorting will be used — not locale-aware. re
turn value an idbindex object: the newly created index. exceptions this method may raise a domexception of one of the following types: exception description constrainterror occurs if an index with the same name already exists in the database. index names are case-sensitive. invalidaccesserror occurs if the provided key path is a sequence, and multientry is s...
IDBObjectStore.delete() - Web APIs
the delete() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, deletes the specified record or records. either a key or an idbkeyrange can be passed, allowing one or multiple records to be deleted from a store. to delete all records in a store, use idbobjectstore.clear. bear in mind that if you are using a idbcursor, you can use the idbcursor.delete() method to more efficiently delete the current record — without having to explicitly look up the record's key. note: this feature is available in web workers. ...
...the idbcursor.delete() method to more efficiently delete the current record — without having to explicitly look up the record's key. note: this feature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. re
turn value an idbrequest object on which subsequent events related to this operation are fired. the request.result attribute is set to undefined. exceptions this method may raise a domexception of the following types: exception description transactioninactiveerror this object store's transaction is inactive. readonlyerror the object store's transaction mode ...
IDBObjectStore.get() - Web APIs
this is for retrieving specific records from an object store. if a value is successfully found, then a structured clone of it is created and set as the result of the request object. note: this method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an undefined value. to tell these situations apart, call the opencursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. note: this feature is available in web workers. ...
... database and b) a record that has an undefined value. to tell these situations apart, call the opencursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. note: this feature is available in web workers. syntax var request = objectstore.get(key); parameters key the key or key range that identifies the record to be retrieved. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalids...
IDBObjectStore.getAll() - Web APIs
the getall() method of the idbobjectstore interface re
turns an idbrequest object containing all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. if a value is successfully found, then a structured clone of it is created and set as the result of the request object. this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you either call the opencursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. the count() method with the same key, which will re
turn 1 if the row exists and 0 if it doesn't. syntax var request = objectstore.getall(); var request = obj...
...if the row exists and 0 if it doesn't. syntax var request = objectstore.getall(); var request = objectstore.getall(query); var request = objectstore.getall(query, count); parameters query optional a key or idbkeyrange to be queried. if nothing is passed, this will default to a key range that selects all the records in this object store. count optional specifies the number of values to re
turn if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transactio...
IDBObjectStore.getAllKeys() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object. this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you need to call the opencursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. ...
...e opencursor() method with the same key. that method provides a cursor if the record exists, and no cursor if it does not. syntax var request = objectstore.getallkeys(); var request = objectstore.getallkeys(query); var request = objectstore.getallkeys(query, count); parameters query optional a value that is or resolves to an idbkeyrange. count optional specifies the number of values to re
turn if more than one is found. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transactio...
IDBObjectStore.index() - Web APIs
the index() method of the idbobjectstore interface opens a named index in the current object store, after which it can be used to, for example, re
turn a series of records sorted by that index using a cursor. note: this feature is available in web workers. syntax var index = objectstore.index(name); parameters name the name of the index to open. re
turn value an idbindex object for accessing the index. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished. notfounderror there is no index with the given name (case-sensitive) in the database. example in the following ex...
... no index with the given name (case-sensitive) in the database. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. finally, we iterate through each record, and insert the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.obj...
IDBObjectStore.openCursor() - Web APIs
used for iterating through an object store with a cursor. to determine if the add operation has completed successfully, listen for the results’s success event. note: this feature is available in web workers. syntax var request = objectstore.opencursor(); var request = objectstore.opencursor(query); var request = objectstore.opencursor(query, direction); parameters query optional a key or idbkeyrange to be queried. if a single valid key is passed, this will default to a range containing only that key. ...
...dbkeyrange to be queried. if a single valid key is passed, this will default to a range containing only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror t...
IDBObjectStore.openKeyCursor() - Web APIs
used for iterating through the keys of an object store with a cursor. to determine if the add operation has completed successfully, listen for the results’s success event. syntax var request = objectstore.openkeycursor(); var request = objectstore.openkeycursor(query); var request = objectstore.openkeycursor(query, direction); parameters query optional the key range to be queried. if a single valid key is passed, this will default to a range containing only that key. ...
... key range to be queried. if a single valid key is passed, this will default to a range containing only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbcursordirection telling the cursor what direction to travel. valid values are "next", "nextunique", "prev", and "prevunique". the default is "next". re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore or idbindex has been deleted. transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror t...
IDBRequest.onerror - Web APIs
the event handler takes one parameter, an error event with type="error". note: this feature is available in web workers. syntax request.onerror = function(event) { ... }; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. also included at the bottom is an onerror function that reports what the error was if the request fails. ...
...mple, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsucc...
IDBRequest.onsuccess - Web APIs
the event handler takes one parameter, a success event with type="success". note: this feature is available in web workers. syntax request.onsuccess = function(event) { ... }; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. ...
...mple, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsucc...
IDBRequest.readyState - Web APIs
every request starts in the pending state. the state changes to done when the request completes successfully or when an error occurs. note: this feature is available in web workers. syntax var currentreadystate = request.readystate; value the idbrequestreadystate of the request, which takes one of the following two values: value meaning pending the request is pending. done the request is done. ...
...mple, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the readystate of this request is " + updatetitlerequest.readystate); // w...
IDBRequest.result - Web APIs
if the request failed and the result is not available, an invalidstateerror exception is thrown. note: this feature is available in web workers. syntax var myresult = request.result; value any example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store. ...
...mple, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsucc...
IDBRequest.source - Web APIs
note: this feature is available in web workers. syntax var idbindex = request.source; var idbcursor = request.source; var idbobjectstore = request.source; value an object representing the source of the request, such as an idbindex, idbobjectstore or idbcursor. ...
...ample, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as its title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object re
turned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the source of this request is " + updatetitlerequest.source); // when this ...
IDBTransaction.db - Web APIs
the db read-only property of the idbtransaction interface re
turns the database connection with which this transaction is associated. note: this feature is available in web workers. syntax var mydatabase = transaction.db; value an idbdatabase object. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we re
turn the associated database connection using db. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = funct...
... recommendation indexed database api draftthe definition of 'db' in that specification. recommendation browser compatibility t...
IDBTransaction.error - Web APIs
the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). ...
...the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). ...
IDBTransaction.mode - Web APIs
is the mode to be read-only, or do you want to write to the object stores?) the default value is readonly. note: this feature is available in web workers. syntax var mycurrentmode = idbtransaction.mode; value an idbtransactionmode object defining the mode for isolating access to data in the current object stores: value explanation readonly allows data to be read but not changed. readwrite allows reading and writing of data in existing data stores to be changed. ...
... recommendation indexed database api draftthe definition of 'mode' in that specification. recommendation browser compatibi...
IDBVersionChangeRequest.setVersion() - Web APIs
the idbversionchangerequest.setversion method updates the version of the database, re
turning immediately and running a versionchange transaction on the connected database in a separate thread. for older webkit browsers, call this method before creating or deleting an object store. warning: the latest draft of the specification has dropped this method. some not up-to-date browsers still implement this method. the new way is to define the version in the idbdatabase.open() method and create and delete object stores in the onupgradeneeded event handler associated with the re
turned request. ...
... browser compatibility the compatibility table on this page is generated from structured data. ...
IdleDeadline.timeRemaining() - Web APIs
the timeremaining() method on the idledeadline interface re
turns the estimated number of milliseconds remaining in the current idle period. the callback can call this method at any time to determine how much time it can continue to work before it must re
turn. for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just re
turn immediately, or look for other work to do with the remaining time. by the time timeremaining() reaches 0, it is suggested that the callback should re
turn control to the user agent's event loop. ...
...r one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just re
turn immediately, or look for other work to do with the remaining time. by the time timeremaining() reaches 0, it is suggested that the callback should re
turn control to the user agent's event loop. syntax timeremaining = idledeadline.timeremaining(); re
turn value a domhighrestimestamp value (which is a floating-point number) representing the number of milliseconds the user agent estimates are left in the current idle period. the value is ideally accurate to within about 5 microseconds. if the idledeadline object's didtimeout property is true, this method re
turns zero. example see our complete example in the article cooperative scheduling of back...
ImageCapture.takePhoto() - Web APIs
syntax const blobpromise = imagecaptureobj.takephoto([photosettings]) parameters photosettings optional an object that sets options for the photo to be taken. the available options are: filllightmode: the flash setting of the capture device, one of "auto", "off", or "flash". imageheight: the desired image height as an integer. the user agent selects the closest height value to this setting if it only supports discrete heights. ...
...red image height as an integer. the user agent selects the closest height value to this setting if it only supports discrete heights. imagewidth: the desired image width as an integer. the user agent selects the closest width value to this setting if it only supports discrete widths. redeyereduction: a boolean indicating whether the red-eye reduction should be used if it is available. re
turn value a promise that resolves with a blob. example this example is extracted from this simple image capture demo. it shows how to use the promise re
turned by takephoto() to copy the re
turned blob to an <img> element. for simplicy it does not show how to instantiate the imagecapture object. var takephotobutton = document.queryselector('button#takephoto'); var canvas = document.queryselector('c...
ImageCapture - Web APIs
r photos from a camera or other photographic device. it provides an interface for capturing images from a photographic device referenced through a valid mediastreamtrack. constructor imagecapture() creates a new imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream. properties imagecapture.track read only re
turns a reference to the mediastreamtrack passed to the constructor. methods the imagecapture interface is based on eventtarget, so it includes the methods defined by that interface as well as the ones listed below. imagecapture.takephoto() takes a single exposure using the video capture device sourcing a mediastreamtrack and re
turns a promise that resolves with a blob containing the data. ima...
...k passed to the constructor. methods the imagecapture interface is based on eventtarget, so it includes the methods defined by that interface as well as the ones listed below. imagecapture.takephoto() takes a single exposure using the video capture device sourcing a mediastreamtrack and re
turns a promise that resolves with a blob containing the data. imagecapture.getphotocapabilities() re
turns a promise that resolves with a photocapabilities object containing the ranges of available configuration options. imagecapture.getphotosettings() re
turns a promise that resolves with a photosettings object containing the current photo configuration settings. imagecapture.grabframe() takes a snapshot of the live video in a mediastreamtrack, re
turning an imagebitmap, if successful. example ...
ImageData() - Web APIs
the imagedata() constructor re
turns a newly instantiated imagedata object built from the typed array given and having the specified width and height. this constructor is the preferred way of creating such an object in a worker. syntax new imagedata(array, width [, height]); new imagedata(width, height); parameters array optional a uint8clampedarray containing the underlying pixel representation of the image. if no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. ...
...el representation of the image. if no such array is given, an image with a transparent black rectangle of the specified width and height will be created. width an unsigned long representing the width of the image. height an unsigned long representing the height of the image. this value is optional if an array is given: the height will be inferred from the array's size and the given width. re
turn value a new imagedata object. errors thrown indexsizeerror thrown if array is specified, but its length is not a multiple of (4 * width) or (4 * width * height). examples creating a blank imagedata object this example creates an imagedata object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imagedata = new imagedata(200, 100); // imagedata { widt...
IndexedDB API - Web APIs
s by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. browser storage 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 re
turns 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...
...s access to a set of data in an indexeddb database, looked up via primary key. idbindex also allows access to a subset of data in an indexeddb database, but uses an index to retrieve the record(s) rather than the primary key. this is sometimes faster than using idbobjectstore. idbcursor iterates over object stores and indexes. idbcursorwithvalue iterates over object stores and indexes and re
turns the cursor's current value. idbkeyrange defines a key range that can be used to retrieve data from a database in a certain range. idblocaleawarekeyrange defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createindex()'s optionalparameters.). this interface isn't part of the...
firesTouchEvents - Web APIs
the inputdevicecapabilities.firestouchevents read-only property re
turns a boolean that indicates whether the device dispatches touch events. you can use this property to detect mouse events that represent an action that may already have been handled by touch event handlers. this doesn't necessarily mean the device is a touch screen. for example, stylus and mouse devices typically generate touch events on mobile browsers. ...
...tes whether the device dispatches touch events. you can use this property to detect mouse events that represent an action that may already have been handled by touch event handlers. this doesn't necessarily mean the device is a touch screen. for example, stylus and mouse devices typically generate touch events on mobile browsers. syntax var boolean = inputdevicecapabilities.firestouchevents re
turns a boolean example mybutton.addeventlistener('mousedown', function(e) { if (!e.sourcecapabilities.firestouchevents) mybutton.classlist.add("pressed"); }); specifications specification status comment inputdevicecapabilitiesthe definition of 'firetouchevents' in that specification. draft initial definition. ...
InstallEvent.activeWorker - Web APIs
syntax var myactiveworker = event.activeworker value a serviceworker object. ...
... syntax var myactiveworker = event.activeworker value a serviceworker object. ...
getVersion - Web APIs
parts of this page show the use of the xpinstall api. the majority of this api is now deprecated and as of gecko 1.9 no longer available. extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. ...
...rsion re
turns an object representing the version number from the client version registry for the specified component. it is used in both trigger scripts and installation scripts. method of installtrigger object syntax installversion getversion ( string component ); parameters the getversion method has one parameter: component the name of a component in the client version registry. re
turns if software installation is disabled, this method re
turns null. otherwise, it re
turns an installversion object representing the version of the component. if the component has not been registered in the client version registry or if the specified component was installed with a null version, this method re
turns null. installing a component with a null version indicates that the component shoul...
IntersectionObserver.IntersectionObserver() - Web APIs
the rootmargin, if specified, is checked to ensure it's syntactically correct, the thresholds are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order. if the threshold list is empty, it's set to the array [0.0]. syntax var observer = new intersectionobserver(callback[, options]); parameters callback a function which is called when the percentage of the target element is visible crosses a threshold. ...
...ween 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target. a value of 0.0 means that even a single visible pixel counts as the target being visible. 1.0 means that the entire target element is visible. see thresholds in intersection observer api for a more in-depth description of how thresholds are used. the default is a threshold of 0.0. re
turn value a new intersectionobserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds. call its observe() method to begin watching for the visibility changes on a given target. exceptions syntaxerror the specified rootmargin is invalid. rangeerror one or more of the values in threshold is ou...
IntersectionObserver.takeRecords() - Web APIs
the intersectionobserver method takerecords() re
turns an array of intersectionobserverentry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a call to this method or implicitly by an automatic call to the observer's callback. note: if you use the callback to monitor these changes, you don't need to call this method. calling this method clears the pending intersection list, so the callback will not be run. syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. ...
...ked, either explicitly through a call to this method or implicitly by an automatic call to the observer's callback. note: if you use the callback to monitor these changes, you don't need to call this method. calling this method clears the pending intersection list, so the callback will not be run. syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. re
turn value an array of intersectionobserverentry objects, one for each target element whose intersection with the root has changed since the last time the intersections were checked. examples <<<...>>> specifications specification status comment intersection observerthe definition of 'intersectionobserver.takerecords()' in that specification. working draft ini...
Keyboard.getLayoutMap() - Web APIs
example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
... example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
Keyboard.lock() - Web APIs
examples capturing all keys the following example captures all keypresses. ...
...the keys on the physical keyboard. this method can only capture keys that are granted access by the underlying operating system. syntax var promise = keyboard.lock([keycodes[]]) parameters keycodes optional an array of one or more key codes to lock. if no keycodes are provided all keys will be locked. a list of valid code values is found in the ui events keyboardevent code values spec. re
turn value a promise. examples capturing all keys the following example captures all keypresses. navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys. it captures these keys regardless of which modifiers are used with the key press. assuming a standard us qwerty layout, registering "keyw" ensures that "w", shift+"w", control+"w", cont...
KeyboardEvent.ctrlKey - Web APIs
the keyboardevent.ctrlkey read-only property re
turns a boolean that indicates if the control key was pressed (true) or not (false) when the event occured. ...
... the keyboardevent.ctrlkey read-only property re
turns a boolean that indicates if the control key was pressed (true) or not (false) when the event occured. ...
KeyboardEvent.metaKey - Web APIs
the keyboardevent.metakey read-only property re
turning a boolean that indicates if the meta key was pressed (true) or not (false) when the event occurred. some operating systems may intercept the key so it is never detected. note: on macintosh keyboards, this is the ⌘ command key. on windows keyboards, this is the windows key (⊞ windows). at least as of firefox 48, the ⊞ windows key is not considered the "meta" key. keyboardevent.metakey is false when the ⊞ windows is pressed. ...
...erating systems may intercept the key so it is never detected. note: on macintosh keyboards, this is the ⌘ command key. on windows keyboards, this is the windows key (⊞ windows). at least as of firefox 48, the ⊞ windows key is not considered the "meta" key. keyboardevent.metakey is false when the ⊞ windows is pressed. syntax var metakeypressed = instanceofkeyboardevent.metakey re
turn value a boolean example function ismetakey(e) { alert("metakey = " + e.metakey); } <button onclick="ismetakey(event)">click me with the meta key</button> specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.metakey' in that specification. obsolete initial definition ...
KeyboardEvent.which - Web APIs
please see keyboardevent.charcode and keyboardevent.keycode for more details. ...
...please see keyboardevent.charcode and keyboardevent.keycode for more details. ...
Keyboard API - Web APIs
and modifier-key state (shift, control, etc.). historically there has been no way to retrieve that information. the keyboard map api provides a way to retrieve the string generated by a particular key press, through the keyboard interface and the keyboardlayoutmap interface. the keyboard interface is accessed through navigator.keyboard. keyboard provides the keyboard.getlayoutmap method, which re
turns a promise that resolves with a keyboardlayoutmap object that contains members for converting codes to keys. a list of valid code values is found in the writing system keys section of the ui events keyboardevent code values spec. the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keyboard. if (navi...
...ys are present on all standard keyboards while green keys are only available on some keyboards. interfaces keyboard provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. keyboardlayoutmap a map-like object with functions for retrieving the string associated with specific physical keys. navigator.keyboard read only re
turns a keyboard object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. specifications specification status comment keyboard map editor's draft initial definition. keyboard lock editor's draft initial definition. ...
KeyframeEffect.getKeyframes() - Web APIs
offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes. this will be null if the keyframe is automatically spaced using keyframeeffect.spacing. ...
...il the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be absent if the composite operation specified on the effect is being used. examples in the red queen race example, we can inspect alice and the redqueen's animation to see its individual keyframes like so: // re
turn the array of keyframes redqueen_alice.effect.getkeyframes(); specifications specification status comment web animationsthe definition of 'keyframeeffect.getkeyframes()' in that specification. working draft editor's draft. ...
KeyframeEffect.setKeyframes() - Web APIs
ect with a new set of keyframes. syntax existingkeyframeeffect.setkeyframes(keyframes); parameters keyframes a keyframe object or null. if set to null, the keyframes are replaced with a sequence of empty keyframes. there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over. this is the canonical format re
turned by the getkeyframes() method. element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); offsets for each keyframe can be specified by providing an offset value. element.animate([ { opacity: 1 }, { opacity: 0.1, offset: 0.7 }, { opacity: 0 } ], 2000); note: ...
... or missing, the keyframe will be evenly spaced between adjacent keyframes. easing the timing function used from this keyframe until the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be auto if the composite operation specified on the effect is being used. re
turn value void. exceptions exception explanation typeerror one or more of the frames were not of the correct type of object, the keyframes were not loosely sorted by offset, or a keyframe existed with an offset of less than 0 or more than 1. note: if the keyframes cannot be processed or are malformed, the keyframeeffect's keyframes are not modified. examples ...
KeyframeEffect.target - Web APIs
nterface represents the element or pseudo-element being animated. it may be null for animations that do not target a specific element. it performs as both a getter and a setter, except with animations and transitions generated by css. syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes = new keyframeeffect( targetelement, keyframeblock, timingoptions ); // re
turns #elementtoanimate keyframes.target; // assigns keyframes a new target keyframes.target = newtargetelement; value an element, csspseudoelement, or null. examples in the follow the white rabbit example, whiterabbit sets the target element to be animated: var whiterabbit = document.getelementbyid("rabbit"); var rabbitdownkeyframes = new keyframeeffect( whiterabbit, [ { transform: 't...
... value an element, csspseudoelement, or null. examples in the follow the white rabbit example, whiterabbit sets the target element to be animated: var whiterabbit = document.getelementbyid("rabbit"); var rabbitdownkeyframes = new keyframeeffect( whiterabbit, [ { transform: 'translatey(0%)' }, { transform: 'translatey(100%)' } ], { duration: 3000, fill: 'forwards' } ); // re
turns <div id="rabbit">click the rabbit's ears!</div> rabbitdownkeyframes.target; specifications specification status comment web animationsthe definition of 'keyframeeffect' in that specification. working draft editor's draft. ...
KeyframeEffect - Web APIs
properties keyframeeffect.target gets and sets the element, or originating element of the pseudo-element, being animated by this object. ...
...ets and sets the iteration composite operation for resolving the property value changes of this keyframe effect. keyframeeffect.composite gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects. methods this interface inherits some of its methods from its parent, animationeffect. animationeffect.getcomputedtiming() re
turns the calculated, current timing values for this keyframe effect. keyframeeffect.getkeyframes() re
turns the computed keyframes that make up this effect along with their computed keyframe offsets. animationeffect.gettiming() the effecttiming object associated with the animation containing all the animation's timing values. keyframeeffect.setkeyframes() replaces the set of keyframes that ma...
LinkStyle - Web APIs
the linkstyle interface provides access to the associated css style sheet of a node. linkstyle is a raw interface and no object of this type can be created; it is implemented by htmllinkelement and htmlstyleelement objects. properties there is no inherited property. linkstyle.sheet read only re
turns the cssstylesheet object associated with the given element, or null if there is none. methods this interface implements no method. ...
...operties there is no inherited property. linkstyle.sheet read only re
turns the cssstylesheet object associated with the given element, or null if there is none. methods this interface implements no method. specifications specification status comment css object model (cssom)the definition of 'linkstyle' in that specification. working draft linkstyle.sheet re
turns more specialized cssstylesheet instead of stylesheet document object model (dom) level 2 style specificationthe definition of 'linkstyle' in that specification. obsolete initial definition ...
LocalFileSystem - Web APIs
ystem. its argument is the filesystem object with two properties: name - the unique name assigned by the browser to the file system. root - the read-only directoryentry object representing the root of the file system. opt_errorcallback the error callback that is called when errors happen or when the request to obtain the file system is denied. its argument is the fileerror object. re
turns void exceptions this method can raise an fileerror with the following code: exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemurl() lets you look up the entry for a file or dire...
... in entrycallback successcallback, in optional errorcallback errorcallback ); parameters url the url of a local file in the file system. successcallback the success callback that is called when the browser provides the file or directory for the supplied url. errorcallback the error callback that is called when errors happen or when the request to obtain the entry object is denied. re
turns void exceptions this method can raise an fileerror with the following code: exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. b...
LocalFileSystemSync - Web APIs
a localfilesystemsync object from within a web worker using this global method, window.requestfilesystemsync(). [ research ] filesystemsync requestfilesystemsync( in unsigned short type, in unsigned long long size ); parameters type the storage type of the file system. the values can be either temporary or persistent. size the storage space—in bytes—that you need for your app. re
turns filesystemsync an object that represents the file system. exceptions this method can raise an fileexception with the following code: exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfile...
... have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directory referred to by a local url. void resolvelocalfilesystemurl( in domstring url ); parameter url the url of a local file in the file system. re
turns entrysync an object that represents entries in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does n...
Location: toString() - Web APIs
the tostring() stringifier method of the location interface re
turns a usvstring containing the whole url. it is a read-only version of location.href. ...
...ng() stringifier method of the location interface re
turns a usvstring containing the whole url. it is a read-only version of location.href. ...
LockManager.query() - Web APIs
held: an array of lock objects for held locks. pending: an array of lock objects for pending lock requests. ...
... held: an array of lock objects for held locks. pending: an array of lock objects for pending lock requests. ...
Long Tasks API - Web APIs
nput latency. high/variable event handling latency. janky animations and scrolling. concepts some key terms or ideas that are utilized by the long tasks api. long task any uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include: long running event handlers. expensive reflows and other re-renders. work the browser does between different
turns of the event loop that exceeds 50 ms. culprit browsing context container the "culprit browsing context container", or "the container" for short, is the top level page, iframe, embed or object that the task occurred within. attributions a list of containers that the task occurred within. for tasks that don't occur within the top level page, the containerid, containername and containersrc fie...
...tifications: // report back for analytics and monitoring // ... } }); // register observer for long task notifications observer.observe({entrytypes: ["longtask"]}); // long script execution after this will result in queueing // and receiving "longtask" entries in the observer. interfaces performancelongtasktiming reports instances of long tasks. taskattributiontiming re
turns information about the work involved in a long task and its associate frame context. specifications specification status comment long tasks api 1 working draft initial definition. ...
MIDIAccess - Web APIs
midiaccess.sysexenabled read only a boolean attribute indicating whether system exclusive support is enabled on the current midiaccess instance. ...
... midiaccess.sysexenabled read only a boolean attribute indicating whether system exclusive support is enabled on the current midiaccess instance. ...
MSGestureEvent - Web APIs
the msgestureevent is a proprietary interface specific to internet explorer and microsoft edge which represents events that occur due to touch gestures. events using this interface include msgesturestart, msgestureend, msgesturetap, msgesturehold, msgesturechange, and msinertiastart. msgestureevent derives from uievent, which in
turn derives from event. though the msgestureevent.initgestureevent() method is kept for backward compatibility, the creation of an msgestureevent object should be done using the msgestureevent() constructor. constructor msgestureevent() creates an msgestureevent object. properties this interface also inherits properties of its parents, uievent and event. msgestureevent.expansion read only the diameter of the gesture area. for example, the di...
...f an msgestureevent object should be done using the msgestureevent() constructor. constructor msgestureevent() creates an msgestureevent object. properties this interface also inherits properties of its parents, uievent and event. msgestureevent.expansion read only the diameter of the gesture area. for example, the distance between fingers. msgestureevent.gestureobject read only re
turns the msgesture object for this gesture event. msgestureevent.rotation read only amount of rotation (in radians) since the previous msgestureevent of the current gesture. positive values indicate clockwise rotation; negative values indicate anticlockwise rotation. msgestureevent.scale read only the difference in scale (for zoom gestures) from the previous msgestureevent of the current gestur...
MediaCapabilities.decodingInfo() - Web APIs
the mediacapabilities.decodinginfo() method, part of the media capabilities api, re
turns a promise with the tested media configuration's mediacapabilitiesinfo; this contains the three boolean properties supported, smooth, and powerefficient, which describe whether decoding the media described would be supported, smooth, and powerefficient. syntax mediacapabilities.decodinginfo(mediadecodingconfiguration) parameters mediadecodingconfiguration a valid mediadecodingconfiguration dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an audioconfiguration or a videoconfiguration. ...
...ibe whether decoding the media described would be supported, smooth, and powerefficient. syntax mediacapabilities.decodinginfo(mediadecodingconfiguration) parameters mediadecodingconfiguration a valid mediadecodingconfiguration dictionary containing a valid media decoding type of file or media-source and a valid media configuration: either an audioconfiguration or a videoconfiguration. ...
MediaCapabilities.encodingInfo() - Web APIs
the mediacapabilities.encodinginfo() method, part of the mediacapabilities interface of the media capabilities api, re
turns a promise with the tested media configuration's mediacapabilitiesinfo; this contains the three boolean properties supported, smooth, and powerefficient, which describe how compatible the device is with the type of media. syntax mediacapabilities.encodinginfo(mediaencodingconfiguration) parameters mediaencodingconfiguration a valid mediaencodingconfiguration dictionary containing a valid media encoding type of record or transmission and a valid media configuration: either an audioconfiguration or videoconfiguration dictionary. ...
...fficient, which describe how compatible the device is with the type of media. syntax mediacapabilities.encodinginfo(mediaencodingconfiguration) parameters mediaencodingconfiguration a valid mediaencodingconfiguration dictionary containing a valid media encoding type of record or transmission and a valid media configuration: either an audioconfiguration or videoconfiguration dictionary. ...
MediaDevices.getSupportedConstraints() - Web APIs
because only constraints supported by the user agent are included in the list, each of these boolean properties has the value true. example this example outputs a list of the constraints supported by your browser. ...
...because only constraints supported by the user agent are included in the list, each of these boolean properties has the value true. example this example outputs a list of the constraints supported by your browser. ...
MediaDevices - Web APIs
eventtarget. events devicechange fired when a media input or output device is attached to or removed from the user's computer. also available via the ondevicechange property. methods inherits methods from its parent interface, eventtarget. enumeratedevices() obtains an array of information about the media input and output devices available on the system. getsupportedconstraints() re
turns an object conforming to mediatracksupportedconstraints indicating which constrainable properties are supported on the mediastreamtrack interface. see capabilities and constraints in media capture and streams api (media stream) to learn more about constraints and how to use them. getdisplaymedia() prompts the user to select a display or portion of a display (such as a window) to capture as a me...
...nstraints indicating which constrainable properties are supported on the mediastreamtrack interface. see capabilities and constraints in media capture and streams api (media stream) to learn more about constraints and how to use them. getdisplaymedia() prompts the user to select a display or portion of a display (such as a window) to capture as a mediastream for sharing or recording purposes. re
turns a promise that resolves to a mediastream. getusermedia() with the user's permission through a prompt,
turns on a camera and/or a microphone on the system and provides a mediastream containing a video track and/or an audio track with the input. example 'use strict'; // put variables in global scope to make them available to the browser console. var video = document.queryselector('video'); v...
load() - Web APIs
specifications specification status comment encrypted media extensionsthe definition of 'load()' in that specification. ...
... specifications specification status comment encrypted media extensionsthe definition of 'load()' in that specification. ...
MediaKeyStatusMap.entries() - Web APIs
browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MediaList - Web APIs
the medialist interface represents the media queries of a stylesheet, e.g. those set using a <link> element's media attribute. note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document. properties medialist.mediatext a stringifier that re
turns a domstring representing the medialist as text, and also allows you to set a new medialist. ...
...esheet, e.g. those set using a <link> element's media attribute. note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document. properties medialist.mediatext a stringifier that re
turns a domstring representing the medialist as text, and also allows you to set a new medialist. medialist.length read only re
turns the number of media queries in the medialist. methods medialist.appendmedium() adds a media query to the medialist. medialist.deletemedium() removes a media query from the medialist. medialist.item() a getter that re
turns a cssomstring representing a media query as text, given the media query's index value inside the medialist. examples the following would log to the console a textu...
MediaRecorder.isTypeSupported - Web APIs
recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. ...
...recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. ...
MediaRecorderErrorEvent.error - Web APIs
on, if it exists. securityerror the mediastream is configured to disallow recording. this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. example this function creates and re
turns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors. function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { /* exception while trying to create the recorder; handle that */ } recorder.ondataavailable = function(event) { bufferlist.push(even...
... working draft initial specification. ...
MediaRecorderErrorEvent - Web APIs
methods inherits methods from its parent interface, event. ...
... methods inherits methods from its parent interface, event. specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent' in that specification. ...
MediaSource.setLiveSeekableRange() - Web APIs
the setliveseekablerange() method of the mediasource interface sets the range that the user can seek to in the media element. syntax mediasource.setliveseekablerange(start, end) parameters start the start of the seekable range to set in seconds measured from the beginning of the source. ...
...eginning of the source. if the duration of the media source is positive infinity, then the timeranges object re
turned by the htmlmediaelement.seekable property will have a start timestamp no greater than this value. end the end of the seekable range to set in seconds measured from the beginning of the source. if the duration of the media source is positive infinity, then the timeranges object re
turned by the htmlmediaelement.seekable property will have an end timestamp no less than this value. re
turn value undefined example // tbd specifications specification status comment media source extensionsthe definition of 'setliveseekablerange()' in that specification. recommendation initial definition. ...
MediaStream.ended - Web APIs
specifications no longer part of any specification. ...
...stream has not been reached. this value once the ended event has been fired. this property has been removed from the specification; you should instead rely on the ended event or check the value of mediastreamtrack.readystate to see if its value is "ended" for the track or tracks you want to ensure have finished playing. syntax var hasended = mediastream.ended; value a boolean value that re
turns true if the end of the stream has been reached. specifications no longer part of any specification. this property was part of earlier drafts of the media capture and streams specification. ...
MediaStream.getVideoTracks() - Web APIs
video tracks are those tracks whose kind property is video. the array is empty if the stream contains no video tracks. note: the order of the tracks is not defined by the specification, and may not be the same from one call to getvideotracks() to another. ...
...cted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor. var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); re
turn imagecapture.getphotocapabilities(); }) specifications specification status comment media capture and streamsthe definition of 'getvideotracks()' in that specification. candidate recommendation initial definition. ...
MediaStreamAudioSourceNode() - Web APIs
note: another way to create a mediastreamaudiosourcenode is to call theaudiocontext.createmediastreamsource() method, specifying the stream from which you want to obtain audio. syntax audiosourcenode = new mediastreamaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. ...
... mediastreamaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamaudiosourceoptions object defining the properties you want the mediastreamaudiosourcenode to have: mediastream a required property which specifies the mediastream from which to obtain audio for the node. re
turn value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. exceptions invalidstateerror the specified mediastream doesn't have any audio tracks. examples this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from its mediastream. // define variables va...
MediaStreamConstraints.audio - Web APIs
the mediastreamconstraints dictionary's audio property is used to indicate what kind of audio track, if any, should be included in the mediastream re
turned by a call to getusermedia(). to learn more about how constraints work, see capabilities, constraints, and settings. syntax var audioconstraints = true | false | mediatrackconstraints; value the value of the audio property can be specified as either of two types: boolean if a boolean value is specified, it simply indicates whether or not an audio track should be included in the re
turned stream; if it's true, an audio track is included; if no audio source is available or if permission is not given to use the audio source, the call to getusermedia() will fail. if false, no audio track is included. mediatrackconstraints a constr...
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <audio id="audio" autoplay controls></audio><br> <div id="log"></div> css content body { font: 1...
MediaStreamConstraints.video - Web APIs
the mediastreamconstraints dictionary's video property is used to indicate what kind of video track, if any, should be included in the mediastream re
turned by a call to getusermedia(). to learn more about how constraints work, see capabilities, constraints, and settings. syntax var videoconstraints = true | false | mediatrackconstraints; value the value of the video property can be specified as either of two types: boolean if a boolean value is specified, it simply indicates whether or not a video track should be included in the re
turned stream; if it's true, a video track is included; if no video source is available or if permission is not given to use the video source, the call to getusermedia() will fail. if false, no video track is included. mediatrackconstraints a constrai...
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <video id="video" width="160" height="120" autoplay></video><br> <div id="log"></div> css content ...
MediaStreamConstraints - Web APIs
the mediastreamconstraints dictionary is used when calling getusermedia() to specify what kinds of tracks should be included in the re
turned mediastream, and, optionally, to establish constraints for those tracks' settings. to learn more about how constraints work, see capabilities, constraints, and settings. properties some combination—but not necessarily all—of the following properties will exist on the object. track constraints audio either a boolean (which indicates whether or not an audio track is requested) or a mediatrackconstraints object providing the constraints which must be met by the audio track included in the re
turned mediastream. if constraints are specified, an audio track is inherently requested. video either a boolean (which indicates whether or not a video tr...
...if constraints are specified, a video track is inherently requested. security peeridentity a domstring identifying the peer who has sole access to the stream. if this property is specified, only the indicated peer can receive and use the stream. ...
MediaStreamTrackAudioSourceNode() - Web APIs
another way to create a mediastreamtrackaudiosourcenode is to call theaudiocontext.createmediastreamtracksource() method, specifying the mediastreamtrack from which you want to obtain audio. syntax audiotracknode = new mediastreamtrackaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. ...
...ediastreamtrackaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with. options a mediastreamtrackaudiosourceoptions object defining the properties you want the mediastreamtrackaudiosourcenode to have: mediastreamtrack the mediastreamtrack from which to take audio data for this node's output. re
turn value a new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track. exceptions notsupportederror the specified context is not an audiocontext. invalidstateerror the specified mediastreamtrack isn't an audio track (that is, its kind property isn't audio. example this example uses getusermedia() to obtain access to the us...
MediaStream Image Capture API - Web APIs
usage the process of retrieving an image or video stream happens as described below. the example code is adapted from chrome's image capture examples. first, get a reference to a device by calling mediadevices.getusermedia(). the example below simply says give me whatever video device is available, though the getusermedia() method allows more specific capabilities to be requested. this method re
turns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. }) next, isolate the visual part of the media stream. do this by calling mediastream.getvideotracks(). this re
turns an array of mediastreamtrack objects. the code below assumes that the first item in the mediastreamtrack array ...
... const track = mediastream.getvideotracks()[0]; at this point, you might want to configure the device capabilities before capturing an image. you can do this by calling applyconstraints() on the track object before doing anything else. let zoom = document.queryselector('#zoom'); const capabilities = track.getcapabilities(); // check whether zoom is supported or not. if(!capabilities.zoom) { re
turn; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the imagecapture() constructor. though a mediastream holds several types of tracks and provides multiple methods for retrieving them, the imagecapture constructor will throw a domexception of type notsupportederror if mediastreamtrack.kind is not "video". let imagecapture = new imagec...
Using the MediaStream Recording API - Web APIs
to some events. first of all, mediarecorder.start() is used to start recording the stream once the record button is pressed: record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; } when the mediarecorder is recording, the mediarecorder.state property will re
turn a value of "recording". as recording progresses, we need to collect the audio data. we register an event handler to do this using mediarecorder.ondataavailable: let chunks = []; mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } note: the browser will fire dataavailable events as needed, but if you want to intervene you can also include a timeslice when invoking the start...
...top(); console.log(mediarecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; } note that the recording may also stop naturally if the media stream ends (e.g. if you were grabbing a song track and the track ended, or the user stopped sharing their microphone). grabbing and using the blob when recording has stopped, the state property re
turns a value of "inactive", and a stop event is fired. we register an event handler for this using mediarecorder.onstop, and finalize our blob there from all the chunks we have received: mediarecorder.onstop = function(e) { console.log("recorder stopped"); const clipname = prompt('enter a name for your sound clip'); const clipcontainer = document.createelement('article'); const cliplabel =...
MediaTrackConstraints.deviceId - Web APIs
the mediatrackconstraints dictionary's deviceid property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the deviceid constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.deviceid as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var constraintsobject = { deviceid: constraint }; constraintsobject.deviceid = constraint; value an object based on constraindomstring specifying on...
...ceptable as the source of media content. device ids are unique for a given origin, and are guaranteed to be the same across browsing sessions on the same origin. however, the value of the deviceid is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of guid is recommended). that means that a given track will only re
turn one value for the deviceid when you call getcapabilities(). because of this, there's no use for the device id when calling mediastreamtrack.applyconstraints(), since there is only one possible value; however, you can record a deviceid and use it to ensure that you get the same source for multiple calls to getusermedia(). an exception to the rule that device ids are the same across browsing ses...
MediaTrackConstraints.displaySurface - Web APIs
ing the requested or mandatory constraints placed upon the value of the displaysurface constrainable property. this is used to specify the type or types of display surfaces which getdisplaymedia() will let the user select among for sharing purposes. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.displaysurface as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { displaysurface: constraint }; constraintsobject.displaysurface = constraint; value a constraindomstring which specifies the type of display surface that's being captured. this value does not ...
...ources in the browser's user interface. see how constraints are defined in capabilities, constraints, and settings for an explanation of how to define constraints. usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the re
turned mediatracksettings object's displaysurface object. for example, if your app needs to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || di...
MediaTrackConstraints.groupId - Web APIs
the mediatrackconstraints dictionary's groupid property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the groupid constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.groupid as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { groupid: constraint }; constraintsobject.groupid = constraint; value an object based on constraindomstring specifying one or more acceptable, ideal, and/or exact (mandatory) group ids which are acceptable as the source of media content. group ids are uniq...
...at the audio and input devices are on the same headset by retrieving the group id of the input device and specifying it when asking for an output device, perhaps. however, the value of the groupid is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of guid is recommended). that means that a given track will only re
turn one value for the groupid when you call getcapabilities(), and keep in mind that this value will change for each browsing session. because of this, there's no use for the group id when calling mediastreamtrack.applyconstraints(), since there is only one possible value, and you can't use it to ensure the same group is used across multiple browsing sessions when calling getusermedia(). example s...
MediaTrackConstraints.logicalSurface - Web APIs
playmedia() should allow the user to choose display surfaces which are not necessarily fully visible on the screen, such as occluded windows or the complete content of windows which are large enough to require scrolling to see their entire contents. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.logicalsurface as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { logicalsurface: constraint }; constraintsobject.logicalsurface = constraint; value a constrainboolean which is true if logical surfaces should be permitted among the selections available to t...
...g the selections available to the user. see how constraints are defined in capabilities, constraints, and settings for an explanation of how to define constraints. usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the re
turned mediatracksettings object's logicalsurface object. for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, o...
MediaTrackSettings.deviceId - Web APIs
nding to the browsing session. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.deviceid property you provided when calling either getusermedia(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.deviceid as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var deviceid = mediatracksettings.deviceid; value a domstring whose value is an origin-...
...sions, for example. the actual value of the string, however, is determined by the source of the track, and there is no guarantee what form it will take, although the specification does recommend it be a guid. since there is a one-to-one pairing of id with each source, all tracks with the same source will share the same id for any given origin, so mediastreamtrack.getcapabilities() will always re
turn exactly one value for deviceid. that makes the device id not useful for any changes to constraints when calling mediastreamtrack.applyconstraints(). an exception to the rule that device ids are the same across browsing sessions: private browsing mode will use a different id, and will change it each browsing session. example see example: constraint exerciser in capabilities, constraints, and ...
Media Source API - Web APIs
a media source to be played via an htmlmediaelement object. sourcebuffer represents a chunk of media to be passed into an htmlmediaelement via a mediasource object. sourcebufferlist a simple container list for multiple sourcebuffer objects. videoplaybackquality contains information about the quality of video being played by a <video> element, such as number of dropped or corrupted frames. re
turned by the htmlvideoelement.getvideoplaybackquality() method. trackdefault provides a sourcebuffer with kind, label, and language information for tracks that do not contain this information in the initialization segments of a media chunk. trackdefaultlist a simple container list for multiple trackdefault objects. extensions to other interfaces url.createobjecturl() creates an object url p...
...nk. trackdefaultlist a simple container list for multiple trackdefault objects. extensions to other interfaces url.createobjecturl() creates an object url pointing to a mediasource object that can then be specified as the src value of an html media element to play a media stream. htmlmediaelement.seekable when a mediasource object is played by an html media element, this property will re
turn a timeranges object that contains the time ranges that the user is able to seek to. htmlvideoelement.getvideoplaybackquality() re
turns a videoplaybackquality object for the currently played video. audiotrack.sourcebuffer, videotrack.sourcebuffer, texttrack.sourcebuffer re
turns the sourcebuffer that created the track in question. specifications specification status comment ...
MimeType - Web APIs
the mimetype interface provides contains information about a mime type associated with a particular plugin. navigatorplugins.mimetypes re
turns an array of this object. properties mimetype.type re
turns the mime type of the associated plugin. mimetype.description re
turns a description of the associated plugin or an empty string if there is none. mimetype.suffixes a string containing valid file extensions for the data displayed by the plugin, or an empty string if an extension is not valid for the particular module. ...
...on of the associated plugin or an empty string if there is none. mimetype.suffixes a string containing valid file extensions for the data displayed by the plugin, or an empty string if an extension is not valid for the particular module. for example, a browser's content decryption module may appear in the plugin list but support more file extensions than can be anticipated. it might therefore re
turn an empty string. mimetype.enabledplugin re
turns an instance of plugin containing information about the plugin itself. specifications specification status comment html living standardthe definition of 'mimetype' in that specification. living standard initial definition. ...
MouseEvent.button - Web APIs
ero, it may not have been caused by the button that is physically left–most on the pointing device; however, it should behave as if the left button was clicked in the standard button layout. note: do not confuse this property with the mouseevent.buttons property, which indicates which buttons are pressed for all mouse events types. ...
... document object model (dom) level 2 events specificationthe definition of 'mouseevent.button' in that specification. obsolete initial definition. ...
MouseEvent.getModifierState() - Web APIs
the value must be one of the keyboardevent.key values which represent modifier keys or "accel". this is case-sensitive. ...
...the value must be one of the keyboardevent.key values which represent modifier keys or "accel". this is case-sensitive. ...
MouseEvent.pageX - Web APIs
originally, this property was defined as a long integer. the cssom view module redefined it as a double float. ...
...ocument. this includes any portion of the document not currently visible. being based on the edge of the document as it is, this property takes into account any horizontal scrolling of the page. for example, if the page is scrolled such that 200 pixels of the left side of the document are scrolled out of view, and the mouse is clicked 100 pixels inward from the left edge of the view, the value re
turned by pagex will be 300. originally, this property was defined as a long integer. the cssom view module redefined it as a double float. see the browser compatibility section for details. see page in coordinate systems for some additional information about coordinates specified in this fashion. syntax var pagex = mouseevent.pagex; value a floating-point number of pixels from the left edge of ...
MouseEvent.relatedTarget - Web APIs
example try moving your mouse cursor into and out of the red and blue boxes. html <body id="body"> <div id="outer"> <div id="red"></div> <div id="blue"></div> </div> <p id="log"></p> </body> css #outer ...
... example try moving your mouse cursor into and out of the red and blue boxes. ...
MutationObserver.MutationObserver() - Web APIs
the dom mutationobserver() constructor — part of the mutationobserver interface — creates and re
turns a new observer which invokes a specified callback when dom events occur. dom observation does not begin immediately; the observe() method must be called first to establish which portion of the dom to watch and what kinds of changes to watch for. syntax const observer = new mutationobserver(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. ...
...er(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options. the callback function takes as input two parameters: an array of mutationrecord objects, describing each change that occurred; and the mutationobserver which invoked the callback. see the example below for more details. re
turn value a new mutationobserver object, configured to call the specified callback when dom mutations occur. example this example simply creates a new mutationobserver configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree. the callback function function callback(mutationlist, ...
MutationObserver - Web APIs
the mutationobserver interface provides the ability to watch for changes being made to the dom tree. it is designed as a replacement for the older mutation events feature, which was part of the dom3 events specification. constructor mutationobserver() creates and re
turns a new mutationobserver which will invoke a specified callback function when dom changes occur. methods disconnect() stops the mutationobserver instance from receiving further notifications until and unless observe() is called again. ...
...hods disconnect() stops the mutationobserver instance from receiving further notifications until and unless observe() is called again. observe() configures the mutationobserver to begin receiving notifications through its callback function when dom changes matching the given options occur. takerecords() removes all pending notifications from the mutationobserver's notification queue and re
turns them in a new array of mutationrecord objects. mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post. // select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config ...
NavigationPreloadManager - Web APIs
the navigationpreloadmanager interface of the the service worker api provides methods for managing the preloading of resources with a service worker. methods navigationpreloadmanager.enable() enables navigation preloading and re
turns a promise that resolves. navigationpreloadmanager.disable() disables navigation preloading and re
turns a promise that resolves. navigationpreloadmanager.setheadervalue() sets the value of the service-worker-navigation-preload header and re
turns an empty promise. navigationpreloadmanager.getstate() re
turns a promise that resolves to an object with properties indicating whether preload is enabled and the contents of the service-worker-navigation-preload. examples feature detecting and enabling navigation preloading addeventlistener('activate', event...
...ait 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) re
turn cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) re
turn response; // else try the network. re
turn fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'navigationpreloadmanager' in that specification. working dra...
Using Navigation Timing - Web APIs
e at a level of accuracy much improved over other techniques. it also offers the advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object re
turned. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which th...
...ncetiming into the correct perspective, you need to know more about what sort of load operation occurred. in particular, you need to know: was this a load or a reload? was this a navigation or a move forward or backward through history? how many (if any) redirects were required in order to complete the navigation? this information is provided by the performance.navigation property, which re
turns a performancenavigation object that includes the needed information. let's add this information to the example above. the new code looks like this: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; output = "load time: " + loadingtime + " ms<br/>"; output += "navigation type: "; switch(performanc...
Navigator.canShare() - Web APIs
true if data can be shared with navigator.share(). exceptions none. ...
...true if data can be shared with navigator.share(). exceptions none. ...
Navigator.clipboard - Web APIs
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. ...
...aces the contents of the element whose class is "cliptext" with the text contents of the clipboard. perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire. if the clipboard is empty or doesn't contain text, the "cliptext" element's contents are cleared. this happens because readtext() re
turns an empty string if the clipboard is empty or doesn't contain text. specifications specification status comment clipboard api and eventsthe definition of 'navigator.clipboard' in that specification. working draft initial definition. ...
Navigator.getBattery() - Web APIs
the getbattery() method provides information about the system's battery. it re
turns a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); re
turn value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. ...
...ccess to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); re
turn value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. exceptions this method doesn't throw true exceptions; instead, it rejects the re
turned promise, passing into it a domexception whose name is one of the following: securityerror the user agent does not expose battery information to insecure contexts and this method was called from insecure context. note: old versions of some user agents might allow use of this feature in insecure contexts. notallowederror note: no user agent currently throws this exception, but the specific...
Navigator.getUserMedia() - Web APIs
back is executed with a mediastreamerror object describing what went wrong. if the user instead doesn't make a choice at all, neither callback is executed. this is a legacy method. please use the newer navigator.mediadevices.getusermedia() instead. while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise re
turning version. syntax navigator.getusermedia(constraints, successcallback, errorcallback); parameters constraints a mediastreamconstraints object specifying the types of media to request, along with any requirements for each type. for details, see the constraints section under the modern mediadevices.getusermedia() method, as well as the article capabilities, constraints, and settings. succ...
...ctor('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anch("errors")}} below for a list of the errors which can occur. re
turn value undefined. errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes. note that this is the deprecated way of doing it: see the examples section under the mediadevices.getusermedia() for modern examples. navigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || ...
Navigator.mediaSession - Web APIs
in addition, the mediasession interface provides the setactionhandler() method, which lets you receive events when the user engages device controls such as either onscreen or physical play, pause, seek, and other similar controls. ...
... in addition, the mediasession interface provides the setactionhandler() method, which lets you receive events when the user engages device controls such as either onscreen or physical play, pause, seek, and other similar controls. ...
navigator.hardwareConcurrency - Web APIs
syntax logicalprocessors = window.navigator.hardwareconcurrency value a number indicating the number of logical processor cores. modern computers have multiple physical processor cores in their cpu (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. so a four-core cpu may offer eight logical processor cores, for example. ...
... of workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system. examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in
turn, stored into an array for later use. this creates a pool of workers we can use to process requests later. let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let newworker = { worker: new worker('cpuworker.js'), inuse: false }; workerlist.push(newworker); } specification specification status comment html living standardth...
NavigatorID.appCodeName - Web APIs
syntax codename = navigator.appcodename value the string "mozilla". ...
... syntax codename = navigator.appcodename value the string "mozilla". ...
NavigatorID.appName - Web APIs
syntax appname = navigator.appname value the string "netscape". ...
... syntax appname = navigator.appname value the string "netscape". ...
NavigatorID.appVersion - Web APIs
syntax window.navigator.appversion value either "4.0" or a string representing version information about the browser. example alert('your browser version is reported as ' + navigator.appversion); notes the window.navigator.useragent property may also contain the version number (for example "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape 6/6.1"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties. ...
...s, or user agents, and also how cavalier the browser vendor themselves are with these properties. the window.navigator.appversion, window.navigator.appname and window.navigator.useragent properties have been used in "browser sniffing" code: scripts that attempt to find out what kind of browser you are using and adjust pages accordingly. this lead to the current situation, where browsers had to re
turn fake values from these properties in order not to be locked out of some websites. specifications specification status comment html living standardthe definition of 'navigatorid.appversion' in that specification. living standard initial definition ...
NavigatorID.product - Web APIs
syntax productname = navigator.product value the string "gecko". ...
... syntax productname = navigator.product value the string "gecko". ...
NavigatorLanguage.languages - Web APIs
when its value changes, as the user's preferred languages are changed a languagechange event is fired on the window object. the accept-language http header in every http request from the user's browser uses the same value for the navigator.languages property except for the extra qvalues (quality values) field (e.g. en-us;q=0.8). ...
... when its value changes, as the user's preferred languages are changed a languagechange event is fired on the window object. the accept-language http header in every http request from the user's browser uses the same value for the navigator.languages property except for the extra qvalues (quality values) field (e.g. en-us;q=0.8). ...
Online and offline events - Web APIs
effectively, the requirements break down as such: you need to know when the user comes back online, so that you can re-synchronize with the server. ...
... maintains a true/false value (true for online, false for offline). this property is updated whenever the user switches into "offline mode" by selecting the corresponding menu item (file -> work offline in firefox). additionally, this property should update whenever a browser is no longer capable of connecting to the network. according to the specification: the navigator.online attribute must re
turn false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)... firefox 2 updates this property when switching to/from the browser's offline mode. firefox 41 updates this property when the os reports a change in network connectivity on windows, linux, and os x. this property existed in older v...
Navigator.onLine - Web APIs
re
turns the online status of the browser. the property re
turns a boolean value, with true meaning online and false meaning offline. the property sends updates whenever the browser's ability to connect to the network changes. the update occurs when the user follows links or when a script requests a remote page. for example, the property should re
turn false when users click links soon after they lose internet connection. browsers implement this property differently. in chrome and safari, if the browser is not able to connect to a local area network (lan) or a router, it is offline; all other conditions re
turn true. so while you can assume that the browser is offline when it re
turns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. y...
...ftware that has virtual ethernet adapters that are always "connected." therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. to learn more, see the html5 rocks article, working off the grid. in firefox and internet explorer, switching the browser to offline mode sends a false value. until firefox 41, all other conditions re
turn a true value; testing actual behavior on nightly 68 on windows shows that it only looks for lan connection like chrome and safari giving false positives. you can see changes in the network state by listening for the events on window.ononline and window.onoffline. syntax online = window.navigator.online; value online is a boolean true or false. example view a live example. to check if yo...
NetworkInformation.downlinkMax - Web APIs
examples the following example monitors the connection using the change event and logs changes as they occur. ...
... examples the following example monitors the connection using the change event and logs changes as they occur. ...
Node.appendChild() - Web APIs
y kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. newer api avaliable! the parentnode.append() method supports multiple arguments and appending strings. syntax element.appendchild(achild) parameters achild the node to append to the given parent node (commonly an element). ...
...f the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. newer api avaliable! the parentnode.append() method supports multiple arguments and appending strings. syntax element.appendchild(achild) parameters achild the node to append to the given parent node (commonly an element). re
turn value the re
turned value is the appended child (achild), except when achild is a documentfragment, in which case the empty documentfragment is re
turned. notes chaining may not work as expected, due to appendchild() re
turning the child element: let ablock = document.createelement('block').appendchild( document.createelement('b') ); sets ablock to <b></b> only, which is probably not what you want. example // ...
Node.baseURI - Web APIs
the base url is used to resolve relative urls when the browser needs to obtain an absolute url, for example when processing the html <img> element's src attribute or xml xlink:href attribute. in most cases the base url is simply the location of the document, but it can be affected by many factors, including the <base> element in html and the xml:base attribute in xml. syntax var nodebaseuri = node.baseuri; value a domstring representing the base url of the specified node. it may be null if unable to obtain an absolute uri. although this property is read-only, its value may change in certain situations (see below). ...
...he document's address (as displayed by the browser and available in window.location), but it can be changed: when an html <base> tag is found in the document when the document is new (created dynamically) see the base urls section of the html living standard for details. you can use document.baseuri to obtain the base url of a document. note that obtaining the base url for a document may re
turn different urls over time if the <base> tags or the document's location change. the base url of an element the base url of an element in html normally equals the base url of the document the node is in. if the document contains xml:base attributes (which you shouldn't do in html documents), the element.baseuri takes the xml:base attributes of element's parents into account when computing the ba...
Node.compareDocumentPosition() - Web APIs
the node.comparedocumentposition() method reports the position of the given node relative to another node in any document — not just the given node’s document. the re
turn value is a bitmask of the following values: name value document_position_disconnected 1 document_position_preceding 2 document_position_following 4 document_position_contains 8 document_position_contained_by 16 document_position_implementation_specific 32 syntax comparemask = node.comparedocumentposition(othernode) parameters othernode the other node with which to compare the first node’s document position. re
turn value an integer value whose bits represent the othernode's relationship to the calling node. more t...
...ed, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a). example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.error('<head> is not before <body>'); } note: because the result re
turned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results. specifications specification status comment domthe definition of 'node.comparedocumentposition()' in that specification. living standard document object model (dom) level 3 core specificationthe definition of 'node.comparedocumentposition()' in that...
Node.firstChild - Web APIs
the node.firstchild read-only property re
turns the node's first child in the tree, or null if the node has no children. if the node is a document, it re
turns the first node in the list of its direct children. syntax var childnode = node.firstchild; example this example demonstrates the use of firstchild and how whitespace nodes might interfere with using this property. <p id="para-01"> <span>first span</span> </p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodename); </script> in the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags. any whitespace will create a #text node, from a single space to multiple spaces, re
turns, tabs, and so on. anoth...
...losing </span> and </p>tags. if this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child. <p id="para-01"><span>first span</span></p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodename); </script> now the console will show 'span'. to avoid the issue with node.firstchild re
turning #text or #comment nodes, parentnode.firstelementchild can be used to re
turn only the first element node. however, node.firstelementchild requires a shim for internet explorer 9 and earlier. specifications specification status comment domthe definition of 'node.firstchild' in that specification. living standard no change document object model (dom) l...
Node.getRootNode() - Web APIs
the getrootnode() method of the node interface re
turns the context object's root, which optionally includes the shadow root if it is available. syntax var root = node.getrootnode(options); parameters options optional an object that sets options for getting the root node. the available options are: composed: a boolean that indicates whether the shadow root should be re
turned (false, the default), or a root node beyond shadow root (true). re
turns an object inheriting from node. this will differ in exact form depending on where you called getrootnode(); for example: calling it on an element inside a standard web page will re
turn an htmldocument object representing the entire page. calling it on an element inside a shadow dom will re
turn the associated shadowroot. examples...
...shadow root (true). re
turns an object inheriting from node. this will differ in exact form depending on where you called getrootnode(); for example: calling it on an element inside a standard web page will re
turn an htmldocument object representing the entire page. calling it on an element inside a shadow dom will re
turn the associated shadowroot. examples the first simple example re
turns a reference to the html/document node: rootnode = node.getrootnode(); this more complex example shows the difference between re
turning a normal root, and a root incuding the shadow root. (see the full source code): <!-- source: https://github.com/jserz/js_piece/blob/master/dom/node/getrootnode()/demo/getrootnode.html --> <div class="js-parent"> <div class="js-child"></div> </div> <div class...
Node.hasChildNodes() - Web APIs
the node.haschildnodes() method re
turns a boolean value indicating whether the given node has child nodes or not. syntax bool = node.haschildnodes(); re
turn value a boolean that is true if the node has child nodes, and false otherwise. ...
...s or not. syntax bool = node.haschildnodes(); re
turn value a boolean that is true if the node has child nodes, and false otherwise. ...
Node.insertBefore() - Web APIs
he newly inserted node. newnode the node to be inserted. referencenode the node before which newnode is inserted. if this is null, then newnode is inserted at the end of parentnode's child nodes. note: referencenode is not an optional parameter. you must explicitly pass a node or null. failing to provide it or passing invalid values may behave differently in different browser versions. re
turn value re
turns the added child (unless newnode is a documentfragment, in which case the empty documentfragment is re
turned). example example 1 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create the new node to insert let newnode = document.createelement("span") // get a reference to the parent node let parentdiv = document.getelementbyid("childelemen...
...the new element into before sp2 parentdiv.insertbefore(sp1, sp2) </script> note: there is no insertafter() method. it can be emulated by combining the insertbefore method with node.nextsibling. in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling re
turns null, and sp1 is inserted at the end of the child node list (immediately after sp2). example 3 insert an element before the first child element, using the firstchild property. // get the parent element let parentelement = document.getelementbyid('parentelement') // get the parent's first child let thefirstchild = parentelement.firstchild // create a new element let newelement = document.crea...
Node.nodeName - Web APIs
syntax var str = node.nodename; value a domstring. ...
...iven the following markup: <div id="d1">hello world</div> <input type="text" id="t"> and the following script: var div1 = document.getelementbyid("d1"); var text_field = document.getelementbyid("t"); text_field.value = div1.nodename; in xhtml (or any other xml format), text_field's value would read "div". however, in html, text_field's value would read "div", because nodename and tagname re
turn in upper case on html elements in doms flagged as html documents. read more details on nodename case sensitivity in different browsers. note that the element.tagname property could have been used instead, since nodename has the same value as tagname for an element. bear in mind, however, that nodename will re
turn "#text" for text nodes while tagname will re
turn undefined. specifications ...
Node.nodeValue - Web APIs
the nodevalue property of the node interface re
turns or sets the value of the current node. syntax str = node.nodevalue; node.nodevalue = str; value str is a string containing the value of the current node, if any. for the document itself, nodevalue re
turns null. for text, comment, and cdata nodes, nodevalue re
turns the content of the node. for attribute nodes, the value of the attribute is re
turned. ...
...ce re
turns or sets the value of the current node. syntax str = node.nodevalue; node.nodevalue = str; value str is a string containing the value of the current node, if any. for the document itself, nodevalue re
turns null. for text, comment, and cdata nodes, nodevalue re
turns the content of the node. for attribute nodes, the value of the attribute is re
turned. ...
NodeIterator.expandEntityReferences - Web APIs
the nodeiterator.expandentityreferences read-only property re
turns a boolean flag indicating whether or not the children of entity reference nodes are visible to the nodeiterator. if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the nodeiterator.whattoshow method and the associated filter. ...
...false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the nodeiterator.whattoshow method and the associated filter. syntax expand = nodeiterator.expandentityreferences; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); expand = nodeiterator.expandentityreferences; specifications specification status comment document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator.expandentityreferences' in that specification. obsolete initial definition. ...
NodeIterator.filter - Web APIs
the nodeiterator.filter read-only method re
turns a nodefilter object, that is an object implement an acceptnode(node) method, used to screen nodes. when creating the nodeiterator, the filter object is passed in as the third parameter, and the object method acceptnode(node) is called on every single node to determine whether or not to accept it. this function should re
turn the constant nodefilter.filter_accept for cases when the node should be accepted and nodefilter.filter_reject for cases when the node should be rejected. ...
... living standard no change from document object model (dom) level 2 traversal and range specification. ...
NodeIterator.nextNode() - Web APIs
the nodeiterator.nextnode() method re
turns the next node in the set represented by the nodeiterator and advances the position of the iterator within the set. the first call to nextnode() re
turns the first node in the set. this method re
turns null when there are no nodes left in the set. in old browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is called after the nodeiterator.detach()method. recent browsers never throw. ...
...ld browsers, as specified in old versions of the specifications, the method may throws the invalid_state_err domexception if this method is called after the nodeiterator.detach()method. recent browsers never throw. syntax node = nodeiterator.nextnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // re
turns the next node specifications specification status comment domthe definition of 'nodeiterator.nextnode' in that specification. living standard as detach() is now a no-op method, this method cannot throw anymore. docum...
NodeIterator.whatToShow - Web APIs
syntax var nodetypes = nodeiterator.whattoshow; the values that can be combined to form the bitmask are: constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. nodefilter.show_attribute 2 shows attribute attr nodes. ...
...do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); if( (nodeiterator.whattoshow == nodefilter.show_all) || (nodeiterator.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // nodeiterator will show comments } specifications specification status comment domthe definition of 'nodeiterator.whattoshow' in that specification. living standard no ch...
NodeList.item() - Web APIs
re
turns a node from a nodelist by index. this method doesn't throw exceptions as long as you provide arguments. a value of null is re
turned if the index is out of range, and a typeerror is thrown if no argument is provided. syntax nodeitem = nodelist.item(index) nodelist is a nodelist. this is usually obtained from another dom property or method, such as childnodes. index is the index of the node to be fetched. the index is zero-based. nodeitem is the indexth node in the nodelist re
turned by the item method. ...
...f the node to be fetched. the index is zero-based. nodeitem is the indexth node in the nodelist re
turned by the item method. alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - re
turns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that specification. living standard ...
Notification.data - Web APIs
note: this feature is available in web workers. the data read-only property of the notification interface re
turns a structured clone of the notification's data, as specified in the data option of the notification() constructor. the notification's data can be any arbitrary data that you want associated with the notification. syntax var data = notification.data; value a structured clone. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. ...
...ication. syntax var data = notification.data; value a structured clone. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', data: 'i like peas.' } var n = new notification('test notification',options); console.log(n.data) // should re
turn 'i like peas.' specifications specification status comment notifications apithe definition of 'data' in that specification. living standard living standard ...
OES_vertex_array_object.isVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... ...
... examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... ...
OfflineAudioContext.OfflineAudioContext() - Web APIs
syntax var offlineaudioctx = new offlineaudiocontext(numberofchannels, length, samplerate); var offlineaudioctx = new offlineaudiocontext(options); parameters you can specify the parameters for the offlineaudiocontext() constructor as either the same set of parameters as are inputs into the audiocontext.createbuffer() method, or by passing those parameters in an options object. either way, the individual parameters are the same. ...
... new audiocontext using the new audiocontext() constructor with no arguments, the offlineaudiocontext() constructor requires three arguments, since it needs to create an audiobuffer. this works in exactly the same way as when you create a new audiobuffer with the audiocontext.createbuffer() method. for more detail, read audio buffers: frames, samples and channels from our basic concepts guide. re
turn value a new offlineaudiocontext object whose associated audiobuffer is configured as requested. like a regular audiocontext, an offlineaudiocontext can be the target of events, therefore it implements the eventtarget interface. example const offlinectx = new offlineaudiocontext({ numberofchannels: 2, length: 44100 * 40, samplerate: 44100, }); const source = offlinectx.createbuffersource...
OfflineAudioContext.startRendering() - Web APIs
will eventually be removed, but currently both mechanisms are provided for legacy reasons. syntax event-based version: offlineaudioctx.startrendering(); offlineaudioctx.oncomplete = function(e) { // e.renderedbuffer contains the output buffer } promise-based version: offlineaudioctx.startrendering().then(function(buffer) { // buffer contains the output buffer }); parameters none. re
turns void. example in this simple example, we declare both an audiocontext and an offlineaudiocontext object. we use the audiocontext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through. after the offline audio graph is set up, you need to render it to an audiobuffer using offlineau...
...ntext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through. after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering. when the startrendering() promise resolves, rendering has completed and the output audiobuffer is re
turned out of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioct...
OfflineAudioContext.suspend() - Web APIs
this is generally useful at the time of manipulating the audio graph synchronously on offlineaudiocontext. note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. ...
...nded down to the nearest render quantum boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... }); parameters suspendtime a double specifying the suspend time, in seconds. re
turns a promise resolving to void. exceptions the promise is rejected when any exception is encountered. invalidstateerror if the quantized frame number is one of the following: a negative number is less than or equal to the current time is greater than or equal to the total render duration is scheduled by another suspend for the same time specifications specification status ...
OfflineAudioContext - Web APIs
when processing is terminated, that is when the complete event (of type offlineaudiocompletionevent) is raised, after the event-based version of offlineaudiocontext.startrendering() is used. methods also inherits methods from its parent interface, baseaudiocontext. offlineaudiocontext.suspend() schedules a suspension of the time progression in the audio context at the specified time and re
turns a promise. offlineaudiocontext.startrendering() starts rendering the audio, taking into account the current connections and the current scheduled changes. this page covers both the event-based version and the promise-based version. deprecated methods offlineaudiocontext.resume() resumes the progression of time in an audio context that has previously been suspended. note: the resume() ...
...ntext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through. after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering. when the startrendering() promise resolves, rendering has completed and the output audiobuffer is re
turned out of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioct...
OffscreenCanvas.getContext() - Web APIs
note: this api is currently implemented for webgl1 and webgl2 contexts only. see bug 801176 for canvas 2d api support from workers. syntax offscreen.getcontext(contexttype, contextattributes); parameters contexttype is a domstring containing the context identifier defining the drawing context associated to the canvas. possible values are: "2d" creates a canvasrenderingcontext2d object representing a two-dimensional rendering context. "webgl" creates a webglrenderingcontext object representing a three-dimensional rendering context. ...
...that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. failifmajorperformancecaveat: boolean that indicates if a context will be created if the system performance is low. re
turn value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" and "experimental-webgl2" , or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is re
turned. examples var offscreen = new offscreencanvas(256, 256...
ParentNode.append() - Web APIs
the parentnode.append() method inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. differences from node.appendchild(): parentnode.append() allows you to also append domstring objects, whereas node.appendchild() only accepts node objects. parentnode.append() has no re
turn value, whereas node.appendchild() re
turns the appended node object. parentnode.append() can append several nodes and strings, whereas node.appendchild() can only append one node. syntax // [throws, unscopable] parentnode.append(...nodesordomstrings) // re
turns undefined parameters nodes a set of node or domstring objects to insert. exceptions hierarchyrequesterror: node cannot be inserted at the specified point...
...nt.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { re
turn; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnod...
ParentNode.childElementCount - Web APIs
the parentnode.childelementcount read-only property re
turns an unsigned long representing the number of child elements of the given element. this property was initially defined in the elementtraversal pure interface. as this interface contained two distinct set of properties, one aimed at node that have children, one at those that are children, they have been moved into two separate pure interfaces, parentnode and childnode. in this case, childelementcount moved to parentnode. this is a fairly technical change that shouldn't affect compatibility. syntax var count = node.childelementcount; count the re
turn value, which is an unsigned long (simply an integer) type. node an object representing a document, documentfragment, or element. example var foo = document.getelementbyid('foo...
...jects. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.childelementcount == null) { object.defineproperty(constructor.prototype, 'childelementcount', { get: function() { var i = 0, count = 0, node, nodes = this.childnodes; while (node = nodes[i++]) { if (node.nodetype === 1) count++; } re
turn count; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.childelementcount' in that specification. living standard split the elementtraversal interface in childnode and parentnode. this method is now defined on the latter. the document and documentfragment implemented the new inte...
ParentNode.prepend() - Web APIs
cts or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. syntax parentnode.prepend(...nodestoprepend); parameters nodestoprepend one or more nodes to insert before the first child node currently in the parentnode. each node can be specified as either a node object or as a string; strings are inserted as new text nodes. re
turn value undefined. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. examples prepending an element var parent = document.createelement("div"); var p = document.createelement("p"); var span = document.createelement("span"); parent.append(p); parent.prepend(span); console.log(parent.childnodes); // nodelist [ <span>, <p> ] prepending text ...
...mation. ...
ParentNode.querySelector() - Web APIs
if you need all the elements matching the selector list, use queryselectorall() instead. note: this method is implemented as document.queryselector(), documentfragment.queryselector() and element.queryselector(). syntax element = parentnode.queryselector(selectors); parameters selectors a domstring containing one or more selectors to match against. this string must be a valid compound selector list supported by the browser; if it's not, a syntaxerror exception is thrown. ...
... using selectors to identify elements. multiple selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. re
turn value the first element that matches at least one of the specified selectors or null if no such element is found. note: if the specified selectors include a css pseudo-element, the re
turned value is always null. exceptions syntaxerror the syntax of the specified selectors string is not valid. specifications specification status comment domthe definition of ...
PaymentAddress.regionCode - Web APIs
syntax var regioncode = paymentaddress.regioncode; value a domstring indicating the one to three character alphanumeric code representing the region portion of the address. ...
...ng) representing the region of the address (e.g., "ca" for california, or "11" for lisbon, portugal). the code is derived from the iso 3166-2 standard, which defines codes for identifying the subdivisions (e.g., states, provinces, autonomous regions, etc.) of all countries in the world. if the browser can't determine the region code, or the country doesn't use regions for postal addresses, it re
turns an empty string. syntax var regioncode = paymentaddress.regioncode; value a domstring indicating the one to three character alphanumeric code representing the region portion of the address. this should correspond to region, but should be the iso 3166--2 standard's region code. the string is empty if the region code couldn't be determined, isn't needed for the address's country, or was not pr...
PaymentCurrencyAmount.value - Web APIs
specifications specification status comment payment request apithe definition of 'paymentcurrencyamount.value' in that specification. candidate recommendation ...
... specifications specification status comment payment request apithe definition of 'paymentcurrencyamount.value' in that specification. candidate recommendation ...
PaymentRequest.prototype.id - Web APIs
the id read-only attribute of the paymentrequest interface re
turns a unique identifier for a particular paymentrequest instance. when constructing an instance of the paymentrequest, you are able to supply an custom id via paymentdetailsinit dictionary's id member. if none is provided, the browser automatically sets the id value to a uuid. example this example shows how to give a paymentrequest instance a custom id. ...
.... example this example shows how to give a paymentrequest instance a custom id. const details = { id: "super-store-order-123-12312", total: { label: "total due", amount: { currency: "usd", value: "65.00" }, }, }; const request = new paymentrequest(methoddata, details); console.log(request.id); // super-store-order-123-12312 the id is then also available in the paymentresponse re
turned from the show() method, but under the requestid attribute. const response = await request.show(); console.log(response.requestid === request.id); // and in serialized form too const json = response.tojson(); console.log(json.requestid,response.requestid, request.id); syntax var id = paymentrequest.id value a domstring. specifications specification status comment ...
PaymentRequest: shippingaddresschange event - Web APIs
dress meets requirements set by the web application. ...
...t = new paymentrequest(methoddata, details, options); paymentrequest.addeventlistener("shippingaddresschange", event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupate); }, false); const checkaddress = theaddress => { let detailsupdate = {}; // check the address, re
turn a paymentdetailsupdate object // with any changes or errors. ...
PaymentRequest - Web APIs
e or the publisher of the app. constructor paymentrequest() secure context creates a new paymentrequest object. properties paymentrequest.id read only secure context an unique identifier for a particular paymentrequest, which can be set via details.id. when none is set, it defaults to a uuid. paymentrequest.shippingaddress read only secure context if requested via payment options, re
turns the shipping address chosen by the user for the purposes of calculating shipping. this property is only populated if the constructor is called with the requestshipping flag set to true. additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are ready to complete the transaction (i.e., they hit "pay"). paymentrequest.shippingoption rea...
...sen by the user for the purposes of calculating shipping. this property is only populated if the constructor is called with the requestshipping flag set to true. additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are ready to complete the transaction (i.e., they hit "pay"). paymentrequest.shippingoption read only secure context re
turns the identifier of the selected shipping option. this property is only populated if the constructor is called with the requestshipping flag set to true. paymentrequest.shippingtype read only secure context re
turns the type of shipping used to fulfill the transaction. this will be one of shipping, delivery, pickup, or null if a value was not provided in the constructor. methods paymentr...
PaymentResponse.complete() - Web APIs
syntax completepromise = paymentrequest.complete(result); parameters result optional a domstring indicating the state of the payment operation upon completion. ...
...ccess or failure status of the transaction is unknown or irrelevant, and the user agent should not present any notification, even if it normally would. this is the default value. note: in older versions of the specification, an empty string, "", was used instead of unknown to indicate a completion without a known result state. see the browser compatibility section below for details. re
turn value a promise which resolves with no input value once the payment interface has been fully closed. if an error occurs, the promise instead rejects, re
turning one of the exceptions listed below. exceptions aborterror the document in which the payment request is taking place became inactive while the user interface was shown. invalidstateerror the payment has already completed, or complet...
PaymentResponse.shippingOption - Web APIs
this option is only present when the requestshipping option is set to true in the paymentoptions object passed to the paymentrequest constructor. syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is called. it calls updatedetails() to toggle the shipping method between "standard" and "express". // initialization of paymentrequest arguments are excerpted for brevity. ...
... browser compatibility the compatibility table on this page is generated from s...
performance.getEntriesByType() - Web APIs
the getentriesbytype() method re
turns a list of performanceentry objects for a given type. the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time. note: this feature is available in web workers. syntax entries = window.performance.getentriesbytype(type); arguments type the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. re
turn value entries a list of performanceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is re
turned. example function useperformanceentrymethods() { ...
...nceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is re
turned. example function useperformanceentrymethods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... ...
PerformanceEntry.entryType - Web APIs
performance entry type names value subtype type of name property description of name property frame, navigation performanceframetiming, performancenavigationtiming url the document's address. resource performanceresourcetiming url the resolved url of the requested resource. ...
...rst-paint' or 'first-contentful-paint'. longtask performancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property. ...
PerformanceEntry.toJSON() - Web APIs
the tojson() method is a serializer; it re
turns a json representation of the performance entry object. note: this feature is available in web workers. syntax json = perfentry.tojson(); arguments none re
turn value json a json object that is the serialization of the performanceentry object. example the following example shows the use of the tojson() method. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
...kers. syntax json = perfentry.tojson(); arguments none re
turn value json a json object that is the serialization of the performanceentry object. example the following example shows the use of the tojson() method. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... ...
PerformanceEntry - Web APIs
s loading a resource (such as an image). performanceentry instances will always be one of the following subtypes: performancemark performancemeasure performanceframetiming performancenavigationtiming performanceresourcetiming performancepainttiming note: this feature is available in web workers. properties performanceentry.name read only a value that further specifies the value re
turned by the performanceentry.entrytype property. the value of both depends on the subtype. see property page for valid values. performanceentry.entrytype read only a domstring representing the type of performance metric such as, for example, "mark". see property page for valid values. performanceentry.starttime read only a domhighrestimestamp representing the starting time for the performance ...
...esenting the type of performance metric such as, for example, "mark". see property page for valid values. performanceentry.starttime read only a domhighrestimestamp representing the starting time for the performance metric. performanceentry.duration read only a domhighrestimestamp representing the time value of the duration of the performance event. methods performanceentry.tojson() re
turns a json representation of the performanceentry object. example the following example checks all performanceentry properties to see if the browser supports them and if so, write their values to the console. function print_performanceentries() { // use getentries() to get a list of all performance entries var p = performance.getentries(); for (var i=0; i < p.length; i++) { console.log...
PerformanceEventTiming - Web APIs
methods performanceeventtiming.tojson() converts the performanceeventtim...
...own keypress keyup mousedown mouseenter mouseleave mouseout mouseover mouseup pointerover pointerenter pointerdown pointerup pointercancel pointerout pointerleave gotpointercapture lostpointercapture touchstart touchend touchcancel properties performanceeventtiming.processingstart re
turns the time at which event dispatch started. performanceeventtiming.processingend re
turns the time at which the event dispatch ended. performanceeventtiming.cancelable re
turns the associated event's cancelable attribute. performanceeventtiming.target re
turns the associated event's last target, if it is not removed. methods performanceeventtiming.tojson() converts the performanceeventtiming object to json. examples the following example shows how to use the api for all ev...
PerformanceFrameTiming - Web APIs
methods this interface has no methods. example see the example in using the frame timing api. specifications specif...
...t-baseline="middle">performanceframetiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties (for "frame" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype re
turns "frame". performanceentry.name re
turns the document's address. performanceentry.starttime re
turns the timestamp when the frame was started. performanceentry.duration re
turns a timestamp indicating the difference between the starttimes of two successive frames. methods this interface has no methods. example see the example in using the frame timing api. specifications specification status comment fra...
PerformanceMark - Web APIs
(a mark has no duration.) methods this interface has no methods. example see the example in using the user timing api. specifications...
...pace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemark</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constraining the properties as follows: performanceentry.entrytype re
turns "mark". performanceentry.name re
turns the name given to the mark when it was created via a call to performance.mark(). performanceentry.starttime re
turns the domhighrestimestamp when performance.mark() was called. performanceentry.duration re
turns "0". (a mark has no duration.) methods this interface has no methods. example see the example in using the user timing api. specifications specification status co...
PerformanceNavigationTiming.type - Web APIs
example the following example illustrates this property's usage. ...
...s bar, form submission, or initializing through a script operation other than reload and back_forward as listed below. reload navigation is through the browser's reload operation or location.reload(). back_forward navigation is through the browser's history traversal operation. prerender navigation is initiated by a prerender hint. this property is read only . syntax perfentry.type; re
turn value a string which is one of the values listed above. example the following example illustrates this property's usage. function print_nav_timing_data() { // use getentriesbytype() to just get the "navigation" events var perfentries = performance.getentriesbytype("navigation"); for (var i=0; i < perfentries.length; i++) { console.log("= navigation entry[" + i + "]"); var p = p...
PerformanceObserverEntryList.getEntries() - Web APIs
the list's members are determined by the set of entry types specified in the call to the observe() method. the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. ...
...ing fields: "name", the name of a performance entry. "entrytype", the entry type. the valid entry types are listed in the performanceentry.entrytype method. "initiatortype", the type of the initiating resource (for example an html element). the values are defined by the performanceresourcetiming.initiatortype interface. this parameter is currently not supported on chrome or opera. re
turn value a list of explicitly observed performanceentry objects that meets the criteria of the filter. the items will be in chronological order based on the entries' starttime. if no objects that meet the filter are found, an empty list is re
turned. if no argument is given, all entries are re
turned. example function print_perf_entry(pe) { console.log("name: " + pe.name + ...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
the getentriesbyname() method of the performanceobserverentrylist interface re
turns a list of explicitly observed performance entry objects for a given name and entry type. the list's members are determined by the set of entry types specified in the call to the observe() method. the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. syntax entries = list.getentriesbyname(name, type); parameters name a domstring representing the name of the entry to retrieve. type optional a domstring representing the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. ...
... function (as the first parameter in the callback). this method is exposed to window and worker interfaces. syntax entries = list.getentriesbyname(name, type); parameters name a domstring representing the name of the entry to retrieve. type optional a domstring representing the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. re
turn value a list of explicitly observed performance entry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to re
turn. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is re
turned. example function print_perf_entry(pe) { console...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
the getentriesbytype() method of the performanceobserverentrylist re
turns a list of explicitly observed performance entry objects for a given performance entry type. the list's members are determined by the set of entry types specified in the call to the observe() method. the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. syntax entries = list.getentriesbytype(type); parameters type the type of entry to retrieve such as "frame". the valid entry types are listed in performanceentry.entrytype. re
turn value a list of explicitly observed performanceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects hav...
...ype); parameters type the type of entry to retrieve such as "frame". the valid entry types are listed in performanceentry.entrytype. re
turn value a list of explicitly observed performanceentry objects that have the specified type. the items will be in chronological order based on the entries' starttime. if no objects have the specified type, or no argument is provided, an empty list is re
turned. example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perf...
PerformancePaintTiming - Web APIs
methods this interface has no methods. example function showpainttimings() { if (window.performance) { let performance = window.performance; let performanceentries = performance.
...t-baseline="middle">performancepainttiming</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties (for "paint" performance entry types) by qualifying and constraining the properties as follows: performanceentry.entrytype re
turns "paint". performanceentry.name re
turns either "first-paint" or "first-contentful-paint". performanceentry.starttime re
turns the timestamp when the paint ocurred. performanceentry.duration re
turns 0. methods this interface has no methods. example function showpainttimings() { if (window.performance) { let performance = window.performance; let performanceentries = performance.getentriesbytype('paint'); performanc...
PerformanceResourceTiming.connectEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.connectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.domainLookupEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.domainLookupStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.fetchStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.responseEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.responseStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.workerStart - Web APIs
note: this feature is available in web workers. syntax resource.workerstart; value a domhighrestimestamp. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... note: this feature is available in web workers. syntax resource.workerstart; value a domhighrestimestamp. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceServerTiming - Web APIs
es performanceservertiming.descriptionread only a domstring value of the server-specified metric description, or an empty string. performanceservertiming.durationread only a double that contains the server-specified metric duration, or value 0.0. performanceservertiming.nameread only a domstring value of the server-specified metric name. methods performanceservertiming.tojson() re
turns a domstring that is the json representation of the performanceservertiming object. example given a server that sends the server-timing header, for example a node.js server like this: const http = require('http'); function requesthandler(request, response) { const headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\...
... object. ...
Using the Performance API - Web APIs
and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. the following code example shows the use of domhighrestimestamp and the performance.now() method. ...
...in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element. ...
Performance Timeline - Web APIs
erview of the standard's interfaces. for more details about the interfaces, see the reference pages and using performance timeline. performance extensions the performance timeline api extends the performance interface with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. the methods are: getentries() re
turns all recorded performance entries or, optionally, the entries based on the specified name, performance type and/or the initiatortype (such as an html element). getentriesbyname() re
turns the recorded performance entries based on the specified name and optionally the performance type. getentriesbytype() re
turns the recorded performance entries based on the specified performance type. perform...
...ormance metric (for example, "mark"). starttime a high resolution timestamp representing the starting time for the performance entry. duration a high resolution timestamp representing the time value of the duration of the performance event. (some performance entry types have no concept of duration and this value is set to '0' for such types.) this interface includes a tojson() method that re
turns the serialization of the performanceentry object. the serialization is specific to the performance entry's type. performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback function that was speci...
PermissionStatus - Web APIs
later versions of the specification replace this with permissionstatus.state. event handler permissionstatus.onchange an event called whenever permissionstatus.status changes. ...
...later versions of the specification replace this with permissionstatus.state. event handler permissionstatus.onchange an event called whenever permissionstatus.status changes. ...
Permissions.query() - Web APIs
syntax navigator.permissions.query(permissiondescriptor).then(function(permissionstatus) { ... }) parameters permissiondescriptor an object that sets options for the query operation consisting of a comma-separated list of name-value pairs. the available options are: name: the name of the api whose permissions you want to query. an up-to-date list of permission names can be found in the spec under the permissionname enum, but bear in mind that the actual permissions supported by browsers is currently much smaller than this. ...
...y message or be able to send silent push notifications. the default is false. sysex: (midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will re
turn true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. re
turns a promise that resolves to a permissionstatus object. exceptions exception explanation typeerror retrieving the permissiondescriptor information failed in some way, or th...
PhotoCapabilities.redEyeReduction - Web APIs
controllable red-eye reduction is available in the source and it is configurable via the photosettings object. specifications specification status comment mediastream image capturethe definition of 'redeyereduction' in that specification. working draft initial definition. ...
... controllable red-eye reduction is available in the source and it is configurable via the photosettings object. specifications specification status comment mediastream image capturethe definition of 'redeyereduction' in that specification. working draft initial definition. ...
PluginArray - Web APIs
the pluginarray interface is used to store a list of plugin objects describing the available plugins; it's re
turned by the window.navigator.plugins property. the pluginarray is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods. note: own properties of pluginarray objects are no longer enumerable in the latest browser versions. properties pluginarray.lengthread only the number of plugins in the array. methods pluginarray.item re
turns the plugin at the specified index into the array. pluginarray.nameditem re
turns the plugin with the specified name. pluginarray.refresh refreshes all plugins on the current page, optionally reloading documents...
... browser versions. properties pluginarray.lengthread only the number of plugins in the array. methods pluginarray.item re
turns the plugin at the specified index into the array. pluginarray.nameditem re
turns the plugin with the specified name. pluginarray.refresh refreshes all plugins on the current page, optionally reloading documents. examples the following example function re
turns the version of the shockwave flash plugin. var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++...
PointerEvent.isPrimary - Web APIs
in a multi-pointer scenario (such as a touch screen that supports more than one touch point), this property is used to identify a master pointer among the set of active pointers for each pointer type. only a primary pointer will produce compatibility mouse events. authors who desire only single-pointer interaction can achieve that by ignoring non-primary pointers. ...
...pointertype) are considered primary. for example, a touch contact and a mouse cursor moved simultaneously will produce pointers that are both considered primary. if there are multiple primary pointers, these pointers will all produce compatibility mouse events (see pointer_events for more information about pointer, mouse and touch interaction). syntax var isprimary = pointerevent.isprimary; re
turn value isprimary re
turns true if the pointer for this event is the primary pointer and re
turns false otherwise. example this example illustrates using the value of isprimary to call the appropriate processing function. target.addeventlistener('pointerdown', function(event) { if (event.isprimary) process_primary_pointer(event); else process_secondary_pointer(event); }, fals...
PositionOptions - Web APIs
mes or increased power consumption (with a gps chip on a mobile device for example). on the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. default: false. positionoptions.timeout secure context is a positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to re
turn a position. the default value is infinity, meaning that getcurrentposition() won't re
turn until the position is available. positionoptions.maximumage secure context is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to re
turn. if set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real...
...default: 0. specifications specification status comment geolocation apithe definition of 'positionoptions' in that specification. ...
PromiseRejectionEvent() - Web APIs
with promise rejection events, it becomes possible to detect and report promises which fail and whose failures go unnoticed. it also becomes easier to write a global handler for errors. there are two types of promiserejectionevent: unhandledrejection is sent by the javascript runtime when a promise is rejected but the rejection goes unhandled. a rejectionhandled event is emitted if a promise is rejected but the rejection is caught by a rejection handler.. ...
...). options an object specifying details about the rejection which occurred: promise the promise that was rejected. reason any value or object which represents the reason the promise was rejected. this can be anything from a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. re
turn value a new promiserejectionevent configured as specified by the parameters. examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". the reason could just as easily be a number, or even an object with detailed information including the home address, how serious the fire is, and the phone number of an emergen...
PublicKeyCredential.getClientExtensionResults() - Web APIs
during the creation or fetching of a publickeycredential (respectively via navigator.credentials.create() and navigator.credentials.get()), it is possible to have "custom" processing by the client for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions. note: extensions are optional and different browsers may recognize different extensions. ...
...t browsers may recognize different extensions. all extensions are optional for the client to process them: if a browser does not know of a given extension, that will not cause any failure. note: this method may only be used in top-level contexts and will not be available in an <iframe> for example. syntax maparraybuffer = publickeycredential.getclientextensionresults() parameters none. re
turn value an arraybuffer containing the result of the processing of the different extensions by the client. this object contains a map between the extensions' identifiers and their results from the processing. warning! as of march 2019, only appid (used during creation with publickeycredentialrequestoptions.extensions) is supported by chrome and edge. firefox does not seem to support any extension...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
a user-verifying platform authenticator is a kind of multi-factor authenticator that is part of the client device (it is generally not removable) and that involves an action from the user in order to identify them. at the time of this writing, this method's result only resolves to true on windows when windows hello capabilities are available (on recent versions of this os). ...
...order to identify them. at the time of this writing, this method's result only resolves to true on windows when windows hello capabilities are available (on recent versions of this os). note: this method may only be used in top-level contexts and will not be available in an <iframe> for example. syntax publickeycredential.isuserverifyingplatformauthenticatoravailable() parameters none. re
turn value a promise which resolves to a boolean indicating whether or a not a user-verifying platform authenticator is available. as of today (march 2019), this is basically indicating if windows hello may be used with the web authentication api and that the user has accepted its use. note: this is a static method which is directly called on the publickeycredential interface and not on an instance...
PushEvent.data - Web APIs
the data read-only property of the pushevent interface re
turns a reference to a pushmessagedata object containing data sent to the pushsubscription. syntax var mypushdata = pushevent.data; value a pushmessagedata object. examples the following example takes data from a pushevent and displays it on all of the service workers' clients. ...
...e to a pushmessagedata object containing data sent to the pushsubscription. syntax var mypushdata = pushevent.data; value a pushmessagedata object. examples the following example takes data from a pushevent and displays it on all of the service workers' clients. ...
PushManager.permissionState() - Web APIs
the permissionstate() method of the pushmanager interface re
turns a promise that resolves to a domstring indicating the permission state of the push manager. possible values are 'prompt', 'denied', or 'granted'. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted for notifications, push will also be enabled. syntax pushmanager.permissionstate(options).then(function(pushmessagingstate) { ... }); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the re
turned push subscription will only be used for messages whose effect is made visible to the user. applicationserverkey: a public key your push server will u...
... specifications specification status comment push apithe definition of 'permissionstate()' in that specification. ...
PushManager.subscribe() - Web APIs
the subscribe() method of the pushmanager interface subscribes to a push service. it re
turns a promise that resolves to a pushsubscription object containing details of a push subscription. a new push subscription is created if the current service worker does not have an existing subscription. syntax pushmanager.subscribe(options).then(function(pushsubscription) { ... } ); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the re
turned push subscription will only be used for messages whose effect is made visible to the user. applicationserverkey: a base64-encoded domstring or arraybuffer containing an ecdsa p-256 public key that the push server will use to authen...
...nticate your application server. if specified, all messages from your application server must use the vapid authentication scheme, and include a jwt signed with the corresponding private key. this key is not the same ecdh key that you use to encrypt the data. for more information, see "using vapid with webpush". note: this parameter is required in some browsers like chrome and edge. re
turns a promise that resolves to a pushsubscription object. example this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc. } navigator.serviceworker.register('serviceworker.js'); // use serviceworker.ready to ensure that you can subscribe for push navigator.serviceworker.ready.the...
PushManager - Web APIs
ger interface of the push api provides a way to receive notifications from third-party servers as well as request urls for push notifications. this interface is accessed via the serviceworkerregistration.pushmanager property. note: this interface replaces functionality previously offered by the obsolete pushregistrationmanager interface. properties pushmanager.supportedcontentencodings re
turns an array of supported content codings that can be used to encrypt the payload of a push message. methods pushmanager.getsubscription() retrieves an existing push subscription. it re
turns a promise that resolves to a pushsubscription object containing details of an existing subscription. if no existing subscription exists, this resolves to a null value. pushmanager.permissionstate() retur...
...a promise that resolves to a pushsubscription object containing details of an existing subscription. if no existing subscription exists, this resolves to a null value. pushmanager.permissionstate() re
turns a promise that resolves to the permission state of the current pushmanager, which will be one of 'granted', 'denied', or 'prompt'. pushmanager.subscribe() subscribes to a push service. it re
turns a promise that resolves to a pushsubscription object containing details of a push subscription. a new push subscription is created if the current service worker does not have an existing subscription. deprecated methods pushmanager.haspermission() re
turns a promise that resolves to the pushpermissionstatus of the requesting webapp, which will be one of granted, denied, or default. replac...
PushSubscription.getKey() - Web APIs
the getkey() method of the pushsubscription interface re
turns an arraybuffer representing a client public key, which can then be sent to a server and used in encrypting push message data. syntax var key = subscription.getkey(name); parameters name a domstring representing the encryption method used to generate a client key. the value can be: p256dh: an elliptic curve diffie–hellman public key on the p-256 curve (that is, the nist secp256r1 elliptic curve). the resulting key is an uncompressed point in ansi x9.62 format. auth: an authentication secret, as described in message encryption for web push. re
turns an arraybuffer. example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push ...
...encryption for web push. re
turns an arraybuffer. example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages. ...
PushSubscription.toJSON() - Web APIs
it currently only contains the subscription endpoint, as an endpoint member. ...
...it currently only contains the subscription endpoint, as an endpoint member. ...
PushSubscription - Web APIs
timestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise. pushsubscription.options read only an object containing the options used to create the subscription. pushsubscription.subscriptionid read only a domstring containing the subscription id associated with the push subscription. ...
... used to create the subscription. pushsubscription.subscriptionid read only a domstring containing the subscription id associated with the push subscription. methods pushsubscription.getkey() re
turns 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 — re
turns a json representation of the subscription properties. pushsubscription.unsubscribe() starts the asynchronous process of unsubscribing from the push service, re
turning 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) { ...
RTCConfiguration.iceServers - Web APIs
each object must at least have an urls property, which is an array of one or more strings, each providing one server's url. ...
...each object must at least have an urls property, which is an array of one or more strings, each providing one server's url. ...
RTCDataChannel.close() - Web APIs
s. most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a close event on the data channel. the sequence of events which occurs in response to this method being called: rtcdatachannel.readystate is set to "closing". a background task is established to handle the remainder of the steps below, and close() re
turns to the caller. the transport layer deals with any buffered messages; the protocol layer decides whether to send them or discard them. the underlying data transport is closed. the rtcdatachannel.readystate property is set to "closed". if the transport was closed with an error, the rtcdatachannel is sent a networkerror event. a close event is sent to the channel. in firefox, the rtcdatacha...
...the rtcdatachannel.readystate property is set to "closed". if the transport was closed with an error, the rtcdatachannel is sent a networkerror event. a close event is sent to the channel. in firefox, the rtcdatachannel interface was implemented under the name datachannel until firefox 24, so this method was called datachannel.close(). syntax rtcdatachannel.close(); parameters none. re
turn value undefined. example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // now negot...
RTCDataChannelEvent - Web APIs
these events sent to an rtcpeerconnection when its remote peer is asking to open an rtcdatachannel between the two peers. you will rarely if ever construct an rtcdatachannelevent by hand; instead, the webrtc layer will generate and deliver them to you at the appropriate time. just listen for the datachannel event to be received by the rtcpeerconnection and when you receive it, use the rtcdatachannelevent.channel property to gain access to the data channel which has been opened. ...
...event to be received by the rtcpeerconnection and when you receive it, use the rtcdatachannelevent.channel property to gain access to the data channel which has been opened. constructorrtcdatachannelevent() the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.propertiesalso inherits properties from: eventchannel read only the read-only property rtcdatachannelevent.channel re
turns the rtcdatachannel associated with the event.methodsthis interface has no methods, but inherits methods from: event examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. the channel property provides the rtcdatachannel representing the connection to the other peer. pc.ondatachannel = ...
RTCIceCandidate.address - Web APIs
ss property on rtcicecandidate can expose more information about the source of the remote peer than the user expects. the ip address can be used to derive information about the remote device's location, network topology, and so forth. it can also be used for fingerprinting purposes. the candidate ip addresses are always exposed to the application through address, and unsavory applications can in
turn potentially reveal the address to the user. this can occur without the remote peer's consent. applications being built with user privacy and security in mind can choose to limit the permitted candidates to relay candidates only. doing so prevents the remote user's address from being exposed, but reduces the pool of available candidates to choose from. to do this, configure the ice agent's ice tr...
...ions being built with user privacy and security in mind can choose to limit the permitted candidates to relay candidates only. doing so prevents the remote user's address from being exposed, but reduces the pool of available candidates to choose from. to do this, configure the ice agent's ice transport policy using rtcconfiguration, like this: var rtcconfig = { iceservers: [ { urls: "
turn:my
turn.server.ip", username: "username", credential: "password" } ], icetransportpolicy: "relay" } by setting rtcconfiguration.icetransportpolicy to "relay", any host candidates (candidates where the ip address is the peer's own ip address) are left out of the pool of candidates, as are any other candidates which aren't relay candidates. usage notes consider this sdp attri...
RTCIceCandidate.candidate - Web APIs
most of the other properties of rtcicecandidate are actually extracted from this string. this property can be configured by specifying the value of the candidate property when constructing the new candidate object using rtcicecandidate(). syntax var candidate = rtcicecandidate.candidate; value a domstring describing the properties of the candidate, taken directly from the sdp attribute "candidate". the candidate string specifies the network connectivity information for the candidate. ...
... signaling process. function handlenewicecandidate(candidatesdp) { var candidateobj = new rtcicecandidate(candidatesdp); mypeerconnection.addicecandidate(candidateobj).catch({ /* handle the error thrown by addicecandidate() */ }); } the handlenewicecandidate() function shown here passes the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in re
turn, which represents the candidate. the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established. this example could be simplified somewhat; you may more often see the code look something like this, taking advantage of more advanced ecmascript 2016 features: let handlenewi...
RTCIceCandidate.relatedAddress - Web APIs
on them having non-null values. syntax var reladdress = rtcicecandidate.relatedaddress; value a domstring which contains the candidate's related address. for both peer and server reflexive candidates, the related address (and related port) are the base for that server or peer reflexive candidate. for relay candidates, the related address and port are set to the mapped address selected by the
turn server. for host candidates, relatedaddress is null, meaning the field is not included in the candidate's a-line. usage notes the related address is included in ice candidates despite not being used by ice itself. relatedaddress can be used for diagnostic purposes; by observing the relationships between the various types of candidates and their addresses and related addresses. relatedaddress c...
... candidate recommendation initial definition. ...
RTCIceCandidate. toJSON() - Web APIs
see the example below. example this simple example obtains a json string representing an rtcicecandidate found in the variable candidate. ...
...see the example below. example this simple example obtains a json string representing an rtcicecandidate found in the variable candidate. ...
RTCIceCandidate - Web APIs
string is empty ("") if the rtcicecandidate is an "end of candidates" indicator. component read only a domstring which indicates whether the candidate is an rtp or an rtcp candidate; its value is either "rtp" or "rtcp", and is derived from the "component-id" field in the candidate a-line string. the permitted values are listed in the rtcicecomponent enumerated type. foundation read only re
turns a domstring containing a unique identifier that is the same for any candidates of the same type, share the same base (the address from which the ice agent sent the candidate), and come from the same stun server. this is used to help optimize ice performance while prioritizing and correlating candidates that appear on multiple rtcicetransport objects. ip read only a domstring containing the ip...
...ing a randomly-generated username fragment ("ice-ufrag") which ice uses for message integrity along with a randomly-generated password ("ice-pwd"). you can use this string to verify generations of ice generation; each generation of the same ice process will use the same usernamefragment, even across ice restarts. methods tojson() given the rtcicecandidate's current configuration, tojson() re
turns a domstring containing a json representation of that configuration in the form of a rtcicecandidateinit object. examples for examples, see the article signaling and video calling, which demonstrates the entire process. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate' in that specificat...
RTCIceCandidatePairStats.selected - Web APIs
m a statistics report by first iterating over each report, looking for a transport report; when one is found, that transport's selectedcandidatepairid is used to get the rtcicecandidatepair describing the connection. if that fails, then the second section iterates over the reports, looking for a candidate-pair record whose firefox-specific selected property is true. this candidate pair is then re
turned as the currently-selected one. function getcurrentcandidatepair(statsresults) { statsresults.foreach(report => { if (report.type === "transport") { currentpair = statsresults.get(report.selectedcandidatepairid); } }); if (!currentpair) { statsresults.foreach(report => { if (report.type === "candidate-pair" && report.selected) { currentpair = report; ...
...selected one. function getcurrentcandidatepair(statsresults) { statsresults.foreach(report => { if (report.type === "transport") { currentpair = statsresults.get(report.selectedcandidatepairid); } }); if (!currentpair) { statsresults.foreach(report => { if (report.type === "candidate-pair" && report.selected) { currentpair = report; } }); } re
turn currentpair; } specifications not part of any specification. this property is unique to firefox. ...
RTCIceCandidatePairStats - Web APIs
determine the selected candidate pair is to look for a stats object of type transport, which is an rtctransportstats object. that object's selectedcandidatepairid property indicates whether or not the specified transport is the one being used. ...
...for more information, see ice restart in lifetime of a webrtc session. example this example computes the average time elapsed between connectivity checks if the rtcstats object rtcstats is an rtcicecandidatepairstats object. ...
RTCIceTransport.getLocalCandidates() - Web APIs
you can't correlate these local candidates with matching remote candidates. ...
...r each of the candidates that have been gathered by the local device during the current ice agent session. the local candidates are placed in this list by the ice agent prior to being delivered to the local client's code in an icecandidate event so that the client can forward the candidates to the remote peer. syntax localcandidates = rtcicetransport.getlocalcandidates(); parameters none. re
turn value a javascript array containing one rtcicecandidate object for each candidate that has been identified so far during the ice candidate gathering session. you can't correlate these local candidates with matching remote candidates. to find the best match found so far, call rtcicetransport.getselectedcandidatepair(). example this simple example gets the local candidate list from the rtcicetr...
RTCInboundRtpStreamStats.qpSum - Web APIs
to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. ...
...stream statistics, re
turning 0 if the object doesn't describe an rtp stream. function calculateaverageqp(stats) { let framecount = 0; switch(stats.type) { case "inbound-rtp": case "remote-inbound-rtp": framecount = stats.framesdecoded; break; case "outbound-rtp": case "remote-outbound-rtp": framecount = stats.framesencoded; break; default: re
turn 0; } re
turn status.qpsum / framecount; } specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.qpsum' in that specification. candidate recommendation initial definition. ...
RTCOutboundRtpStreamStats.qpSum - Web APIs
to derive a scaling matrix used during the quantization process. additionally, qp is not likely to be the only parameter the codec uses to adjust the compression. see the individual codec specifications for details. ...
...stream statistics, re
turning 0 if the object doesn't describe an rtp stream. function calculateaverageqp(stats) { let framecount = 0; switch(stats.type) { case "inbound-rtp": case "remote-inbound-rtp": framecount = stats.framesdecoded; break; case "outbound-rtp": case "remote-outbound-rtp": framecount = stats.framesencoded; break; default: re
turn 0; } re
turn status.qpsum / framecount; } specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.qpsum' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.currentLocalDescription - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated. to change the currentlocaldescription, call rtcpeerconnection.setlocaldescription(), which triggers a series of events which leads to this value being set. ...
...rily instantaneous, see pending and current descriptions in webrtc connectivity. unlike rtcpeerconnection.localdescription, this value represents the actual current state of the local end of the connection; localdescription may specify a description which the connection is currently in the process of switching over to. syntax sessiondescription = rtcpeerconnection.currentlocaldescription; re
turn value the current description of the local end of the connection, if one has been set. if none has been successfully set, this value is null. example this example looks at the currentlocaldescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. var pc = new rtcpeerconnection(); … var sd = pc.currentlocaldescription; if (sd) { alert("local sessio...
RTCPeerConnection.currentRemoteDescription - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated. to change the currentremotedescription, call rtcpeerconnection.setremotedescription(), which triggers a series of events which leads to this value being set. ...
...y instantaneous, see pending and current descriptions in webrtc connectivity. unlike rtcpeerconnection.remotedescription, this value represents the actual current state of the local end of the connection; remotedescription may specify a description which the connection is currently in the process of switching over to. syntax sessiondescription = rtcpeerconnection.currentremotedescription; re
turn value the current description of the remote end of the connection, if one has been set. if none has been successfully set, this value is null. example this example looks at the currentremotedescription and displays an alert containing the rtcsessiondescription object's type and sdp fields. var pc = new rtcpeerconnection(); … var sd = pc.currentremotedescription; if (sd) { alert("local ses...
RTCPeerConnection.getTransceivers() - Web APIs
the list is in the order in which the transceivers were added to the connection. example the following snippet of code stops all transceivers associated with an rtcpeerconnection. ...
...the list is in the order in which the transceivers were added to the connection. example the following snippet of code stops all transceivers associated with an rtcpeerconnection. ...
RTCPeerConnection.iceConnectionState - Web APIs
the read-only property rtcpeerconnection.iceconnectionstate re
turns an enum of type rtciceconnectionstate which state of the ice agent associated with the rtcpeerconnection. you can detect when this value has changed by watching for the iceconnectionstatechange event. syntax var state = rtcpeerconnection.iceconnectionstate; value the current state of the ice agent and its connection. the value is one of the strings in the rtciceconnectionstate enum. rtciceconnectionstate enum the rtciceconnectionstate enum defines the string constants used to describe the current state of the ice agent and its connection to the ice server (that is, the stun or
turn server). constant description "new" the ice agent is gathering addresses or is waiting to be given remote can...
...atible connections for some components. "disconnected" checks to ensure that components are still connected failed for at least one component of the rtcpeerconnection. this is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. when the problem resolves, the connection may re
turn to the "connected" state. "closed" the ice agent for this rtcpeerconnection has shut down and is no longer handling requests. example var pc = new rtcpeerconnection(); var state = pc.iceconnectionstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.iceconnection...
RTCPeerConnection: negotiationneeded event - Web APIs
aling and video calling for a description of the signaling process that begins with a negotiationneeded event. examples in this example, we use addeventlistener() to create an event handler for negotiationneeded. its role is to create an sdp offer and send it through the signaling channel to the remote peer. ...
... up by creating its own rtcpeerconnection, setting the remote description with setremotedescription(), and then creating an answer to send back to the offering peer. you can also set an event handler for the negotiationneeded event by assigning the event handler function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => re
turn pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }; for a more detailed example, see starting negotiation in signaling and video calling. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definiti...
RTCPeerConnection.onnegotiationneeded - Web APIs
ou can get by examining the properties of the rtcpeerconnection. example this example, derived from the example in signaling and video calling, establishes a handler for negotiationneeded events to handle creating an offer, configuring the local end of the connection, and sending the offer to the remote peer. ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onnegotiationneeded' in that specification. ...
RTCPeerConnection.restartIce() - Web APIs
the webrtc api's rtcpeerconnection interface offers the restartice() method to allow a web application to easily request that ice candidate gathering be redone on both ends of the connection. this simplifies the process by allowing the same method to be used by either the caller or the receiver to trigger an ice restart. after restartice() re
turns, the offer re
turned by the next call to createoffer() is automatically configured to trigger ice restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. restartice() causes the negotiationneeded event to be fired on the rtcpeerconnection to inform the application that it should perform negotiation using its ...
...back or because incoming offers are in the process of being negotiated—the rtcpeerconnection will remember that you requested ice restart. the next time the connection's signalingstate changes to stable, the connection will fire the negotiationneeded event. this process continues until an ice restart has been successfully completed. syntax rtcpeerconnection.restartice(); parameters none. re
turn value undefined. usage notes after calling restartice(), the next offer created using createoffer() will initiate ice restart once sent to the remote peer over your signaling mechanism. restarting ice essentially resets ice so that it creates all new candidates using new credentials. existing media transmissions continue uninterrupted during this process. for details about how ice restart wor...
RTCPeerConnection: track event - Web APIs
interface rtctrackevent event handler property ontrack by the time this event is delivered, the new track has been fully added to the peer connection. see track event types in rtctrackevent for details. examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler. pc = new rtcpeerconnection({ iceservers: [ { urls: "
turn:fake.
turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addeventlistener("track", e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoelement. you can also assign the event handler funct...
...= e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoelement. you can also assign the event handler function to the ontrack property, rather than use addeventlistener(). pc.ontrack = e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; re
turn false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'track' in that specification. candidate recommendation initial specification. ...
RTCPeerConnectionIceEvent() - Web APIs
the name of the event, like "icecandidate". options a dictionary of type rtcpeerconnectioninit, which may contain one or more of the following fields: "candidate" (optional, default is null): a rtcicecandidate representing the ice candidate being concerned by the event. if null, the event indicates the end of candidate gathering. "url" (optional, default is null): the url of the stun or
turn server which was used to gather the candidate. if the candidate was not gathered by a stun or
turn server, this value must be null. "bubbles" (optional, default is false): inherited from eventinit(), this boolean option indicates whether or not the event must bubble. "cancelable" (optional, default is false, inherited from eventinit(), this boolean indicates whether or not the event can be ca...
...s used to gather the candidate. if the candidate was not gathered by a stun or
turn server, this value must be null. "bubbles" (optional, default is false): inherited from eventinit(), this boolean option indicates whether or not the event must bubble. "cancelable" (optional, default is false, inherited from eventinit(), this boolean indicates whether or not the event can be canceled. re
turn value a newly-created rtcpeerconnectioniceevent, configured as specified in the provided options. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceevent()' in that specification. candidate recommendation initial definition. ...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
p (describing a remote peer's statistics about sending data to the local peer) has a corresponding record of type inbound-rtp which describes the local peer's perspective on the same data being moved between the two peers. let's create a utility function to help us look up the value of a key in the paired statistics object. ...
... an rtcstatsreport, re
turning the rtcstats-based statistics record which contains the specified key — and for which the key has the specified value. if no match is found (or the statistics report has no record corresponding to the statistics category indicated by key. function findreportentry(report, key, value) { for (const stats of report.values()) { if (stats[key] === value) { re
turn stats; } } re
turn null; } since the rtcstatsreport is a javascript map, we can iterate over the map's values() to examine each of the rtcstats-based statistics records in the report until we find one that has the key property with the specified value. when a match is found, the statistics object is re
turned. if no match is found, the function re
turns null. the main networkteststop() fu...
RTCRtpReceiveParameters - Web APIs
the rtcrtpreceiveparameters dictionary, based upon the rtcrtpparameters dictionary, is re
turned by the the rtcrtpreceiver method getparameters(). it describes the parameters being used by the receiver's rtp connection to the remote peer. properties this dictionary currently has no properties of its own; it exists for future expansion. it inherits all of the properties of its parent, rtcrtpparameters. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. ...
...eceiver's rtp connection to the remote peer. properties this dictionary currently has no properties of its own; it exists for future expansion. it inherits all of the properties of its parent, rtcrtpparameters. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. function getrtcpcname(receiver) { let parameters = receiver.getparameters(); re
turn parameters.rtcp.cname; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiveparameters' in that specification. candidate recommendation initial definition. ...
RTCRtpReceiver.getContributingSources() - Web APIs
each instance describes one of the contributing sources that provided data to the incoming stream in the past ten seconds. ...
...each instance describes one of the contributing sources that provided data to the incoming stream in the past ten seconds. ...
RTCRtpReceiver.getParameters() - Web APIs
the getparameters() method of the rtcrtpreceiver interface re
turns an rtcrtpreceiveparameters object describing the current configuration for the encoding and transmission of media on the receiver's track. syntax let rtpreceiveparameters = rtpreceiver.getparameters(); parameters none. re
turn value an rtcrtpreceiveparameters object indicating the current configuration of the receiver. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. ...
... on the receiver's track. syntax let rtpreceiveparameters = rtpreceiver.getparameters(); parameters none. re
turn value an rtcrtpreceiveparameters object indicating the current configuration of the receiver. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver. function getrtcpcname(receiver) { let parameters = receiver.getparameters(); re
turn parameters.rtcp.cname; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getparameters()' in that specification. candidate recommendation initial definition. ...
RTCRtpReceiver.getSynchronizationSources() - Web APIs
each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. as you'll see in the documentarion for rtcrtpsynchronizationsource, it inherits the properties of rtcrtpcontributingsource, including timestamp, source, and audiolevel. ...
...each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. as you'll see in the documentarion for rtcrtpsynchronizationsource, it inherits the properties of rtcrtpcontributingsource, including timestamp, source, and audiolevel. ...
RTCRtpSender.getParameters() - Web APIs
the getparameters() method of the rtcrtpsender interface re
turns an rtcrtpsendparameters object describing the current configuration for the encoding and transmission of media on the sender's track. syntax var rtpsendparameters = rtpsender.getparameters() parameters none. re
turn value an rtcrtpsendparameters object indicating the current configuration of the sender. examples this example gets the sender's current transaction id; the transaction id uniquely identifies the current set of parameters, to ensure that calls to setparameters() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters. ...
...uration of the sender. examples this example gets the sender's current transaction id; the transaction id uniquely identifies the current set of parameters, to ensure that calls to setparameters() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters. function getsendertransactionid(sender) { let parameters = sender.getparameters(); re
turn parameters.transactionid; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'getparameters()' in that specification. candidate recommendation initial definition. ...
RTCRtpSender - Web APIs
of media and control data. this value is null until the transport is established. when bundling is in use, more than transceiver may be sharing the same transport object. obsolete properties rtcptransport this property has been removed; the rtp and rtcp transports have been combined into a single transport. use the transport property instead. methods rtcrtpsender.getparameters() re
turns a rtcrtpparameters object describing the current configuration for the encoding and transmission of media on the track. rtcrtpsender.getstats() re
turns a promise which is fulfilled with a rtcstatsreport which provides statistics data for all outbound streams being sent using this rtcrtpsender. rtcrtpsender.setparameters() applies changes to parameters which configure how the track is encoded...
...) sets the mediastream(s) associated with the track being transmitted by this sender. rtcrtpsender.replacetrack() attempts to replace the track currently being sent by the rtcrtpsender with another track, without performing renegotiation. this method can be used, for example, to toggle between the front- and rear-facing cameras on a device. static methods rtcrtpsender.getcapabilities() re
turns an rtcrtpcapabilities object describing the system's capabilities for sending a specified kind of media data. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender' in that specification. candidate recommendation ...
RTCTrackEvent() - Web APIs
in general, you won't need to use this constructor, as rtctrackevent objects are created by webrtc and delivered to your rtcpeerconnector's ontrack event handler as appropriate. syntax trackevent = new rtctrackevent(eventinfo); parameters eventinfo an object based on the rtctrackeventinit dictionary, providing information about the track which has been added to the rtcpeerconnection. this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. ...
... rtcpeerconnection. this object has the following properties: receiver the rtcrtpreceiver which is being used to receive the track's media. streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track. track the mediastreamtrack the event is associated with. transceiver the rtcrtptransceiver associated with the event. re
turn value a new rtctrackevent describing a track which has been added to the rtcpeerconnection. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtctrackevent()' in that specification. candidate recommendation initial specification. ...
RadioNodeList.value - Web APIs
on setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked. ...
...on setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked. ...
Range.compareNode() - Web APIs
the possible values are: node_before (0) node starts before the range node_after (1) node ends after the range node_before_and_after (2) node starts before and ends after the range node_inside (3) node starts after and ends before the range, i.e. the node is completely selected by the range. ...
...angecomparenode(range, node) { var noderange = node.ownerdocument.createrange(); try { noderange.selectnode(node); } catch (e) { noderange.selectnodecontents(node); } var nodeisbefore = range.compareboundarypoints(range.start_to_start, noderange) == 1; var nodeisafter = range.compareboundarypoints(range.end_to_end, noderange) == -1; if (nodeisbefore && !nodeisafter) re
turn 0; if (!nodeisbefore && nodeisafter) re
turn 1; if (nodeisbefore && nodeisafter) re
turn 2; re
turn 3; } syntax re
turnvalue = range.comparenode( referencenode ); parameters referencenode the node to compare with the range. example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); re
turnvalue = range.comparenode(document.getelem...
Range.comparePoint() - Web APIs
the range.comparepoint() method re
turns -1, 0, or 1 depending on whether the referencenode is before, the same as, or after the range. if the reference node is a node of type text, comment, or cdatasection, then offset is the number of characters from the start of reference node. for other node types, offset is the number of child nodes between the start of the reference node. syntax re
turnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range. offset an integer greater than or equal to zero representing the offset inside the referencenode. ...
...er of child nodes between the start of the reference node. syntax re
turnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range. offset an integer greater than or equal to zero representing the offset inside the referencenode. example range = document.createrange(); range.selectnode(document.getelementsbytagname('div').item(0)); re
turnvalue = range.comparepoint(document.getelementsbytagname('p').item(0), 1); specification specification status comment domthe definition of 'range.comparepoint()' in that specification. living standard initial specification. ...
Range.getBoundingClientRect() - Web APIs
syntax boundingrect = range.getboundingclientrect() example html <div id="highlight"></div> <p>this example positions a "highlight" rectangle behind the contents of a range. the range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
... syntax boundingrect = range.getboundingclientrect() example html <div id="highlight"></div> <p>this example positions a "highlight" rectangle behind the contents of a range. the range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader, or its stream controller is not a readablebytestreamcontroller. ...
... exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader, or its stream controller is not a readablebytestreamcontroller. ...
ReadableStreamBYOBReader - Web APIs
the readablestreambyobreader interface of the streams api represents a byob ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom readablestream() constructor). constructor readablestreambyobreader() creates and re
turns a readablestreambyobreader object instance. properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. re
turns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreambyobreader.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 ...
... readablestreambyobreader.releaselock() releases the reader's lock on the stream. examples tbd. specifications specification status comment streamsthe definition of 'readablestreambyobreader' in that specification. ...
ReportingObserver - Web APIs
nstance, which can be used to collect and access reports. properties this interface has no properties defined on it. methods reportingobserver.disconnect() stops a reporting observer that had previously started observing from collecting reports. reportingobserver.observe() instructs a reporting observer to start collecting reports in its report queue. reportingobserver.takerecords() re
turns the current list of reports contained in the observer's report queue, and empties the queue. events this interface has no events that fire on it. examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(fun...
...e); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice. after the first time we call reportingobserver.takerecords(), which re
turns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting apithe definition of 'reportingobserver' in that specification. editor's draft initial definition. ...
Reporting API - Web APIs
aries reportingobserveroptions allows options to be set in the constructor when creating a reporting observer. available report types the spec defines the following report types: deprecation report indicates that a webapi or other browser feature being used in the website is expected to stop working in a future release. indicated by a report.body property with a deprecationreportbody re
turn value. intervention report indicates that a request made by the website has been denied by the browser, e.g. for security or user annoyance reasons. indicated by a report.body property with a interventionreportbody re
turn value. crash report indicates that the website stopped running due to a browser crash. indicated by a report.body property with a crashreportbody re
turn value. examples i...
...e); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice. after the first time we call reportingobserver.takerecords(), which re
turns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting api spec ...
Request.destination - Web APIs
the string must be one of those found in the requestdestination enumerated type or the empty string, which is the default value. the destination is used by the user agent to, for example, help determine which set of rules to follow for cors purposes, or how to navigate any complicated code paths that affect how specific types of request get handled. these destinations vary substantially in how they operate. some are simply data receptacles, where the received data is stored for processing later. ...
...alues (such as "document" or "manifest"), and may include contextual cues such as "image" or "worker" or "audioworklet". example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // re
turns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification. living standard initial definition ...
Request.referrerPolicy - Web APIs
the referrerpolicy read-only property of the request interface re
turns the referrer policy, which governs what referrer information, sent in the referer header, should be included with the request. syntax var myreferrerpolicy = request.referrerpolicy; value a domstring representing the request's referrerpolicy. for more information and possible values, see the referrer-policy http header page. ...
...errerpolicy. for more information and possible values, see the referrer-policy http header page. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // re
turns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification. living standard initial definition ...
ResizeObserver - Web APIs
l for further explanation. resizeobserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and re
turns a new resizeobserver object. properties none. methods resizeobserver.disconnect() unobserves all observed element targets of a particular observer. resizeobserver.observe() initiates the observing of a specified element. resizeobserver.unobserve() ends the observing of a specified element. examples in the resize-observer-text.html (see source) example, we use the resize observer t...
...ing of a specified element. examples in the resize-observer-text.html (see source) example, we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. we also provide a checkbox to
turn the observer off and on. if it is
turned off, the text will not change in response to the <div>'s width changing. the javascript looks like so: const h1elem = document.queryselector('h1'); const pelem = document.queryselector('p'); const divelem = document.queryselector('body > div'); const slider = document.queryselector('input[type="range"]'); const checkbox = document.queryselector('input[ty...
ResizeObserverEntry.contentRect - Web APIs
the contentrect read-only property of the resizeobserverentry interface re
turns a domrectreadonly object containing the new size of the observed element when the callback is run. note that this is better supported than resizeobserverentry.borderboxsize or resizeobserverentry.contentboxsize, but it is left over from an earlier implementation of the resize observer api, is still included in the spec for web compat reasons, and may be deprecated in future versions. syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the new size of the element indicated by the target property. if the target is an html element, the re
turned contentrect is the element's content box. ...
...rver api, is still included in the spec for web compat reasons, and may be deprecated in future versions. syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the new size of the element indicated by the target property. if the target is an html element, the re
turned contentrect is the element's content box. if the target is an svgelement, the re
turned contentrect is the svg's bounding box. examples the following snippet is taken from the resize-observer-text.html (see source) example. this uses a simple feature detection test to see if the browser supports the newer resizeobserverentry.contentboxsize property — if so, it uses that to get the sizing data it needs. if not, it uses contentrect. const resizeobserver = new resizeobserver(ent...
Response.redirect() - Web APIs
exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. ...
...the serviceworker api. a controlling service worker could intercept a page's request and redirect it as desired. this will actually lead to a real redirect if a service worker sends it upstream. syntax var response = response.redirect(url, status); parameters url the url that the new response is to originate from. status optional an optional status code for the response (e.g., 302.) re
turn value a response object. exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. example responseobj.redirect('https://www.example.com', 302); specifications specification status comment fetchthe definition of 'redirect()' in that specification. ...
Response.redirected - Web APIs
ng the fetch operation. note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under disallowing redirects below. ...
... living standard initial definition ...
SVGAnimationElement - Web APIs
nelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgelement. svganimationelement.targetelement read only an svgelement representing the element which is being animated. if no target element is being animated (for example, because the href specifies an unknown element) the value re
turned is null. methods this interface also inherits methods from its parent, svgelement. svganimationelement.getstarttime() re
turns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. if there is no current interval, then a domexception with code invalid_state_err is thrown. svganimatio...
...nterface also inherits methods from its parent, svgelement. svganimationelement.getstarttime() re
turns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. if there is no current interval, then a domexception with code invalid_state_err is thrown. svganimationelement.getcurrenttime() re
turns a float representing the current time in seconds relative to time zero for the given time container. svganimationelement.getsimpleduration() re
turns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), then a domexception with code not_supported_err is raised. svganimationelement.beginele...
SVGEllipseElement - Web APIs
"-44" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgellipseelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svggeometryelement. svgellipseelement.cx read only this property re
turns a svganimatedlength reflecting the cx attribute of the given <ellipse> element. svgellipseelement.cy read only this property re
turns a svganimatedlength reflecting the cy attribute of the given <ellipse> element. svgellipseelement.rx read only this property re
turns a svganimatedlength reflecting the rx attribute of the given <ellipse> element. svgellipseelement.ry read only this propert...
... methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svggeometryelement. ...
SVGGeometryElement.getPointAtLength() - Web APIs
specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
... specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
SVGGeometryElement.getTotalLength() - Web APIs
specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
... specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.gettotallength()' in that specification. ...
SVGGradientElement - Web APIs
to this type. svg_spreadmethod_pad 1 corresponds to value pad. svg_spreadmethod_reflect 2 corresponds to value reflect. svg_spreadmethod_repeat 3 corresponds to value repeat. properties this interface also inherits properties from its parent, svgelement, and implements those of svgurireference. ...
... to value repeat. properties this interface also inherits properties from its parent, svgelement, and implements those of svgurireference. svggradientelement.gradientunits read only re
turns an svganimatedenumeration corresponding to the gradientunits attribute on the given element. takes one of the constants defined in svgunittypes. svggradientelement.gradienttransform read only re
turns an svganimatedtransformlist corresponding to attribute gradienttransform on the given element. svggradientelement.spreadmethod read only re
turns an svganimatedenumeration corresponding to attribute spreadmethod on the given element. one of the spread method types defined on this interface. methods this interface does not provide any specific methods, but implements those of its parent, svg...
SVGGraphicsElement - Web APIs
rom svg 1.1. properties this interface also inherits properties from its parent, svgelement. svggraphicselement.transform read only an svganimatedtransformlist reflecting the computed value of the transform property and its corresponding transform attribute of the given element. methods this interface also inherits methods from its parent, svgelement. ...
...lement.transform read only an svganimatedtransformlist reflecting the computed value of the transform property and its corresponding transform attribute of the given element. methods this interface also inherits methods from its parent, svgelement. svggraphicselement.getbbox() re
turns a domrect representing the computed bounding box of the current element. svggraphicselement.getctm() re
turns a dommatrix representing the matrix that transforms the current element's coordinate system to its svg viewport's coordinate system. svggraphicselement.getscreenctm() re
turns a dommatrix representing the matrix that transforms the current element's coordinate system to the coordinate system of the svg viewport for the svg document fragment. specifications specification status ...
SVGImageElement.decode - Web APIs
exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. ...
... exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. ...
SVGImageElement - Web APIs
fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgimageelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggraphicselement. svgimageelement.crossorigin a domstring corresponding to the crossorigin attribute of the given <image> element. svgimageelement.decoding re
turns a domstring representing a hint given to the browser on how it should decode the image. svgimageelement.height read only an svganimatedlength corresponding to the height attribute of the given <image> element. svgimageelement.preserveaspectratio read only an svganimatedpreserveaspectratio corresponding to the preserveaspectratio attribute of the given <image> element. svgimageelement.widt...
...geelement.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. re
turns 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 svgtests, svglangspace, svgexternalresour...
SVGLengthList - Web APIs
readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newitem) svglength clears all ex...
...ect itself is read only. initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the re
turn value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength re
turns the specified item from the list. the re
turned item is the item itself and not a copy. any changes ma...
SVGLineElement - Web APIs
stroke-width="2px" /><text x="-29" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svglineelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. ...
...e53" text-anchor="middle" alignment-baseline="middle">svglineelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggeometryelement. svglineelement.x1 read only re
turns an svganimatedlength that corresponds to attribute x1 on the given <line> element. svglineelement.y1 read only re
turns an svganimatedlength that corresponds to attribute y1 on the given <line> element. svglineelement.x2 read only re
turns an svganimatedlength that corresponds to attribute x2 on the given <line> element. svglineelement.y2 read only re
turns an svganimatedlength that corresponds to attribute y2 on the given <line> element. methods this interface doesn't implement any specific methods, but i...
SVGNumberList - Web APIs
readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber newitem) svgnumber clears ...
... object itself is read only. initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the re
turn value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber re
turns the specified item from the list. the re
turned item is the item itself and not a copy. any chang...
SVGPathElement.getTotalLength() - Web APIs
specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgpathelement.gettotallength()' in that specification. ...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgpathelement.gettotallength()' in that specification. ...
SVGPoint - Web APIs
an svgpoint represents a 2d or 3d point in the svg coordinate system. syntax retobject = svgsvgelement.createsvgpoint() value the re
turned value is an svgpoint object. ...
... an svgpoint represents a 2d or 3d point in the svg coordinate system. syntax retobject = svgsvgelement.createsvgpoint() value the re
turned value is an svgpoint object. ...
SVGStringList - Web APIs
readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. methods name & arguments re
turn description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring newitem) domstring clears ...
...t itself is read only. initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the re
turn value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring re
turns the specified item from the list. the re
turned item is the item itself and not a copy. any chang...
Screen.colorDepth - Web APIs
see the browser compatibility section for those that don't. ...
...see the browser compatibility section for those that don't. ...
Screen.orientation - Web APIs
example var orientation = (screen.orientation || {}).type || screen.mozorientation || screen.msorientation; if (orientation === "landscape-primary") { console.log("that looks good."); } else if (orientation === "landscape-secondary") { console.log("mmmh... ...
... example var orientation = (screen.orientation || {}).type || screen.mozorientation || screen.msorientation; if (orientation === "landscape-primary") { console.log("that looks good."); } else if (orientation === "landscape-secondary") { console.log("mmmh... ...
Selection API - Web APIs
the selection api provides functionality for reading and manipulating the range of text selected by the user. concepts and usage to retrieve the current text range the user has selected, you can use the window.getselection() or document.getselection() method, storing the re
turn value — a selection object — in a variable for futher use. once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren(). you can run code in response to the selection b...
...de in response to the selection being changed, or a new selection being started, using the globaleventhandlers.onselectionchange and globaleventhandlers.onselectstart event handlers. selection api interfaces selection represents the range of text selected by the user or the current position of the caret. extensions to other interfaces window.getselection(), document.getselection() re
turns a selection object representing the range of text selected by the user or the current position of the caret. document.getselection() is basically an alias of window.getselection(). globaleventhandlers.onselectstart represents the event handler that is called when a selectstart event is fired on the current object (i.e. when a new range of text is about to be selected by the user). globalevent...
ServiceWorker - Web APIs
ed, and the controlled page has been reloaded.) the serviceworker interface is dispatched a set of lifecycle events — install and activate — and functional events including fetch. a serviceworker object has an associated serviceworker.state, related to its lifecycle. properties the serviceworker interface inherits properties from its parent, worker. serviceworker.scripturl read only re
turns the serviceworker serialized script url defined as part of serviceworkerregistration. the url must be on the same origin as the document that registers the serviceworker. serviceworker.state read only re
turns the state of the service worker. it re
turns one of the following values: installing, installed, activating, activated, or redundant. event handlers serviceworker.onstatechange read ...
...it is basically fired anytime the serviceworker.state changes. methods the serviceworker interface inherits methods from its parent, worker, with the exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and re
turns its value. if ('serviceworker' in navigator) { navigator.serviceworker.register('service-worker.js', { scope: './' }).then(function (registration) { var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.queryselector('#kind').textcontent = 'installing'; } else if (registration.waiting) ...
ServiceWorkerContainer.controller - Web APIs
syntax var mycontroller = navigator.serviceworker.controller; value a serviceworker object. example if ('serviceworker' in navigator) { // do a one-off check to see if a service worker's in control. ...
... syntax var mycontroller = navigator.serviceworker.controller; value a serviceworker object. example if ('serviceworker' in navigator) { // do a one-off check to see if a service worker's in control. ...
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
living standard initial definition. this property is specified on the notifications_api even though it's part of serviceworkerglobalscope. ...
... living standard initial definition. this property is specified on the notifications_api even though it's part of serviceworkerglobalscope. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
nt was defined to be sent when a pushsubscription has expired. examples this example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addeventlistener("pushsubscriptionchange", event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { re
turn fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. when t...
...h("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. when the re
turned promise is resolved, we receive the new subscription. this is delivered to the app server using a fetch() call to post a json formatted rendition of the subscription's endpoint to the app server. you can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waituntil(swregistration.pushmanager.subscribe(eve...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
obalscope.skipwaiting() method of the serviceworkerglobalscope forces the waiting service worker to become the active service worker. use this method with clients.claim() to ensure that updates to the underlying service worker take effect immediately for both the current client and all other active clients. syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); re
turns a promise that immediately resolves with undefined. example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. therefore, it's common to call self.skipwaiting() from inside of an installevent handler. the following example causes a ...
...er that might otherwise remain in the waiting state. therefore, it's common to call self.skipwaiting() from inside of an installevent handler. the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker. self.addeventlistener('install', function(event) { // the promise that skipwaiting() re
turns can be safely ignored. self.skipwaiting(); // perform any other actions required for your // service worker to install, potentially inside // of event.waituntil(); }); specifications specification status comment service workersthe definition of 'skipwaiting()' in that specification. working draft initial definition. ...
ServiceWorkerMessageEvent - Web APIs
accessed via the handler function of a message event, when fired by a message received from a service worker. this interface inherits from the event interface. constructor serviceworkermessageevent.serviceworkermessageevent() creates a new serviceworkermessageevent object instance. properties inherits properties from its parent, event. ...
...ice worker. this interface inherits from the event interface. constructor serviceworkermessageevent.serviceworkermessageevent() creates a new serviceworkermessageevent object instance. properties inherits properties from its parent, event. serviceworkermessageevent.data read only re
turns the event's data. it can be any data type. serviceworkermessageevent.origin read only re
turns the origin of the service worker's environment settings object. serviceworkermessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. serviceworkermessageevent.source read only re
turns a reference to the service worker that sent the message. serviceworkermessageevent.ports read only re
turns an array of messageport objects. meth...
SpeechGrammarList.length - Web APIs
syntax var mylistlength = speechgrammarlistinstance.length; value a number indicating the number of speechgrammar objects contained in the speechgrammarlist. ...
... specifications specification status comment web speech apithe definition of 'length' in that specification. draft ...
SpeechRecognition.interimResults - Web APIs
examples this code is excerpted from our speech color changer example. ...
... interim results are results that are not yet final (e.g. the speechrecognitionresult.isfinal property is false.) the default value for interimresults is false. syntax var myinterimresult = myspeechrecognition.interimresults; myspeechrecognition.interimresults = false; value a boolean representing the state of the current speechrecognition's interim results. true means interim results are re
turned, and false means they aren't. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | nav...
SpeechRecognition.onnomatch - Web APIs
this is being worked on. syntax myspeechrecognition.onnomatch = function() { ... ...
...this is being worked on. syntax myspeechrecognition.onnomatch = function() { ... ...
SpeechSynthesis.getVoices() - Web APIs
the getvoices() method of the speechsynthesis interface re
turns a list of speechsynthesisvoice objects representing all the available voices on the current device. syntax speechsynthesisinstance.getvoices(); parameters none. re
turn value a list (array) of speechsynthesisvoice objects. note: the spec wrongly lists this method as re
turning as a speechsynthesisvoicelist object, but this was in fact removed from the spec. ...
...es on the current device. syntax speechsynthesisinstance.getvoices(); parameters none. re
turn value a list (array) of speechsynthesisvoice objects. note: the spec wrongly lists this method as re
turning as a speechsynthesisvoicelist object, but this was in fact removed from the spec. ...
SpeechSynthesis.onvoiceschanged - Web APIs
the onvoiceschanged property of the speechsynthesis interface represents an event handler that will run when the list of speechsynthesisvoice objects that would be re
turned by the speechsynthesis.getvoices() method has changed (when the voiceschanged event fires.) this may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running. syntax speechsynthesisinstance.onvoiceschanged = function() { ... ...
...hronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running. 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 re
turn a list of voices when speechsynthesis.getvoices() is fired. with chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. var voices = []; function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].na...
SpeechSynthesis.pending - Web APIs
the pending read-only property of the speechsynthesis interface is a boolean that re
turns true if the utterance queue contains as-yet-unspoken utterances. syntax var amipending = speechsynthesisinstance.pending; value a boolean. ...
...ending; value a boolean. examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now? this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amipending = synth.pending; // will re
turn true if utterance 1 is still being spoken and utterance 2 is in the queue specifications specification status comment web speech apithe definition of 'pending' in that specification. draft ...
SpeechSynthesis.speaking - Web APIs
the speaking read-only property of the speechsynthesis interface is a boolean that re
turns true if an utterance is currently in the process of being spoken — even if speechsynthesis is in a paused state. syntax var amispeaking = speechsynthesisinstance.speaking; value a boolean. ...
...king; value a boolean. examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now? this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amispeaking = synth.speaking; // will re
turn true if utterance 1 or utterance 2 are currently being spoken specifications specification status comment web speech apithe definition of 'speaking' in that specification. draft ...
SpeechSynthesisVoice.voiceURI - Web APIs
the voiceuri read-only property of the speechsynthesisvoice interface re
turns the type of uri and location of the speech synthesis service for this voice. syntax var myvoiceuri = speechsynthesisvoiceinstance.voiceuri; value a domstring representing the uri of the voice. this is a generic uri and can point to local or remote services, e.g. it could be a proprietary system urn or a a url to a remote service. ...
...t to local or remote services, e.g. it could be a proprietary system urn or a a url to a remote service. examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } console.log(voices[i].voiceuri); // on mac, this re
turns urns, for example 'urn:moz-tts:osx:com.apple.speech.synthesis.voice.daniel' option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition of 'voiceuri' in that specification. draft ...
StorageManager.estimate() - Web APIs
the estimate() method of the storagemanager interface asks the storage manager for how much storage the current origin takes up (usage), and how much space is available (quota). this method operates asynchronously, so it re
turns a promise which resolves once the information is available. the promise's fulfillment handler is called with a storageestimate containing the usage and quota data. syntax const estimatepromise = storagemanager.estimate(); parameters none. re
turn value a promise that resolves to an object which conforms to the storageestimate dictionary. ...
... you may find that the quota varies from origin to origin. ...
StylePropertyMapReadOnly.get() - Web APIs
the get() method of the stylepropertymapreadonly interface re
turns a cssstylevalue object for the first value of the specified property. syntax var declarationblock = stylepropertymapreadonly.get(property) parameters property the name of the property to retrieve the value of. re
turn value a cssstylevalue object. examples let's get just a few properties and values. ...
...we create an array of properties of interest and use the stylepropertymapreadonly's get() method to get only those values. // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const stylemap = my...
StylePropertyMapReadOnly.keys() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
... example // tbd specifications specification status comment css typed om level 1the definition of 'keys()' in that specification. ...
Stylesheet.href - Web APIs
for inline style sheets, the value of this attribute is null. ...
...ef parameters uri is a string containing the stylesheet's uri. example // on a local machine: <html> <head> <link rel="stylesheet" href="example.css" type="text/css" /> <script> function sref() { alert(document.stylesheets[0].href); } </script> </head> <body> <div class="thunder">thunder</div> <button onclick="sref()">ss</button> </body> </html> // re
turns "file:////c:/windows/desktop/example.css notes if the style sheet is a linked style sheet, the value of its attribute is its location. for inline style sheets, the value of this attribute is null. this property is read-only in firefox, opera, google chrome, and safari, and it is read/write in internet explorer. specifications specification status comment css obj...
SubmitEvent() - Web APIs
examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it. next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). ...
... examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it. next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). ...
SyncEvent - Web APIs
methods inherits methods from its parent, extendableevent. none. ...
...text-anchor="middle" alignment-baseline="middle">syncevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor syncevent.syncevent() creates a new syncevent object. properties inherits properties from its ancestor, event. syncevent.tag read only re
turns the developer-defined identifier for this syncevent. syncevent.lastchance read only re
turns true if the user agent will not make further synchronization attempts after the current attempt. methods inherits methods from its parent, extendableevent. none. ...
Text.splitText() - Web APIs
the text.splittext() method breaks the text node into two nodes at the specified offset, keeping both nodes in the tree as siblings. after the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text. the newly created node is re
turned to the caller. if the original node had a parent, the new node is inserted as the next sibling of the original node. ...
...original node had a parent, the new node is inserted as the next sibling of the original node. if the offset is equal to the length of the original node, the newly created node has no data. separated text nodes can be concatenated using the node.normalize() method. syntax newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node. re
turn value re
turns a newly created text node that contains the text after the specified offset point. exceptions thrown a domexception with a value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a domexception with a value of no_modification_allowed_err is thrown if the node is read-only. example in this example, t...
Text.wholeText - Web APIs
the text is concatenated in document order. this allows to specify any text node and obtain all adjacent text as a single string. ...
...refer to treat all those adjacent text nodes as a single one. that’s where wholetext comes in: if you have multiple adjacent text nodes, you can access the contents of all of them using wholetext. let’s pretend you never made that last mistake. in that case, we have: assert(para.firstchild.wholetext == "thru-hiking is great! however, "); wholetext is just a property of text nodes that re
turns the string of data making up all the adjacent (i.e. not separated by an element boundary) text nodes combined. now let’s re
turn to our original problem. what we want is to be able to replace the whole text with new text. that’s where replacewholetext() comes in: para.firstchild.replacewholetext("thru-hiking is great, but "); we’re removing every adjacent text node (all the ones that co...
Text - Web APIs
s/web/api/text" target="_top"><rect x="436" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="473.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">text</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor text() re
turns a text node with the parameter as its textual content. properties inherits properties from its parent, characterdata. text.iselementcontentwhitespace read only re
turns a boolean flag indicating whether or not the text node contains only whitespace. text.wholetext read only re
turns a domstring containing the text of all text nodes logically adjacent to this node, concatenated in d...
...content. properties inherits properties from its parent, characterdata. text.iselementcontentwhitespace read only re
turns a boolean flag indicating whether or not the text node contains only whitespace. text.wholetext read only re
turns a domstring containing the text of all text nodes logically adjacent to this node, concatenated in document order. text.assignedslot read only re
turns the htmlslotelement object associated with the element. properties included from slotable the text interface includes the following property, defined on the slotable mixin. slotable.assignedslot read only re
turns a htmlslotelement representing the <slot> the node is inserted in. methods inherits methods from its parent, characterdata. text.replacewholetext replaces the text o...
TextDecoder - Web APIs
!", which means "hello, world." in our textdecoder() constructor, we specify the windows-1251 character encoding, which is appropriate for cyrillic script. let win1251decoder = new textdecoder('windows-1251'); let bytes = new uint8array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир! constructor textdecoder() re
turns a newly constructed textdecoder that will generate a code point stream with the decoding method specified in parameters. properties the textdecoder interface doesn't inherit any properties. textdecoder.prototype.encodingread only is a domstring containing the name of the decoder, that is a string describing the method the textdecoder will use. textdecoder.prototype.fatalread only is a...
... the name of the decoder, that is a string describing the method the textdecoder will use. textdecoder.prototype.fatalread only is a boolean indicating whether the error mode is fatal. textdecoder.prototype.ignorebomread only is a boolean indicating whether the byte order marker is ignored. methods the textdecoder interface doesn't inherit any method. textdecoder.prototype.decode() re
turns a domstring containing the text decoded with the method of the specific textdecoder object. specifications specification status comment encodingthe definition of 'textdecoder' in that specification. living standard initial definition. ...
Touch.force - Web APIs
in environments where force is known, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary. example this example illustrates using the touch interface's touch.force property. ...
...in environments where force is known, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary. example this example illustrates using the touch interface's touch.force property. ...
Touch.identifier - Web APIs
example someelement.addeventlistener('touchmove', function(e) { // iterate through the list of touch points that changed // since the last event and print each touch point's identifier. ...
... example someelement.addeventlistener('touchmove', function(e) { // iterate through the list of touch points that changed // since the last event and print each touch point's identifier. ...
Touch.radiusY - Web APIs
summary re
turns the y radius of the ellipse that most closely circumscribes the area of contact with the touch surface. the value is in css pixels of the same scale as touch.screenx. this value, in combination with touch.radiusx and touch.rotationangle constructs an ellipse that approximates the size and shape of the area of contact between the user and the screen. this may be a large ellipse representing the contact between a fingertip and the screen or a small one representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. ...
...ay be a large ellipse representing the contact between a fingertip and the screen or a small one representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. syntax var yradius = touchitem.radiusy; re
turn value yradius the y radius of the ellipse that most closely circumscribes the area of contact with the screen. example the touch.radiusx example includes an example of this property's usage. specifications specification status comment touch events – level 2 draft non-stable version. ...
Touch.rotationAngle - Web APIs
summary re
turns the rotation angle, in degrees, of the contact area ellipse defined by touch.radiusx and touch.radiusy. the value may be between 0 and 90. together, these three values describe an ellipse that approximates the size and shape of the area of contact between the user and the screen. this may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. ...
...ly large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example. note: this attribute has not been formally standardized. it is specified in the touch events – level 2 draft specification and not in touch events recommendation. this attribute is not widely implemented. syntax var angle = touchitem.rotationangle; re
turn value angle the number of degrees of rotation to apply to the described ellipse to align with the contact area between the user and the touch surface. example the touch.radiusx example includes an example of this property's usage. specifications specification status comment touch events – level 2 draft non-stable version. ...
Touch.target - Web APIs
example this example illustrates how to access the touch object's touch.target property. ...
...ven been removed from the document. note that if the target element is removed from the document, events will still be targeted at it, and hence won't necessarily bubble up to the window or document anymore. if there is any risk of an element being removed while it is being touched, the best practice is to attach the touch listeners directly to the target. syntax var el = touchpoint.target; re
turn value el the target element of the touch object. example this example illustrates how to access the touch object's touch.target property. the touch.target property is an element (eventtarget) on which a touch point is started when contact is first placed on the surface. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element. when th...
TouchEvent.targetTouches - Web APIs
the targettouches read-only property is a touchlist listing all the touch objects for touch points that are still in contact with the touch surface and whose touchstart event occurred inside the same target element as the current target element. syntax var touches = touchevent.targettouches; re
turn value touches a touchlist listing all the touch objects for touch points that are still in contact with the touch surface and whose touchstart event occurred inside the same target element as the current target element. example this example illustrates the touchevent object's touchevent.targettouches property. the touchevent.targettouches property is a touchlist object that includes those tps that are currently touching the surface and started on the element that is the target of the cur...
...rty. the touchevent.targettouches property is a touchlist object that includes those tps that are currently touching the surface and started on the element that is the target of the current event. as such, the targettouches list is a strict subset of the touches list. in following code snippet, the function compares the length of the touches list to the the length of the targettouches list and re
turns true if the lengths are the same and re
turns false otherwise. function touches_in_target(ev) { // re
turn true if all of the touches are within the target element; // otherwise re
turn false. re
turn (ev.touches.length == ev.targettouches.length ? true : false); } specifications specification status comment touch events – level 2 draft non-stable version. ...
TrackEvent() - Web APIs
syntax trackevent = new trackevent(type, eventinfo); parameters type the type of track event which is described by the object: "addtrack" or "removetrack". eventinfo optional an optional dictionary providing additional information configuring the new event; it can contain the following fields in any combination: track optional the track to which the event refers; this is null by default, but should be set to a videotrack, audiotrack, or texttrack as appropriate given the type of track. ...
...deotrack, audiotrack, or texttrack as appropriate given the type of track. bubbles optional a boolean indicating whether the event bubbles or not. cancelable optional a boolean indicating whether or not the event can be canceled. composed optional a boolean indicating whether or not the event will trigger listeners outside of a shadow root; see event.composed for more details. re
turn value a newly-created trackevent object, initialized as described by the inputs to the constructor. specifications specification status comment html living standardthe definition of 'trackevent()' in that specification. living standard initial definition. html5the definition of 'trackevent()' in that specification. recommendation initial definition.
TreeWalker.expandEntityReferences - Web APIs
the treewalker.expandentityreferences read-only property re
turns a boolean flag indicating whether or not the children of entity reference nodes are visible to the treewalker. if this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the treewalker.whattoshow method and the associated filter. ...
...alue is false, the children of entity reference nodes (as well as all of their descendants) are rejected. this takes precedence over the value of the treewalker.whattoshow method and the associated filter. syntax expand = treewalker.expandentityreferences; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); expand = treewalker.expandentityreferences; specifications document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.expandentityreferences' in that specification. obsolete initial definition. ...
TreeWalker.root - Web APIs
living standard no change from document object model (dom) level 2 traversal and range specification document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.root' in that specification. ...
... living standard no change from document object model (dom) level 2 traversal and range specification document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.root' in that specification. ...
TreeWalker.whatToShow - Web APIs
non-matching nodes are skipped, but their children may be included, if relevant. the possible values are: constant numerical value description nodefilter.show_all -1 (that is the max value of unsigned long) shows all nodes. nodefilter.show_attribute 2 shows attribute attr nodes. this is meaningful only when creating a treewalker with an attr node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. ...
...ocument tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. syntax nodetypes = treewalker.whattoshow; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); if( (treewalker.whattoshow == nodefilter.show_all) || (treewalker.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // treewalker will show comments } specifications specification status comment domthe definition of 'treewalker.whattoshow' in that specification. living standard no change fro...
UIEvent.isChar - Web APIs
it is used when event handlers need to do something like echo the input on the screen. example in this snippet, which is part of an event handler, the event is checked to see if it generates a character; if it does, the value of uievent.which is appended to a string which buffers the typed characters. ...
...it is used when event handlers need to do something like echo the input on the screen. example in this snippet, which is part of an event handler, the event is checked to see if it generates a character; if it does, the value of uievent.which is appended to a string which buffers the typed characters. ...
URL.origin - Web APIs
note: this feature is available in web workers. syntax const originstring = url.origin value a usvstring. ...
...act structure varies depending on the type of url: for http or https urls, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified). for file: urls, the value is browser dependant. for blob: urls, the origin of the url following blob: will be used, e.g "blob:https://mozilla.org" will be re
turned as "https://mozilla.org". note: this feature is available in web workers. syntax const originstring = url.origin value a usvstring. examples const url = new url("blob:https://mozilla.org:443/") console.log(url.origin); // logs 'https://mozilla.org' specifications specification status comment urlthe definition of 'url.origin' in that specification. living s...
URLSearchParams() - Web APIs
examples the following example shows how to create a urlsearchparams object from a url string. ...
...urlsearchparams object. note: this feature is available in web workers. syntax var urlsearchparams = new urlsearchparams(init); parameters init optional one of: a usvstring, which will be parsed from application/x-www-form-urlencoded format. a leading '?' character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. re
turn value a urlsearchparams object instance. examples the following example shows how to create a urlsearchparams object from a url string. // retrieve params via url.search, passed into ctor var url = new url('https://example.com?foo=1&bar=2'); var params = new urlsearchparams(url.search); // pass in a string literal var params2 = new urlsearchparams("foo=1&bar=2"); var params2a = new urlsearch...
URLSearchParams.get() - Web APIs
the get() method of the urlsearchparams interface re
turns the first value associated to the given search parameter. note: this feature is available in web workers. syntax urlsearchparams.get(name) parameters name the name of the parameter to re
turn. re
turn value a usvstring if the given search parameter is found; otherwise, null. ...
... living standard initial definition. ...
URLSearchParams.set() - Web APIs
the value associated with a given search parameter to the given value. if there were several matching values, this method deletes the others. if the search parameter doesn't exist, this method creates it. note: this feature is available in web workers. syntax urlsearchparams.set(name, value) parameters name the name of the parameter to set. value the value of the parameter to set. re
turn value void. examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter. params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters. you can copy and paste the example in a...
...rl.searchparams.set( 'expression', rexp.tostring() ) theurl.searchparams.set( 'tool', 'replace' ) theurl.searchparams.set( 'input', '\u2911\u20dc' )// ⤑⃜ theurl.searchparams.set( 'text', atext.join('\n') ) if( bdebug ){ // display the key/value pairs for(var pair of theurl.searchparams.entries()) { console.debug(pair[0] + ' = \'' + pair[1] + '\''); } console.debug(theurl) } re
turn theurl } var url = genurl( /(^\s*\/\/|\s*[^:]\/\/).*\s*$|\s*\/\*(.|\n)+?\*\/\s*$/gm // single/multi-line comments // /(^\s*\/\/.*|\s*[^:]\/\/.*)/g // single-line comments ,[ "these should work:", "", "// eslint-disable-next-line no-unused-vars", "lockpref( 'keyword.url',\t\t'https://duckduckgo.com/html/?q=!+' )\t// test", "/*", " * bla bla ", "*/", "", "/* bla ...
URLUtilsReadOnly.host - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URLUtilsReadOnly.hostname - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URLUtilsReadOnly.href - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
URLUtilsReadOnly.pathname - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
URLUtilsReadOnly.protocol - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URLUtilsReadOnly.search - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URLUtilsReadOnly.toString() - Web APIs
if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
USB.getDevices() - Web APIs
example the following example logs the product name and serial number of paired devices to the console. for information on pairing devices, see usb.requestdevice(). ...
... example the following example logs the product name and serial number of paired devices to the console. for information on pairing devices, see usb.requestdevice(). ...
USB.requestDevice() - Web APIs
example the following example looks for one of two usb devices. notice that two product ids are specified. both are passed to requestdevice(). ...
... an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. syntax usb.requestdevice([filters]) parameters filters an array of filter objects for possible devices you would like to pair. each filter object can have the following properties: vendorid productid classcode subclasscode protocolcode serialnumber re
turn value a promise that resolves with an instance of usbdevice. example the following example looks for one of two usb devices. notice that two product ids are specified. both are passed to requestdevice(). this triggers a user-agent flow that prompts the user to select a device for pairing. only the selected device is passed to then(). the number of filters does not specifiy the number of devic...
USBConfiguration - Web APIs
rface of the webusb api provides information about a particular configuration of a usb device and the interfaces that it supports. constructor usbconfiguration.usbconfiguration() creates a new usbconfiguration object which contains information about the configuration on the provided usbdevice with the given configuration value. properties usbconfiguration.configurationvalueread only re
turns the configuration value of this configuration. this is equal to the bconfigurationvalue field of the configuration descriptor provided by the device defining this configuration. usbconfiguration.configurationnameread only re
turns the name provided by the device to describe this configuration. this is equal to the value of the string descriptor with the index provided in the iconfiguration fie...
...figuration descriptor provided by the device defining this configuration. usbconfiguration.configurationnameread only re
turns the name provided by the device to describe this configuration. this is equal to the value of the string descriptor with the index provided in the iconfiguration field of the configuration descriptor defining this configuration. usbconfiguration.interfacesread only re
turns an array containing instances of the usbinterface describing each interface supported by this configuration. specifications specification status comment webusbthe definition of 'usbconfiguration' in that specification. draft initial definition. ...
USBDevice.claimInterface() - Web APIs
example the following example shows claiminterface() in the context of connecting to a usb device. ...
... example the following example shows claiminterface() in the context of connecting to a usb device. ...
USBDevice.controlTransferIn() - Web APIs
syntax var promise = usbdevice.controltransferin(setup, length) parameters setup an object that sets options for . the available options are: requesttype: must be one of three values specifying whether the tranfer is "standard" (common to all usb devices) "class" (common to an industry-standard class of devices) or "vendor". recipient: specifices the target of the transfer on the device, one of "device", "interface", "endpoint", or "other". request: a vendor-specific command. ...
...endor". recipient: specifices the target of the transfer on the device, one of "device", "interface", "endpoint", or "other". request: a vendor-specific command. value: vender-specific request parameters. index: the interface number of the recipient. length the maximum number of bytes to read from the device. the actual data is in the usbintransferresult in the resolved promise. re
turn value promise that resolves with a usbintransferresult. specifications specification status comment webusbthe definition of 'controltransferin()' in that specification. draft initial definition. ...
USBDevice.controlTransferOut() - Web APIs
syntax var promise = usbdevice.controltransferout(setup, data) parameters setup an object that sets options for . the available options are: requesttype: must be one of three values specifying whether the tranfer is "standard" (common to all usb devices) "class" (common to an industry-standard class of devices) or "vendor". recipient: specifices the target of the transfer on the device, one of "device", "interface", "endpoint", or "other". request: a vendor-specific command. value: vender-specific request parameters. ...
...endpoint", or "other". request: a vendor-specific command. value: vender-specific request parameters. index: the interface number of the recipient. data a typedarray containing the data that will be transfered to the device. not all commands require data; some commands can send data just through the value parameter. check with your device to see what the specific request requires. re
turn value a promise that resolves with a usbouttransferresult. specifications specification status comment webusbthe definition of 'controltransferout()' in that specification. draft initial definition. ...
USBInterface - Web APIs
face represents a feature of the device which implements a particular protocol and may contain endpoints for bidirectional communication. constructor usbinterface.usbinterface creates a new usbinterface object which will be populated with information about the interface on the provided usbconfiguration with the given interface number. properties usbinterface.interfacenumberread only re
turns the interface number of this interface. this is equal to the binterfacenumber field of the interface descriptor defining this interface. usbinterface.alternateread only re
turns the currently selected alternative configuration of this interface. by default this is the usbalternateinterface from alternates with alternatesetting equal to 0. it can be changed by calling usbdevice.selectalternatei...
...e interface descriptor defining this interface. usbinterface.alternateread only re
turns the currently selected alternative configuration of this interface. by default this is the usbalternateinterface from alternates with alternatesetting equal to 0. it can be changed by calling usbdevice.selectalternateinterface() with any other value found in alternates. usbinterface.alternatesread only re
turns an array containing instances of the usbalternateinterface interface describing each of the alternative configurations possible for this interface. usbinterface.claimedread only re
turns whether or not this interface has been claimed by the current page by calling usbdevice.claiminterface(). specifications specification status comment webusbthe definition of 'usbinte...
USBIsochronousInTransferResult - Web APIs
he isochronoustransferin() method of the usbdevice interface. it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbisochronousintransferresult.usbisochronousintransferresult() creates a new usbisochronousintransferresult object with the provided packets and data fields. ...
...ct with the provided packets and data fields. properties usbisochronousintransferresult.dataread only re
turns a dataview object containing the data received from the device. this is the combined data from all packets. see the individual dataview objects in the packets array for the portion of this buffer containing data from each packet. usbisochronousintransferresult.packetsread only re
turns an array of usbisochronousintransferpacket objects containing the result of each request to receive a packet from the device. specifications specification status comment webusbthe definition of 'usbisochronousintransferresult' in that specification. draft initial definition. ...
VTTCue() - Web APIs
syntax vttcue = new vttcue(starttime, endtime, text); parameters starttime this is a double representing the initial text track cue start time. this is the time, given in seconds and fractions of a second, denoting the beginning of the range of the media data to which this cue applies. for example, if a cue is to be visible from 50 seconds to a one minute, five and a half seconds in the media's playback, starttime will be 50.0. endtime this is a double representing the ending time for this text track cue. this is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. ...
... endtime this is a double representing the ending time for this text track cue. this is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. given the example cue mentioned under starttime, the value of endtime would be 65.5. text a domstring providing the text that will be shown during the time span indicated by starttime and endtime. re
turn value a new vttcue object representing a cue which will be presented during the time span given. example // create a cue that is shown from 2 to 3 seconds and uses the given text. var cue = new vttcue(2, 3, 'cool text to be displayed'); specifications specification status comment webvtt: the web video text tracks formatthe definition of 'vttcue()' in that specificatio...
VideoTrack - Web APIs
ack whose kind is "sign" might have a label of "a sign-language interpretation". this string is empty if no label is provided. language read only a domstring specifying the video track's primary language, or an empty string if unknown. the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. ...
...rfc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. re
turns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get a videotrack for a given media element, use the element's videotracks property, which re
turns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach(). this first example gets the first video track on the media: var firsttrack = tracks[0]; the next example scans through a...
WakeLock.request() - Web APIs
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. ...
... 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. ...
WakeLockSentinel.type - Web APIs
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. ...
...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. ...
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
uniform block within a webglprogram. syntax any gl.getactiveuniformblockparameter(program, uniformblockindex, pname); parameters program a webglprogram containing the active uniform block. uniformblockindex a gluint specifying the index of the active uniform block within the program. pname a glenum specifying which information to query. possible values: gl.uniform_block_binding: re
turns a gluint indicating the uniform buffer binding point. gl.uniform_block_data_size: re
turns a gluint indicating the minimum total buffer object size. gl.uniform_block_active_uniforms: re
turns a gluint indicating the number of active uniforms in the uniform block. gl.uniform_block_active_uniform_indices: re
turns a uint32array indicating the list of active uniforms in the uniform block. gl.u...
...ding point. gl.uniform_block_data_size: re
turns a gluint indicating the minimum total buffer object size. gl.uniform_block_active_uniforms: re
turns a gluint indicating the number of active uniforms in the uniform block. gl.uniform_block_active_uniform_indices: re
turns a uint32array indicating the list of active uniforms in the uniform block. gl.uniform_block_referenced_by_vertex_shader: re
turns a glboolean indicating whether the uniform block is referenced by the vertex shader. gl.uniform_block_referenced_by_fragment_shader: re
turns a glboolean indicating whether the uniform block is referenced by the fragment shader. re
turn value depends on which information is requested using the pname parameter. if an error occurs, null is re
turned. examples var blocksize = gl.getactiveun...
WebGL2RenderingContext.getFragDataLocation() - Web APIs
examples // program is a linked webglprogram gl.getfragdatalocation(program, 'fragcolor'); specifications specification status comment webgl 2.0the definition of 'getfragdatalocation' in that specification. editor's draft initial definition. ...
... examples // program is a linked webglprogram gl.getfragdatalocation(program, 'fragcolor'); specifications specification status comment webgl 2.0the definition of 'getfragdatalocation' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
the webgl2renderingcontext.getinternalformatparameter() method of the webgl 2 api re
turns information about implementation-dependent support for internal formats. syntax any gl.getinternalformatparameter(target, internalformat, pname); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. internalformat a glenum specifying the internal format about which to retrieve information (must be a color-renderable, depth-renderable or stencil-renderable format). pname a glenum specifying the type of information to query. possible values: gl.samples: re
turns a int32array containing sample counts supported for internalformat in descending order. ...
...enderable internal format. internalformat a glenum specifying the internal format about which to retrieve information (must be a color-renderable, depth-renderable or stencil-renderable format). pname a glenum specifying the type of information to query. possible values: gl.samples: re
turns a int32array containing sample counts supported for internalformat in descending order. re
turn value depends on the requested information (as specified with pname). it is an int32array if pname is gl.samples. examples var samples = gl.getinternalformatparameter(gl.renderbuffer, gl.rgba8, gl.samples); specifications specification status comment webgl 2.0the definition of 'getinternalformatparameter' in that specificat...
WebGL2RenderingContext.getSyncParameter() - Web APIs
the webgl2renderingcontext.getsyncparameter() method of the webgl 2 api re
turns parameter information of a webglsync object. syntax any gl.getsyncparameter(sync, pname); parameters sync a webglsync object. pname a glenum specifying which information to re
turn. possible values: gl.object_type: re
turns a glenum indicating the type of the sync object (always gl.sync_fence). gl.sync_status: re
turns a glenum indicating the status of the sync object (gl.signaled or gl.unsignaled). gl.sync_condition: re
turns a glenum indicating the sync objects' condition (always gl.sync_gpu_commands_complete). ...
...pecifying which information to re
turn. possible values: gl.object_type: re
turns a glenum indicating the type of the sync object (always gl.sync_fence). gl.sync_status: re
turns a glenum indicating the status of the sync object (gl.signaled or gl.unsignaled). gl.sync_condition: re
turns a glenum indicating the sync objects' condition (always gl.sync_gpu_commands_complete). gl.sync_flags: re
turns a glenum indicating the flags with which the sync object was created (always 0 as no flags are supported). re
turn value depends on the pname parameter, either a glenum or a glbitfield. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.getsyncparameter(sync, gl.sync_status); specifications specification status comment webgl 2.0the definitio...
WebGL2RenderingContext.getTransformFeedbackVarying() - Web APIs
examples activeinfo = gl.gettransformfeedbackvarying(program, 0); specifications specification status comment webgl 2.0the definition of 'gettransformfeedbackvarying' in that specification. editor's draft initial definition for webgl. ...
... examples activeinfo = gl.gettransformfeedbackvarying(program, 0); specifications specification status comment webgl 2.0the definition of 'gettransformfeedbackvarying' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.isTransformFeedback() - Web APIs
examples gl must be a webgl2renderingcontext. webgltransformfeedback objects are not available in webgl 1. var transformfeedback = gl.createtransformfeedback(); // ... ...
... examples gl must be a webgl2renderingcontext. webgltransformfeedback objects are not available in webgl 1. var transformfeedback = gl.createtransformfeedback(); // ... ...
WebGL2RenderingContext.isVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... gl.isvertexarray(vao); specifications specification status comment webgl 2.0the definition of 'isvertexarray' in that specification. editor's draft initial definition. ...
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... gl.isvertexarray(vao); specifications specification status comment webgl 2.0the definition of 'isvertexarray' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
syntax void gl.renderbufferstoragemultisample(target, samples, internalformat, width, height); parameters target a glenum specifying the target renderbuffer object. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. samples a glsizei specifying the number of samples to be used for the renderbuffer storage. internalformat a glenum specifying the internal format of the renderbuffer. ...
... gl.rgba8ui gl.rgba8i gl.rgb10_a2ui gl.rgba16ui gl.rgba16i gl.rgba32i gl.rgba32ui gl.depth_component16 gl.depth_component24 gl.depth_component32f gl.depth_stencil gl.depth24_stencil8 gl.depth32f_stencil8 gl.stencil_index8 width a glsizei specifying the width of the renderbuffer in pixels. height a glsizei specifying the height of the renderbuffer in pixels. re
turn value none. examples gl.renderbufferstoragemultisample(gl.renderbuffer, 4, gl.rbga4, 256, 256); specifications specification status comment webgl 2.0the definition of 'glrenderbufferstoragemultisample' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glrenderbufferstoragemultisample' in that specificat...
WebGLActiveInfo - Web APIs
the webglactiveinfo interface is part of the webgl api and represents the information re
turned by calling the webglrenderingcontext.getactiveattrib() and webglrenderingcontext.getactiveuniform() methods. properties webglactiveinfo.name the read-only name of the requested variable. webglactiveinfo.size the read-only size of the requested variable. webglactiveinfo.type the read-only type of the requested variable. ...
...ts the information re
turned by calling the webglrenderingcontext.getactiveattrib() and webglrenderingcontext.getactiveuniform() methods. properties webglactiveinfo.name the read-only name of the requested variable. webglactiveinfo.size the read-only size of the requested variable. webglactiveinfo.type the read-only type of the requested variable. ...
WebGLRenderingContext.activeTexture() - Web APIs
the webglrenderingcontext.activetexture() method of the webgl api specifies which texture unit to make active. syntax void gl.activetexture(texture); parameters texture the texture unit to make active. the value is a gl.texturei where i is within the range from 0 to gl.max_combined_texture_image_units - 1. re
turn value none. exceptions if texture is not one of gl.texturei, where i is within the range from 0 to gl.max_combined_texture_image_units - 1, a gl.invalid_enum error is thrown. examples the following call selects gl.texture1 as the current texture. subsequent calls that modify the texture state will affect this texture. gl.activetexture(gl.texture1); the number of texture units is implementation dependent, you can get this number with the help of the max_combined_text...
...etexture(gl.texture1); the number of texture units is implementation dependent, you can get this number with the help of the max_combined_texture_image_units constant. it is, per specification, at least 8. gl.getparameter(gl.max_combined_texture_image_units); to get the active texture, query the active_texture constant. gl.activetexture(gl.texture0); gl.getparameter(gl.active_texture); // re
turns "33984" (0x84c0, gl.texture0 enum value) specifications specification status comment webgl 1.0the definition of 'activetexture' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glactivetexture' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.blendEquation() - Web APIs
urce and destination, ext.max_ext: maximum of source and destination. when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. default value: gl.func_add exception if mode is not one of the three possible values, a gl.invalid_enum error is thrown. ...
...nc_add exception if mode is not one of the three possible values, a gl.invalid_enum error is thrown. re
turn value none. examples to set the blend equation, use: gl.blendequation(gl.func_add); gl.blendequation(gl.func_subtract); gl.blendequation(gl.func_reverse_subtract); to get the blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which re
turn gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is enabled: ext.min_ext or ext.max_ext. gl.getparameter(gl.blend_equation_rgb) === gl.func_add; // true gl.getparameter(gl.blend_equation_alpha) === gl.func_add; // true specifications specification status comment webgl 1.0the definition of 'blendequation' in that specification. rec...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
.func_reverse_subtract: destination - source, when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: maximum of source and destination. when using a webgl 2 context, the following values are available additionally: gl.min: minimum of source and destination, gl.max: maximum of source and destination. ...
...l.max: maximum of source and destination. re
turn value none. exceptions if mode is not one of the three possible values, a gl.invalid_enum error is thrown. examples to set the blend equations, use: gl.blendequationseparate(gl.func_add, gl.func_subtract); to get the current blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which re
turn gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is enabled: ext.min_ext or ext.max_ext. gl.getparameter(gl.blend_equation_rgb) === gl.func_add; // true gl.getparameter(gl.blend_equation_alpha) === gl.func_add; // true specifications specification status comment webgl 1.0the definition of 'blendequationseparate' in that specification...
WebGLRenderingContext.blendFunc() - Web APIs
which function is used for blending pixel arithmetic. syntax void gl.blendfunc(sfactor, dfactor); parameters sfactor a glenum specifying a multiplier for the source blending factors. the default value is gl.one. for possible values, see below. dfactor a glenum specifying a multiplier for the destination blending factors. the default value is gl.zero. for possible values, see below. re
turn value none. exceptions if sfactor or dfactor is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source and destination factors, a gl.invalid_enum error is thrown. constants the following constants can be used for sfactor and dfactor. the formula for the blending color can be described like this...
...estination alpha value. the alpha value is multiplied by 1. examples to use the blend function, you first have to activate blending with webglrenderingcontext.enable() with the argument gl.blend. gl.enable(gl.blend); gl.blendfunc(gl.src_color, gl.dst_color); to get the current blend function, query the blend_src_rgb, blend_src_alpha, blend_dst_rgb, and blend_dst_alpha constants which re
turn one of the blend function constants. gl.enable(gl.blend); gl.blendfunc(gl.src_color, gl.dst_color); gl.getparameter(gl.blend_src_rgb) == gl.src_color; // true specifications specification status comment webgl 1.0the definition of 'blendfunc' in that specification. recommendation initial definition. in webgl, constant color and constant alpha cannot be used to...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
blue (rgb) destination blending factors. the default value is gl.zero. for possible values, see below. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see below. dstalpha a glenum specifying a multiplier for the alpha destination blending factor. the default value is gl.zero. for possible values, see below. re
turn value none. exceptions if srcrgb, dstrgb, srcalpha, or dstalpha is not one of the listed possible values, a gl.invalid_enum error is thrown. if a constant color and a constant alpha value are used together as source (srcrgb) and destination (dstrgb) factors, a gl.invalid_enum error is thrown. constants the following constants can be used for srcrgb, dstrgb, srcalpha, and dstalpha the fo...
...he alpha value is multiplied by 1. examples to use the blend function, you first have to activate blending with webglrenderingcontext.enable() with the argument gl.blend. gl.enable(gl.blend); gl.blendfuncseparate(gl.src_color, gl.dst_color, gl.one, gl.zero); to get the current blend function, query the blend_src_rgb, blend_src_alpha, blend_dst_rgb, and blend_dst_alpha constants which re
turn one of the blend function constants. gl.enable(gl.blend); gl.blendfuncseparate(gl.src_color, gl.dst_color, gl.one, gl.zero); gl.getparameter(gl.blend_src_rgb) == gl.src_color; // true specifications specification status comment webgl 1.0the definition of 'blendfunc' in that specification. recommendation initial definition. in webgl, constant color and constan...
WebGLRenderingContext.disableVertexAttribArray() - Web APIs
examples gl.disablevertexattribarray(0); specifications specification status comment webgl 1.0the definition of 'disablevertexattribarray' in that specification. recommendation initial definition. ...
... examples gl.disablevertexattribarray(0); specifications specification status comment webgl 1.0the definition of 'disablevertexattribarray' in that specification. recommendation initial definition. ...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
you can disable the attribute array by calling disablevertexattribarray(). in webgl, values that apply to a specific vertex are stored in attributes. these are only available to the javascript code and the vertex shader. attributes are referenced by an index number into the list of attributes maintained by the gpu. some vertex attribute indices may have predefined purposes, depending on the platform and/or the gpu. others are assigned by the webgl layer when you create the attributes. ...
... methods can be used to access the attribute, including vertexattribpointer(), vertexattrib*(), and getvertexattrib(). syntax void gl.enablevertexattribarray(index); parameters index a gluint specifying the index number that uniquely identifies the vertex attribute to enable. if you know the name of the attribute but not its index, you can get the index by calling getattriblocation(). re
turn value undefined. errors to check for errors after calling enablevertexattribarray(), call geterror(). webglrenderingcontext.invalid_value the specified index is invalid; that is, it's greater than or equal to the maximum number of entries permitted in the context's vertex attribute list, as indicated by the value of webglrenderingcontext.max_vertex_attribs. example this code — a snipp...
WebGLRenderingContext.getContextAttributes() - Web APIs
the webglrenderingcontext.getcontextattributes() method re
turns a webglcontextattributes object that contains the actual context parameters. might re
turn null, if the context is lost. syntax gl.getcontextattributes(); re
turn value a webglcontextattributes object that contains the actual context parameters, or null if the context is lost. ...
...l.getcontextattributes(); re
turn value a webglcontextattributes object that contains the actual context parameters, or null if the context is lost. ...
WebGLRenderingContext.getError() - Web APIs
the value of this constant is 0. gl.invalid_enum an unacceptable value has been specified for an enumerated argument. the command is ignored and the error flag is set. gl.invalid_value a numeric argument is out of range. the command is ignored and the error flag is set. gl.invalid_operation the specified command is not allowed for the current state. the command is ignored and the error flag is set. ...
...nd is not allowed for the current state. the command is ignored and the error flag is set. gl.invalid_framebuffer_operation the currently bound framebuffer is not framebuffer complete when trying to render to or to read from it. gl.out_of_memory not enough memory is left to execute the command. gl.context_lost_webgl if the webgl context is lost, this error is re
turned on the first call to geterror. afterwards and until the context has been restored, it re
turns gl.no_error. examples gl.geterror(); // gl.no_error (0) gl.enable(gl.foobar); gl.geterror(); // gl.invalid_enum; specifications specification status comment webgl 1.0the definition of 'geterror' in that specification. recommendation initial definition. ...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
syntax any gl.getframebufferattachmentparameter(target, attachment, pname); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. ...
...ent_red_size gl.framebuffer_attachment_stencil_size gl.framebuffer_attachment_texture_layer when using the ovr_multiview2 extension: ext.framebuffer_attachment_texture_num_views_ovr: the number of views of the framebuffer object attachment. ext.framebuffer_attachment_texture_base_view_index_ovr: the base view index of the framebuffer object attachment. re
turn value depends on the requested information (as specified with pname). either a glint, a glenum, a webglrenderbuffer, or a webgltexture. pname parameter re
turn value gl.framebuffer_attachment_object_type a glenum indicating the type of the texture. either gl.renderbuffer, gl.texture, or if no image is attached, gl.none. gl.framebuffer_attachment_object_name ...
WebGLRenderingContext.getProgramInfoLog() - Web APIs
when a webglprogram object is initially created, its information log will be a string of length 0. ...
...when a webglprogram object is initially created, its information log will be a string of length 0. ...
WebGLRenderingContext.getShaderInfoLog() - Web APIs
when a webglshader object is initially created, its information log will be a string of length 0. examples checking compilation messages /* load shader source code. */ gl.shadersource(shader, shadercode); /* compile shader source code. ...
...when a webglshader object is initially created, its information log will be a string of length 0. examples checking compilation messages /* load shader source code. */ gl.shadersource(shader, shadercode); /* compile shader source code. ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
exceptions gl.invalid_enum if the shader or precision types aren't recognized. ...
...ormat object describing the range and precision for the specified shader numeric format. syntax webglshaderprecisionformat gl.getshaderprecisionformat(shadertype, precisiontype); parameters shadertype either a gl.fragment_shader or a gl.vertex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. re
turn value a webglshaderprecisionformat object or null, if an error occurs. exceptions gl.invalid_enum if the shader or precision types aren't recognized. gl.invalid_operation if the shader compiler isn't supported. examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type. var canvas = document.getelementbyid('canvas'); var gl = canvas...
WebGLRenderingContext.getVertexAttribOffset() - Web APIs
examples gl.getvertexattriboffset(i, gl.vertex_attrib_array_pointer); specifications specification status comment webgl 1.0the definition of 'getvertexattriboffset' in that specification. recommendation initial definition. ...
... examples gl.getvertexattriboffset(i, gl.vertex_attrib_array_pointer); specifications specification status comment webgl 1.0the definition of 'getvertexattriboffset' in that specification. recommendation initial definition. ...
WebGLRenderingContext.scissor() - Web APIs
zontal coordinate for the lower left corner of the box. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the box. default value: 0. width a non-negative glsizei specifying the width of the scissor box. default value: width of the canvas. height a non-negative glsizei specifying the height of the scissor box. default value: height of the canvas. re
turn value none. exceptions if either width or height is a negative value, a gl.invalid_value error is thrown. examples when the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands. //
turn on scissor test gl.enable(gl.scissor_test); // set the scissor rectangle gl.scissor(x, y, width, height); // execute drawing commands in the scissor box (e.g. cle...
...none. exceptions if either width or height is a negative value, a gl.invalid_value error is thrown. examples when the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands. //
turn on scissor test gl.enable(gl.scissor_test); // set the scissor rectangle gl.scissor(x, y, width, height); // execute drawing commands in the scissor box (e.g. clear) //
turn off scissor test again gl.disable(gl.scissor_test); to get the current scissor box dimensions, query the scissor_box constant which re
turns an int32array. gl.scissor(0, 0, 200, 200); gl.getparameter(gl.scissor_box); // int32array[0, 0, 200, 200] specifications specification status comment webgl 1.0the definition of 'scissor' in that specification. recommendation ...
WebGLRenderingContext.viewport() - Web APIs
for the lower left corner of the viewport origin. default value: 0. y a glint specifying the vertical coordinate for the lower left corner of the viewport origin. default value: 0. width a non-negative glsizei specifying the width of the viewport. default value: width of the canvas. height a non-negative glsizei specifying the height of the viewport. default value: height of the canvas. re
turn value none. errors thrown if either width or height is a negative value, a gl.invalid_value error is thrown. examples when you first create a webgl context, the size of the viewport will match the size of the canvas. however, if you resize the canvas, you will need to tell the webgl context a new viewport setting. in this situation, you can use gl.viewport. gl.viewport(0, 0, canvas.width, c...
...the viewport will match the size of the canvas. however, if you resize the canvas, you will need to tell the webgl context a new viewport setting. in this situation, you can use gl.viewport. gl.viewport(0, 0, canvas.width, canvas.height); the viewport width and height are clamped to a range that is implementation dependent. to get this range, you can use the max_viewport_dims constant, which re
turns an int32array. gl.getparameter(gl.max_viewport_dims); // e.g. int32array[16384, 16384] to get the current viewport, query the viewport constant. gl.getparameter(gl.viewport); // e.g. int32array[0, 0, 640, 480] specifications specification status comment webgl 1.0the definition of 'viewport' in that specification. recommendation initial definition. op...
Clearing by clicking - Web APIs
f undefined, try to obtain the webglrenderingcontext. // if failed, alert user of failure. // otherwise, initialize the drawing buffer (the viewport). if (!gl) { gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); re
turn; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. var color = getrandomcolor(); // set the clear color to the random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. this is // the function call that actually does the draw...
...color value using a helper function. var color = getrandomcolor(); // set the clear color to the random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. this is // the function call that actually does the drawing. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { re
turn [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github. « previousnext » ...
Color masking - Web APIs
ion setupanimation (evt) { "use strict" window.removeeventlistener(evt.type, setupanimation, false); var canvas = document.queryselector("canvas"); var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; re
turn; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); var timer = setinterval(drawanimation, 1000); var mask = [true, true, true]; var redtoggle = document.queryselector("#red-toggle"), greentoggle = document.queryselector("#green-toggle"), bluetoggle = document.queryselector("#blue-toggle"); redtoggle.addeventlistener("click", setcolormask, false); gree...
... « previousnext » ...
Simple color animation - Web APIs
var color = getrandomcolor(); // set the webglrenderingcontext clear color to the // random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. gl.clear(gl.color_buffer_b...
...height); } // get a random color value using a helper function. var color = getrandomcolor(); // set the webglrenderingcontext clear color to the // random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { re
turn [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github. « previousnext » ...
Compressed texture formats - Web APIs
compressed textures require hardware support, therefore no specific formats are required by webgl; instead, a context can make different formats available, depending on hardware support. this site shows which formats are supported in the used browser. usage of compressed formats first requires activating the respective extension with webglrenderingcontext.getextension(). if supported, it will re
turn an extension object with constants for the added formats and the formats will also be re
turned by calls to gl.getparameter(gl.compressed_texture_formats). (e.g. ext.compressed_rgba_s3tc_dxt1_ext for the webgl_compressed_texture_s3tc extension.) these can then be used with compressedteximage[23]d or compressedtexsubimage[23]d instead of teximage2d calls. note that webgl makes no functionality ava...
...response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image re
turn texture; } } ...
Getting started with WebGL - Web APIs
purpose is to set up the webgl context and start rendering content. // // start here // function main() { const canvas = document.queryselector("#glcanvas"); // initialize the gl context const gl = canvas.getcontext("webgl"); // only continue if webgl is available and working if (gl === null) { alert("unable to initialize webgl. your browser or machine may not support it."); re
turn; } // set clear color to black, fully opaque gl.clearcolor(0.0, 0.0, 0.0, 1.0); // clear the color buffer with specified clear color gl.clear(gl.color_buffer_bit); } window.onload = main; the first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. once we have the canvas, we try to get a webglrenderingcontext for it by calling getcontex...
... the color buffer with specified clear color gl.clear(gl.color_buffer_bit); } window.onload = main; the first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. once we have the canvas, we try to get a webglrenderingcontext for it by calling getcontext() and passing it the string "webgl". if the browser does not support webgl, getcontext() will re
turn null in which case we display a message to the user and exit. if the context is successfully initialized, the variable gl is our reference to it. in this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). at this point, you have enough code that the webgl context should successfully initialize, and you should wind up wit...
Taking still photos with WebRTC - Web APIs
tream the next task is to get the media stream: navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function(stream) { video.srcobject = stream; video.play(); }) .catch(function(err) { console.log("an error occurred: " + err); }); here, we're calling mediadevices.getusermedia() and requesting a video stream (without audio). it re
turns a promise which we attach success and failure callbacks to. the success callback receives a stream object as input. it is the <video> element's source to our new stream. once the stream is linked to the <video> element, we start it playing by calling htmlmediaelement.play(). the error callback is called if opening the stream doesn't work. this will happen for example if there's no compatible ...
...tribute() to make our captured still box display the image. if there isn't a valid image available (that is, the width and height are both 0), we clear the contents of the captured frame box by calling clearphoto(). fun with filters since we're capturing images from the user's webcam by grabbing frames from a <video> element, we can very easily apply filters and fun effects to the video. as it
turns out, any css filters you apply to the element using the filter property affect the captured photo. these filters can range from the simple (making the image black and white) to the extreme (gaussian blurs and hue rotation). you can play with this effect using, for example, the firefox developer tools' style editor; see edit css filters for details on how to do so. using specific devices you ...
Using WebRTC data channels - Web APIs
achannel connection for you. to do this, simply call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false. this will automatically trigger the rtcpeerconnection to handle the negotiations for you, causing the remote peer to create a data channel and linking the two together across the network. the rtcdatachannel object is re
turned immediately by createdatachannel(); you can tell when the connection has been made successfully by watching for the open event to be sent to the rtcdatachannel. let datachannel = pc.createdatachannel("myapp channel"); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); manual negotiation to manually negotiate the data channel connection, you need to firs...
...re the same underlying library for handling stream control transmission protocol (sctp) data, there can still be variations due to how the library is used. for example, both firefox and google chrome use the usrsctp library to implement sctp, but there are still situations in which data transfer on an rtcdatachannel can fail due to differences in how they call the library and react to errors it re
turns. when two users running firefox are communicating on a data channel, the message size limit is much larger than when firefox and chrome are communicating because firefox implements a now deprecated technique for sending large messages in multiple sctp messages, which chrome does not. chrome will instead see a series of messages that it believes are complete, and will deliver them to the receivi...
Writing a WebSocket server in Java - Web APIs
outputstream methods: write(byte[] b, int off, int len) writes len bytes from the specified byte array starting at offset off to this output stream. inputstream methods: read(byte[] b, int off, int len) reads up to len bytes of data from the input stream into an array of bytes...
...eption, nosuchalgorithmexception { serversocket server = new serversocket(80); try { system.out.println("server has started on 127.0.0.1:80.\r\nwaiting for a connection..."); socket client = server.accept(); system.out.println("a client connected."); socket methods: java.net.socket getinputstream() re
turns an input stream for this socket. java.net.socket getoutputstream() re
turns an output stream for this socket. outputstream methods: write(byte[] b, int off, int len) writes len bytes from the specified byte array starting at offset off to this output stream. inputstream methods: read(byte[] b, int off, int len) reads up to len bytes of data from the input stream into an array of bytes. let us extend our example. inputstream in = client.getinputstream(); ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
er the frame ... */ } } the frame parameter is the xrframe representing the animation frame information provided by webxr. when called, this function begins by getting the xrsession from the frame object, then uses the frame's getviewerpose() method to compute the xrviewerpose for the viewer, given viewerrefspace, which describes the current facing direction and position of the viewer. the re
turned viewer pose, viewerpose, can in
turn be used to compute positions and orientations to properly render the objects in the scene given the user's point of view. offsetting or moving reference spaces while you can't change a reference space since both xrreferencespace and xrboundedreferencespace are read-only, you can easily create new reference spaces by applying an offset transform to them. th...
...et the position and facing direction of the viewer (defining what the user should see), and getpose() to get any other poses, such as the positions of the hand controllers and any other parts of the xr system. detecting and functioning after tracking loss if tracking fails, such as due to a temporary loss of connectivity between the headset and the user's device, the xr layer will continue to re
turn poses, but those poses' emulatedposition property will be true, indicating that the computation of the pose is based on a guess of the current position of the user. some xr hardware uses algorithms to compute the estimated position of the user based on the movement currently ongoing, while other hardware will report no movement at all, but with emulatedposition set to true. in either case, you m...
Web Animations API - Web APIs
readonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an optional dictionary object of timing properties. extensions to other interfaces the web animations api adds some new features to document and element. extensions to the document interface document.timeline the documenttimeline object representing the default document timeline. ...
...ent and element. extensions to the document interface document.timeline the documenttimeline object representing the default document timeline. document.getanimations() re
turns an array of animation objects currently in effect on elements in the document. extensions to the element interface element.animate() a shortcut method for creating and playing an animation on an element. it re
turns the created animation object instance. element.getanimations() re
turns an array of animation objects currently affecting an element or which are scheduled to do so in future. specifications specification status comment web animations working draft initial definition ...
Basic concepts behind Web Audio API - Web APIs
audio graphs the web audio api involves handling audio operations inside an audio context, and has been designed to allow modular routing. basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. ...
...here x>y down-mix discrete channels. fill each output channel with its input counterpart, that is the input channel with the same index. input channels with no corresponding output channels are dropped. visualizations in general, audio visualizations are achieved by accessing an output of audio data over time, usually gain or frequency data, and then using a graphical technology to
turn that into a visual output, such as a graph. the web audio api has an analysernode available that doesn't alter the audio signal passing through it. instead it outputs audio data that can be passed to a visualization technology such as <canvas>. you can grab data using the following methods: analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array pas...
Web audio spatialization basics - Web APIs
ing the different properties of the pannernode object instance in relation to that movement, to emulate spacialization. note: the experience is much better if you use headphones, or have some kind of surround sound system to plug your computer into. creating an audio listener so let's begin! the baseaudiocontext (the interface the audiocontext is extended from) has a listener property that re
turns an audiolistener object. this represents the listener of the scene, usually your user. you can define where they are in space and in which direction they are facing. they remain static. the pannernode can then calculate its sound position relative to the position of the listener. let's create our context and listener and set the listener's position to emulate a person looking into our room: co...
...er.orientationy.value = y; panner.orientationz.value = z; break; } boombox.style.transform = 'translatex('+transform.xaxis+'px) translatey('+transform.yaxis+'px) scale('+transform.zaxis+') rotatey('+transform.rotatey+'deg) rotatex('+transform.rotatex+'deg)'; const move = prevmove || {}; move.frameid = requestanimationframe(() => moveboombox(direction, move)); re
turn move; } wiring up our controls wiring up out control buttons is comparatively simple — now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values movecontrols.foreach(function(el) { let moving; el.addeventlistener('mousedown', function() { ...
Attestation and Assertion - Web APIs
ers a new key pair with a service, the authenticator signs the public key with an attestation certificate. the attestation certificate is built into the authenticator during manufacturing time and is specific to a device model. that is, all "samsung galaxy s8" phones, manufactured at a specific time or particular manufacturing run, have the same attestation certificate. the attestation is re
turned through the webauthn api as the authenticatorattestationresponse. the attestation format contains two basic arraybuffers: clientdatajson - an arraybuffer that contains a json representation of what the browser saw when being asked to authenticate. attestationobject - cryptographic attestation that a newly generated keypair was created by that authenticator. contains authenticator da...
... has already been authenticated and has established a secure session. assertion when a user chooses to log into a service, the server sends a challenge and the authenticator signs over it with a key pair previously registered to that service. this creates an assertion. unlike the attestation, the format of the assertion is always the same regardless of the device being used. the assertion is re
turned through the webauthn api as the authenticatorassertionresponse. the assertion format is fairly simple as it contains four basic arraybuffers: clientdatajson - the same as in attestation. an arraybuffer that contains a json representation of what the browser saw when being asked to authenticate. authenticatordata - data created and/or used by the authenticator signature - a sig...
Window.back() - Web APIs
example this simple example handles a click on a "back" button by calling back(). ...
... example this simple example handles a click on a "back" button by calling back(). ...
window.cancelIdleCallback() - Web APIs
example see our complete example in the article cooperative scheduling of background tasks api. specifications specification status comment cooperative scheduling of background tasks proposed recommendation initial definition. ...
... example see our complete example in the article cooperative scheduling of background tasks api. specifications specification status comment cooperative scheduling of background tasks proposed recommendation initial definition. ...
Window.crypto - Web APIs
in general, you should use this api only in secure contexts. ...
...in general, you should use this api only in secure contexts. syntax var cryptoobj = window.crypto || window.mscrypto; // for ie 11 value an instance of the crypto interface, providing access to general-purpose cryptography and a strong random-number generator. ...
Window.devicePixelRatio - Web APIs
this value could also be interpreted as the ratio of pixel sizes: the size of one css pixel to the size of one physical pixel. in simpler terms, this tells the browser how many of the screen's actual pixels should be used to draw a single css pixel. this is useful when dealing with the difference between rendering on a standard display versus a hidpi or retina display, which use more screen pixels to draw the same objects, resulting in a sharper image. ...
... a different pixel density). see the example below. syntax value = window.devicepixelratio; value a double-precision floating-point value indicating the ratio of the display's resolution in physical pixels to the resolution in css pixels. a value of 1 indicates a classic 96 dpi (76 dpi on some platforms) display, while a value of 2 is expected for hidpi/retina displays. other values may be re
turned as well in the case of unusually low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 dpi. examples correcting resolution in a <canvas> a <canvas> can appear too blurry on retina screens. use window.devicepixelratio to determine how much extra pixel density should be added to allow for a sharper image. html <...
Window.event - Web APIs
in addition, window.event is not accurate for events dispatched within shadow trees. specifications specification status comment domthe definition of 'window.event' in that specification. ...
... code. outside the context of an event handler, the value is always undefined. you should avoid using this property in new code, and should instead use the event passed into the event handler function. this property is not universally supported and even when supported introduces potential fragility to your code. note: this property can be fragile, in that there may be situations in which the re
turned event is not the expected value. in addition, window.event is not accurate for events dispatched within shadow trees. specifications specification status comment domthe definition of 'window.event' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. if yo...
Window.innerHeight - Web APIs
the value of innerheight is taken from the height of the window's layout viewport. the width can be obtained using the innerwidth property. syntax let intviewportheight = window.innerheight; value an integer value indicating the window's layout viewport height in pixels. the property is read only and has no default value. to change the width of the window, call one of its resize methods, such as resizeto() or resizeby(). ...
... obtain the height of the window minus its horizontal scroll bar and any borders, use the root <html> element's clientheight() property instead. both innerheight and innerwidth are available on any window or any object that behaves like a window, such as a tab or frame. example assuming a frameset var intframeheight = window.innerheight; // or var intframeheight = self.innerheight; // will re
turn the height of the frame viewport within the frameset var intframesetheight = parent.innerheight; // will re
turn the height of the viewport of the closest frameset var intouterframesetheight = top.innerheight; // will re
turn the height of the viewport of the outermost frameset fixme: link to an interactive demo here to change the size of a window, see window.resizeby() and window.resizeto(). ...
Window.requestFileSystem() - Web APIs
even compared to the rest of the file and directory entries api, requestfilesystem() is especially non-standard; only chrome implements it, and all other browser makers have decided that they will not implement it. it has even been removed from the proposed specification. ...
...eter: a filesystem object representing the file system the app has permission to use. errorcallback optional an optional parameter specifying a function which is called if an error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system. the callback receives as input a single parameter: a fileerror object describing the error. re
turn value undefined example specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or whatwg specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/...
Window.screenLeft - Web APIs
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
... examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
Window.screenTop - Web APIs
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
... examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
Window.screenX - Web APIs
examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. ...
... examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. ...
Window.screenY - Web APIs
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
... examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. ...
Window.scrollY - Web APIs
the read-only scrolly property of the window interface re
turns the number of pixels that the document is currently scrolled vertically. this value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. you can get the number of pixels the document is scrolled horizontally from the scrollx property. syntax var y = window.scrolly value in practice, the re
turned value is a double-precision floating-point value indicating the number of pixels the document is currently scrolled vertically from the origin, where a positive value means the content is scrolled to upward. if the document is rendered on a subpixel-precise device, then the re
turned value is also subpixel-precise and may contain a decimal component. if the document isn't scrolled at all up or down, ...
...the origin, where a positive value means the content is scrolled to upward. if the document is rendered on a subpixel-precise device, then the re
turned value is also subpixel-precise and may contain a decimal component. if the document isn't scrolled at all up or down, then scrolly is 0. if you need an integer value, you can use math.round() to round it off. in more technical terms, scrolly re
turns the y coordinate of the top edge of the current viewport. if there is no viewport, the re
turned value is 0. example // make sure and go down to the second page if (window.scrolly) { window.scroll(0, 0); // reset the scroll position to the top left of the document. } window.scrollbypages(1); notes use this property to check that the document hasn't already been scrolled when using relativ...
WindowOrWorkerGlobalScope.caches - Web APIs
the caches read-only property of the windoworworkerglobalscope interface re
turns 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. syntax var mycachestorage = self.caches; // or just caches value a cachestorage object. example the following example shows how you'd use a cache in a service worker context to store assets offline. ...
... assets for offline use, and generating custom responses to requests. syntax var mycachestorage = self.caches; // or just caches value a cachestorage object. example the following example shows how you'd use a cache in a service worker context to store assets offline. ...
self.createImageBitmap() - Web APIs
the createimagebitmap() method creates a bitmap from a given source, optionally cropped to contain only a portion of that source. the method exists on the global scope in both windows and workers. it accepts a variety of different image sources, and re
turns a promise which resolves to an imagebitmap. syntax const imagebitmappromise = createimagebitmap(image[, options]); const imagebitmappromise = createimagebitmap(image, sx, sy, sw, sh[, options]); parameters image an image source, which can be an <img>, svg <image>, <video>, <canvas>, htmlimageelement, svgimageelement, htmlvideoelement, htmlcanvaselement, blob, imagedata, imagebitmap, or offscreencanvas object. sx the x coordinate of the reference point of the rectangle from which the imagebitmap will be extracted. sy the y coordi...
...ther none or default (default). the value default indicates that implementation-specific behavior is used. resizewidth: a long integer that indicates the output width. resizeheight: a long integer that indicates the output height. resizequality: specifies the algorithm to be used for resizing the input to match the output dimensions. one of pixelated, low (default), medium, or high. re
turn value a promise which resolves to an imagebitmap object containing bitmap data from the given rectangle. example creating sprites from a sprite sheet this example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. a sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. var canvas = docu...
WorkerGlobalScope.navigator - Web APIs
it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers. syntax var navigatorobj = self.navigator; value a workernavigator object. ...
... specifications specification status comment html living standardthe definition of 'navigator' in that specification. living standard ...
WritableStreamDefaultWriter.desiredSize - Web APIs
the desiredsize read-only property of the writablestreamdefaultwriter interface re
turns the desired size required to fill the stream's internal queue. syntax var desiredsize = writablestreamdefaultwriter.desiredsize; value an integer. note that this can be negative if the queue is over-full. the value will be null if the stream cannot be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. exceptions typeerror the writer’s lock is released. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... ...
...be successfully written to (due to either being errored, or having an abort queued up), and zero if the stream is closed. exceptions typeerror the writer’s lock is released. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // re
turn stream's desired size let size = writer.desiredsize; specifications specification status comment streamsthe definition of 'desiredsize' in that specification. living standard initial definition. ...
XMLHttpRequest.getResponseHeader() - Web APIs
the xmlhttprequest method getresponseheader() re
turns the string containing the text of a particular header's value. if there are multiple response headers with the same name, then their values are re
turned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. the getresponseheader() method re
turns the value as a utf byte sequence. note: the search for the header name is case-insensitive. if you need to get the raw string of all of the headers, use the getallresponseheaders() method, which re
turns the entire raw header string. ...
...urns the value as a utf byte sequence. note: the search for the header name is case-insensitive. if you need to get the raw string of all of the headers, use the getallresponseheaders() method, which re
turns the entire raw header string. syntax var myheader = xmlhttprequest.getresponseheader(headername); parameters headername a bytestring indicating the name of the header you want to re
turn the text value of. re
turn value a bytestring representing the header's text value, or null if either the response has not yet been received or the header doesn't exist in the response. example in this example, a request is created and sent, and a readystatechange handler is established to look for the readystate to indicate that the headers have been received; when that is the case, the valu...
XMLHttpRequest.responseURL - Web APIs
the value of responseurl will be the final url obtained after any redirects. ...
...the value of responseurl will be the final url obtained after any redirects. ...
XMLHttpRequest.send() - Web APIs
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. ...
...ich case it is serialized before being sent. an xmlhttprequestbodyinit, which per the fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring object. null if no value is specified for the body, a default value of null is used. the best way to send binary content (e.g. in file uploads) is by using an arraybufferview or blob in conjunction with the send() method. re
turn value undefined. exceptions exception description invalidstateerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // requ...
XPathEvaluator.evaluate() - Web APIs
the evaluate() method of the xpathevaluator interface executes an xpath expression on the given node or document and re
turns an xpathresult. syntax xpathresult xpathevaluator.evaluate(expression, contextnode, resolver, type, result); parameters expression a domstring representing the xpath expression to be parsed and evaluated. contextnode a node representing the context to use for evaluating the expression. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. type optional specifies the type of result to be re
turned by evaluating the expression. ...
...for evaluating the expression. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. type optional specifies the type of result to be re
turned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and re
turned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be re
turned. re
turn value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expressio...
XPathResult.snapshotItem() - Web APIs
exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotitem() method. ...
... exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotitem() method. ...
XPathResult - Web APIs
e type and value of the result. properties xpathresult.booleanvalueread only a boolean representing the value of the result if resulttype is boolean_type. xpathresult.invaliditeratorstateread only signifies that the iterator has become invalid. it is true if resulttype is unordered_node_iterator_type or ordered_node_iterator_type and the document has been modified since this result was re
turned. xpathresult.numbervalueread only a number representing the value of the result if resulttype is number_type. xpathresult.resulttyperead only a number code representing the type of the result, as defined by the type constants. xpathresult.singlenodevalueread only a node representing the value of the single node result, which may be null. xpathresult.snapshotlengthread only the numbe...
...nglenodevalueread only a node representing the value of the single node result, which may be null. xpathresult.snapshotlengthread only the number of nodes in the result snapshot. xpathresult.stringvalueread only a string representing the value of the result if resulttype is string_type. methods xpathresult.iteratenext() if the result is a node set, this method iterates over it and re
turns the next node from it or null if there are no more nodes. xpathresult.snapshotitem() re
turns an item of the snapshot collection or null in case the index is not within the range of nodes. unlike the iterator result, the snapshot does not become invalid, but may not correspond to the current document if it is mutated. constants result type defined constant value description ...
XRFrame.getPose() - Web APIs
the xrframe method getpose() re
turns the relative position and orientation—the pose—of one xrspace to that of another space. with this, you can observe the motion of objects relative to each other and to fixed locations throughout the scene. for example, to get the position of a controller relative to the viewer's head, you would compare the controller's gripspace to the xrreferencespace of type viewer. syntax var xrpose = xrframe.getpose(space, basespace); parameters space an xrspace specifying the space for which to obtain an xrpose describing the item's position and orientation. basespace an xrspace to use as the base or origin for the purposes of computing the relative position and orientation. ...
... you would compare the controller's gripspace to the xrreferencespace of type viewer. syntax var xrpose = xrframe.getpose(space, basespace); parameters space an xrspace specifying the space for which to obtain an xrpose describing the item's position and orientation. basespace an xrspace to use as the base or origin for the purposes of computing the relative position and orientation. re
turn value an xrpose object specifying the position and orientation, relative to the xrspace indicated by basespace. specifications specification status comment webxr device apithe definition of 'xrframe.getpose()' in that specification. working draft initial definition. ...
XRInputSource.gripSpace - Web APIs
for example, if a user were holding a virtual straight rod, the native origin of this xrspace would be located at the approximate center of mass of the user's fist. syntax var xrspace = xrinputsource.gripspace; value an xrspace object representing the position and orientation of the input device in virtual space, suitable for rendering an image of the device into the scene. gripspace is null if the input source is inherently untrackable. for example, only inputs whose targetraymode is tracked-pointer provide a gripspace. ...
... specifications specification status comment webxr device apithe definition of 'xrinputsource.gripspace' in that specification. working draft initial definition. ...
XRInputSourceArray.entries() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
... examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. ...
XRPermissionDescriptor.optionalFeatures - Web APIs
xrreferencespacetype enumerated type, indicating set of features that your app would like to use, but can operate without if permission to use them isn't available. while further features may be defined in future editions of webxr, currently all permitted values come from the xrreferencespacetype enumerated type, indicating reference spaces the app rquires to be available. the reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is re
turned for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement t...
... space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
XRReferenceSpaceType - Web APIs
the xrreferencespacetype enumerated type defines the strings which identify the types of reference spaces supported by webxr. this type is used when calling the requestreferencespace() method to obtain a reference space for an xrsession. values the reference space re
turned by xrsession.requestreferencespace() is either xrreferencespace or xrboundedreferencespace. the "interface" column in the table below indicates which of the two types is re
turned for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except t...
... space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
XRRenderState.baseLayer - Web APIs
this property is read-only; however, you can indirectly change its value using xrsession.updaterenderstate. syntax var xrwebgllayer = xrrenderstate.baselayer; value a xrwebgllayer object which is used as the source of the world's contents when rendering each frame of the scene. see the examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. ...
...w to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); setnewwebgllayer(); function setnewwebgllayer(gl) { if (!gl) { /* webgl not available */ re
turn; } xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl); }); }; here, the canvas obtained in the first line is the canvas into which webgl is going to draw. that context is passed into new xrwebgllayer() to create an xrwebgllayer which uses the contents of the webgl context gl as the source of the world's image during presentation. specifications specif...
XRRigidTransform.matrix - Web APIs
syntax let matrix = xrrigidtransform.matrix; value a float32array containing 16 entries which represents the 4x4 transform matrix which is described by the position and orientation properties. usage notes matrix format all 4x4 transform matrices used in webgl are stored in 16-element float32arrays. ...
...q_y - q_zq_w) & 2(q_xq_z + q_yq_w) & p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w) & p_y\\ 2(q_xq_z - q_yq_w) & 2(q_yq_z + q_xq_w) & 1 - 2(q_x^2 + q_y^2) & p_z\\ 0 & 0 & 0 & 1 \end{bmatrix} the final transform matrix is calculated by multiplying the translation matrix by the rotation matrix, in the order (translation * rotation). ...
XRRigidTransform - Web APIs
donly specifying a 3-dimensional point, expressed in meters, describing the translation component of the transform. the w attribute is always 1.0. xrrigidtransform.orientation read only a dompointreadonly which contains a unit quaternion describing the rotational component of the transform. as a unit quaternion, its length is always normalized to 1.0. ...
... dompointreadonly which contains a unit quaternion describing the rotational component of the transform. as a unit quaternion, its length is always normalized to 1.0. xrrigidtransform.matrix read only re
turns the transform matrix in the form of a 16-member float32array. see the section matrix format for how the array is used to represent a matrix. xrrigidtransform.inverse read only re
turns a xrrigidtransform which is the inverse of this transform. that is, if applied to an object that had been previously transformed by the original transform, it will undo the transform and re
turn the original object. usage notes when an xrrigidtransform is interpreted, the orientation is always applied to the affected object before the position is applied. example this code snippet creates an...
XRSession.cancelAnimationFrame() - Web APIs
usage notes this function has no effect if the specified handle cannot be found. ...
... usage notes this function has no effect if the specified handle cannot be found. ...
XRSession.end() - Web APIs
you can use the promise to do things like update ui elements to reflect the shut down connection, trigger application shut down, or whatever else you might need to do. ...
...you can use the promise to do things like update ui elements to reflect the shut down connection, trigger application shut down, or whatever else you might need to do. ...
XRSession.inputSources - Web APIs
the read-only inputsources property of the xrsession interface re
turns an xrinputsourcearray object which lists all controllers and input devices which are expressly associated with the xr device and are currently available. these controllers may include handheld controllers, xr-equipped gloves, optically tracked hands, and gaze-based input methods. keyboards, gamepads, and mice are not considered webxr input sources. note: traditional gamepad controllers are supported using the gamepad api. syntax inputsources = xrsession.inputsources; value an xrinputsourcearray object listing all of the currently-connected input controllers which are linked specifically to the xr device currently in use. ...
...d hands, and gaze-based input methods. keyboards, gamepads, and mice are not considered webxr input sources. note: traditional gamepad controllers are supported using the gamepad api. syntax inputsources = xrsession.inputsources; value an xrinputsourcearray object listing all of the currently-connected input controllers which are linked specifically to the xr device currently in use. the re
turned object is live; as devices are connected to and removed from the user's system, the list's contents update to reflect the changes. usage notes you can add a handler for the xrsession event inputsourceschange to be advised when the contents of the session's connected devices list changes. you can then either get the value of inputsources to examine the list, or you can refer to a reference to ...
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and re
turns a new xrsessionevent object. these objects represent events announcing state changes in an xrsession representing an augmented or virtual reality session. syntax newxrsessionevent = new xrsessionevent(type, eventinitdict); parameters type a domstring indicating which of the events represented by objects of type xrsessionevent this particular object represents. see event types for a list of the permitted values. eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the newly-created event object. permitted values are: session the xrsession to which the event is to be delivered. ...
...ting which of the events represented by objects of type xrsessionevent this particular object represents. see event types for a list of the permitted values. eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the newly-created event object. permitted values are: session the xrsession to which the event is to be delivered. re
turn value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter. event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property. end fired at the session when it has ended, after being terminated by the application or the user agent. visib...
XRSystem: isSessionSupported() - Web APIs
the xrsystem method issessionsupported() re
turns a promise which resolves to true if the specified webxr session mode is supported by the user's webxr device. otherwise, the promise resolves with false. if the no devices are available or the browser doesn't have permission to use the xr device, the promise is rejected with an appropriate domexception. syntax var issupportedpromise = xr.issessionsupported(xrsessionmode) parameters xrsessionmode a domstring specifying the webxr session mode for which support is to be checked. this string must be one of inline (to present the webxr content inline within the context of an html document) or immersive-vr for a fully-immersive virtual experience. ...
... rejected with an appropriate domexception. syntax var issupportedpromise = xr.issessionsupported(xrsessionmode) parameters xrsessionmode a domstring specifying the webxr session mode for which support is to be checked. this string must be one of inline (to present the webxr content inline within the context of an html document) or immersive-vr for a fully-immersive virtual experience. re
turn value a promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. exceptions rather than throwing true exceptions, issessionsupported() rejects the re
turned promise, passing to the rejection handler a domexception whose name is one of the following strings. securityerror the document's origin does not have permission to use the xr-sp...
XRSystem - Web APIs
ssion in hand, you can use it to interact with the augmented reality (ar) or virtual reality (vr) device. properties while xrsystem directly offers no properties, it does inherit properties from its parent interface, eventtarget. methods in addition to inheriting methods from its parent interface, eventtarget, the xrsystem interface includes the following methods: issessionsupported() re
turns a promise which resolves to true if the browser supports the given xrsessionmode. resolves to false if the specified mode isn't supported. requestsession() re
turns a promise that resolves to a new xrsession with the specified xrsessionmode. events devicechange sent when the set of available xr devices has changed. also available using the ondevicechange event handler. usage notes ...
...it the desired session option before enabling the button, immersivebutton, which the user can then use to switch to immersive mode only if immersive vr mode is available. if immersive vr isn't available, the button is disabled to prevent its use. the onbuttonclicked() function checks to see if there's already a session running. if there isn't, we use requestsession() to start one and, once the re
turned promise resolves, we call a function onsessionstarted() to set up our session for rendering and so forth. if, on the other hand, there is already an ongoing xr session, we instead call end() to end the current session. when the re
turned promise resolves, we set xrsession to null to record the fact that we no longer have an ongoing session. that way, if the user clicks the button again, a new s...
XRWebGLLayer.getViewport() - Web APIs
the xrwebgllayer interface's getviewport() method re
turns the xrviewport that should be used to render the specified xrview into the webgl layer. for webxr devices which use a single framebuffer for both the left and right eyes, the re
turned viewport represents the region of the framebuffer into which the scene should be rendered for the eye represented by the view. syntax let viewport = xrwebgllayer.getviewport(view); parameters view an xrview object indicating the view for which the viewport is to be re
turned. re
turn value a xrviewport object representing the viewport which will restrict drawing to the portion of the layer corresponding to the specified view. exceptions invalidstateerror either the specified view is not in an active xrframe or that xrframe and the xrwebglla...
... xrframe or that xrframe and the xrwebgllayer are not part of the same webxr session. example this example demonstrates in part what the callback for the requestanimationframe() function might look like, using getviewport() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered. this works because the set of views re
turned by an xrviewerpose each represent one eye's perspective on the scene. since the framebuffer is split in half, one half for each eye, setting the webgl viewport to match the webxr layer's viewport will ensure that when rendering the scene for the current eye's pose, it is rendered into the correct half of the framebuffer. <<<--- add link to appropriate section in the cameras and views article -...
msCapsLockWarningOff - Web APIs
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 mscapslockwarningoff read/write property
turns automatic caps lock warning on or off for validated password input fields. ...
...ed password input fields. this proprietary property is specific to internet explorer and microsoft edge. starting with internet explorer 10, input type=password fields will automatically display a warning if the caps lock is on. this property enables this warning to be disabled. syntax document.mscapslockwarningoff = true; value type: boolean false: default. automatic caps lock warning is
turned on. true: automatic caps lock warning is
turned off. example fiddle: http://jsfiddle.net/jonathansampson/mqcha/1/ example 2 <html> <head> <title>mscapslockwarningoff example</title> <script type="text/javascript"> function capsoff() { if (document.mscapslockwarningoff == false) { document.mscapslockwarningoff = true; docume...
Alerts - Accessibility
imary method in javascript used for form validation is the checkvalidity function. this method takes three parameters: the id of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert. to see if it is valid, the function checks whether the indexof the input’s value is anything greater than -1. a value of -1 or less is re
turned if the index of the search term could not be found within the value. if invalid, the function does two things: it sets the element’s aria-invalid attribute to “true”, which will indicate to screen readers that there is invalid content in here. it will call the addalert function to add the alert with the provided error message. if the search term is found, the aria-invalid attribute...
...reen reader, try the following: enter only your first name as the name. when tabbing, you’ll hear an alert that tells you you’ve entered an invalid name. you can then shift-tab back and correct the error. enter an e-mail address without the “@” symbol. when tabbing out of this field, you should hear a warning that says you didn’t enter a valid e-mail address. in both cases, when re
turning focus to the field in question, your screen reader should tell you that this field is invalid. jaws 9 supports this, but jaws 8 does not, so this may not work in all versions of the screen readers supported. a few questions that you might have q. why did you put both “(required)” in the label text and the aria-required attribute on some of the inputs? a. if this were a real live form,...
Accessibility: What users can do to browse more safely - Accessibility
"move ya! or maybe, don't, if the user prefers-reduced-motion!"). this will not work on animated gifs; the source of the animation is self-contained within a gif and is not affected by these settings. use reader mode on browsers enable content blockers; gets rid of ads, reduces and/or removes distractions enables text-to-speech in certain browsers, enable fonts by choice enable page zoom
turn off animated gifs in the browser browsers offer much power to their users; it's just a matter of knowing where to go. using firefox as an example, it explains that by changing the value the image.animation_mode from "normal" to "none", all animated images will be blocked. to reverse it, you will have to change the value back to "normal" use browser extensions gif blocker for chrome, gif bl...
... browser extension that allows you to set up for grayscale and dyslexi font, among other things take advantage operating system accessibility features most operating systems such as windows 10, have accessibility options that are surprisingly powerful. usually they are quite easy to find by simply typing ( or saying) in the word, "accessibility" in the search finder of the operating system.
turn off animations in the operating system in the windows10 operating system, the user has an ability to
turn off animations. this will not work on animated gifs; the source of the animation is self-contained within a gif and is not affected by these settings.. grayscale those who have sufferred traumatic brain injury (tbi) may be highly sensitive to color; it can require such a great "investmen...
Understandable - Accessibility
semantically and in terms of labels. again, sensible design! "labels" can refer to descriptive information in text content, or html form labels. see meaningful text labels for more information. 3.2.5 change on request (aaa) changes in context that could possibly confuse or disorient users should only occur only when requested by the user, or the user should be able to
turn them off. if you need to have something that significantly changes the current view (e.g. content or controls), let the user control when they want that change to occur (e.g. what page to show, when to advance to the next photo in the gallery...) if you need to have something like a carousel on a page, provide an option to stop it automatically advancing. better to avoid such functional...
...or your situation. when an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. for screenreader users, you can use aria live regions to alert the user to a change on the page. note: server-side validation should *always* be used alongside client-side validation. client-side validation is too easy to
turn off or otherwise get around, so it can't be relied on alone. see form data validation for comprehensive validation information, and wai-aria: dynamic content updates for information on live regions. 3.3.2 labels or instructions (a) clear instructions should be provided when data input is required. when a simple instruction or prompt is required, you can use <label> el...
Using feature queries - CSS: Cascading Style Sheets
than one property in your feature query. to do so, you can include a list of features to test for, separated by and keywords: @supports (property1: value) and (property2: value) { css rules to apply } for example, if the css you want to run requires that the browser supports css shapes and css grid, you could create a rule which checks for both of these things. the following rule will only re
turn true if both shape-outside: circle() and display: grid are supported by the browser. you can also use or, if one property out of a selection could match to enable the css you want to use: @supports (property1: value) or (property2: value) { css rules to apply } this can be particularly useful if a feature is vendor prefixed, as you can test for the standard property plus any vendor prefixe...
...css rules to apply } this can be particularly useful if a feature is vendor prefixed, as you can test for the standard property plus any vendor prefixes. limitations of feature queries the @supports rule tests to see if the browser can parse one or more property/value pairs, and therefore if it claims to support the feature(s). if the property and value pair is understood by the browser it re
turns a positive response. therefore feature queries cannot be used to check if a browser supports a thing properly, and without bugs! in addition, feature queries cannot test for partial implementations. a good example of this is the gap property. all browsers that support css grid support gap in css grid, however only firefox supports gap in flexbox. if you test for the gap property, because you wa...
CSS Containment - CSS: Cascading Style Sheets
d elements — these must also be offscreen as they are contained completely by that box. size containment article { contain: size; } size containment does not offer much in the way of performance optimizations when used on its own. however, it means that the size of the element's children cannot affect the size of the element itself — its size is computed as if it had no children. if you
turn on contain: size you need to also specify the size of the element you have applied this to. it will end up being zero-sized in most cases, if you don't manually give it a size. style containment article { contain: style; } despite the name, style containment does not provide scoped styles such as you would get with the shadow dom. the main use case is to prevent situations where a css counte...
...le would ensure that the counter-increment and counter-set properties created new counters scoped to that subtree only. note: style containment is "at-risk" in the spec and may not be supported everywhere (it's not currently supported in firefox). special values there are two special values of contain: content strict we encountered the first in the example above. using contain: content
turns on layout and paint containment. the specification describes this value as being "reasonably safe to apply widely". it does not apply size containment, so you would not be at risk of a box ending up zero-sized due to a reliance on the size of its children. to gain as much containment as possible use contain: strict, which behaves the same as contain: size layout paint, or perhaps the following ...
Variable fonts guide - CSS: Cascading Style Sheets
g the 'variation axis' the heart of the new variable fonts format is the concept of an axis of variation describing the allowable range of that particular aspect of the typeface design. so the 'weight axis' describes how light or how bold the letterforms can be; the 'width axis' describes how narrow or how wide they can be; the 'italic axis' describes if italic letterforms are present and can be
turned on or off accordingly, etc. note that an axis can be a range or a binary choice. weight might range from 1–999, whereas italic might simply be 0 or 1 (off or on). as defined in the specification, there are two kinds of axes: registered and custom: registered axes are simply those that are most frequently encountered, and common enough that the authors of the specification felt it was w...
... size rendering. optical size values are generally intended to be automatically applied corresponding to font-size, but can also be manipulated using the lower-level font-variation-settings syntax. there is a new attribute, font-optical-sizing, created to support variable fonts in css. when using font-optical-sizing, the only allowed values are auto or none — so this attribute only allows for
turning optical sizing on or off. however when using font-variation-settings: 'opsz' <num>, you can supply a numeric value. in most cases you would want to match the font-size (the physical size the type is being rendered) with the opsz value (which is how optical sizing is intended to be applied when using auto). the option to provide a specific value is provided so that should it be necessary to ove...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
} * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } all the direct children are now grid items. in a web browser, you won’t see any difference to how these items are displayed before
turning them into a grid, as grid has created a single column grid for the items. at this point, you may find it useful to work with the grid inspector, available as part of firefox's developer tools. if you view this example in firefox and inspect the grid, you will see a small icon next to the value grid. click this and then the grid on this element will be overlaid in the browser window. as you ...
... change the track definition of grid-template-columns: repeat(3, 1fr), to grid-template-columns: subgrid. the nested grid will then use the parent grid tracks to layout items. .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-start: 1; grid-row-end: 3; display: grid; grid-template-columns: subgrid; } layering items with z-index grid items can occupy the same cell. if we re
turn to our example with items positioned by line number, we can change this to make two items overlap. <div class="wrapper"> <div class="box box1">one</div> <div class="box box2">two</div> <div class="box box3">three</div> <div class="box box4">four</div> <div class="box box5">five</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 100px;...
CSS values and units - CSS: Cascading Style Sheets
ric part of the value, with no space in-between. angle units angle values are represented by the type <angle> and accept the following values: unit name description deg degrees there are 360 degrees in a full circle. grad gradians there are 400 gradians in a full circle. rad radians there are 2π radians in a full circle.
turn turns there is 1
turn in a full circle. time units time values are represented by the type <time>. when including a time value, the unit identifier -- the s or ms -- is required. it accepts the following values. unit name description s seconds ms milliseconds there are 1,000 milliseconds in a second. frequency units frequenc...
...i, vb, ic, cap, lh and rlh units. adds the min(), max() and clamp() functional notation adds toggle() css values and units module level 3 candidate recommendation adds calc(), ch, rem, vw, vw, vmin, vmax, q css color module level 4 working draft adds commaless syntaxes for the rgb(), rgba(), hsl(), and hsla() functions. allows alpha values in rgb() and hsl(),
turning rgba() and hsla() into (deprecated) aliases for them. adds color keyword rebeccapurple. adds 4- and 8-digit hex color values, where the last digit(s) represents the alpha value. adds hwb(), device-cmyk(), and color() functions. css color module level 3 recommendation deprecates system-colors. adds svg colors. adds the rgba(), hsl(), and hsla() functions. css...
backface-visibility - CSS: Cascading Style Sheets
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. an element's back face is a mirror image of its front face. though invisible in 2d, the back face can become visible when a transformation causes the element to be rotated in 3d space. ...
...roperty has no effect on 2d transforms, which have no perspective.) syntax /* keyword values */ backface-visibility: visible; backface-visibility: hidden; /* global values */ backface-visibility: inherit; backface-visibility: initial; backface-visibility: unset; the backface-visibility property is specified as one of the keywords listed below. values visible the back face is visible when
turned towards the user. hidden the back face is hidden, effectively making the element invisible when
turned away from the user. formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces this example shows a cube with transparent faces, and o...
Computed value - CSS: Cascading Style Sheets
m units or percentages) to absolute values. for example, if an element has specified values font-size: 16px and padding-top: 2em, then the computed value of padding-top is 32px (double the font size). ...
... specifications specification status comment css level 2 (revision 2)the definition of 'computed-value' in that specification. ...
counter() - CSS: Cascading Style Sheets
note: the counter() function can be used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. check the browser compatibility table carefully before using this in production. ...
...rrent value of the named counter, if there is one. it is generally used with pseudo-elements, but can be used, theoretically, anywhere a <string> value is supported. /* simple usage */ counter(countername); /* changing the counter display */ counter(countername, upper-roman) a counter has no visible effect by itself. the counter() function (and counters() function) is what makes it useful by re
turning developer defined strings (or images). note: the counter() function can be used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. check the browser compatibility table carefully before using this in production. syntax values <custom-ident> a name identifying the counter, which is the same case-s...
counters() - CSS: Cascading Style Sheets
the counters() function has two forms: 'counters(name, string)' or 'counters(name, string, style)'. it is generally used with pseudo-elements, but can be used, theoretically, anywhere a <string> value is supported. the generated text is the value of all counters with the given name, from outermost to innermost, separated by the specified string. the counters are rendered in the style indicated, defaulting to decimal if no style is specified. ...
...d by the specified string. the counters are rendered in the style indicated, defaulting to decimal if no style is specified. /* simple usage - style defaults to decimal */ counters(countername, '-'); /* changing the counter display */ counters(countername, '.', upper-roman) a counter has no visible effect by itself. the counters() function (and counter() function) is what makes it useful by re
turning developer defined content. note: the counters() function can be used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. check the browser compatibility table carefully before using this in production. syntax values <custom-ident> a name identifying the counters, which is the same case-sensitive n...
font-smooth - CSS: Cascading Style Sheets
nti-aliasing when fonts are rendered. syntax /* keyword values */ font-smooth: auto; font-smooth: never; font-smooth: always; /* <length> value */ font-smooth: 2em; webkit implements a similar property, but with different values: -webkit-font-smoothing. it only works on mac os x/macos. auto - let the browser decide (uses subpixel anti-aliasing when available; this is the default) none -
turn font smoothing off; display text with jagged sharp edges. antialiased - smooth the font on the level of the pixel, as opposed to the subpixel. switching from subpixel rendering to antialiasing for light text on dark backgrounds makes it look lighter. subpixel-antialiased - on most non-retina displays, this will give the sharpest text. firefox implements a similar property, but with differen...
.... formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | never | always | <absolute-size> | <length>where <absolute-size> = xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large examples basic usage example the following example shows the safari/chromium and firefox equivalents that
turn on font-smoothing on macos. in both cases the smoothed font should look slightly lighter in weight. for those of you not on a macos system, here is a screenshot (the live version appears later on): html <p>without font smoothing</p> <p class="smoothed">with font smoothing</p> css html { background-color: black; color: white; font-size: 3rem; } p { text-align: center; } .smoothed...
linear-gradient() - CSS: Cascading Style Sheets
github.com/mdn/interactive-examples and send us a pull request. ...
...dient going from the bottom to top, starting blue,
turning green at 40% of its length, and finishing red */ linear-gradient(0deg, blue, green 40%, red); /* color hint: a gradient going from the left to right, starting red, getting to the midpoint color 10% of the way across the length of the gradient, taking the rest of the 90% of the length to change to blue */ linear-gradient(.25
turn, red, 10%, blue); /* multi-position color stop: a gradient tilted 45 degrees, with a red bottom-left half and a blue top-right half, with a hard line where the gradient changes from red to blue */ linear-gradient(45deg, red 0 50%, blue 50% 100%); values <side-or-corner> the position of the gradient line's starting point. if specified, it consists of the word to and up to two keywords:...
Guide to scroll anchoring - CSS: Cascading Style Sheets
after the user has already scrolled to a new part of the document. how does it work? scroll anchoring adjusts the scroll position to compensate for the changes outside of the viewport. this means that the point in the document the user is looking at remains in the viewport, which may mean their scroll position actually changes in terms of how far they have moved through the document. how do i
turn on scroll anchoring? you don't! the feature is enabled by default in supporting browsers. in most cases anchored scrolling is exactly what you want — content jumping is a poor experience for anyone. what if i need to debug it? if your page is not behaving well with scroll anchoring enabled, it is probably because some scroll event listener is not handling well the extra scrolling to compensa...
...o opt out a certain part of the document use overflow-anchor: none on its container element: .container { overflow-anchor: none; } note: the specification details that once scroll anchoring has been opted out of, you cannot opt back into it from a child element. for example, if you opt out for the entire document, you will not be able to set overflow-anchor: auto elsewhere in the document to
turn it back on for a subsection. suppression triggers the specification also details some suppression triggers, which will disable scroll anchoring in places where it might be problematic. if any of the triggers happen on the anchor node, or an ancestor of it, anchoring is suppressed. these suppression triggers are changes to the computed value of any of the following properties: top, left, ri...
transform - CSS: Cascading Style Sheets
d. that is, all elements whose layout is governed by the css box model except for: non-replaced inline boxes, table-column boxes, and table-column-group boxes. ...
... right, meaning that composite transforms are effectively applied in order from right to left. none specifies that no transform should be applied. accessibility concerns scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. if you need to include such animations on your website, you should provide a control to allow users to
turn off animations, preferrably site-wide. also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will
turn off animations if the user has reduced animation specified in their system preferences. find out more: mdn understanding wcag, guideline 2.3 explanations understanding success criterion 2.3.3 | w3c understanding wcag 2.1 formal defin...
exsl:object-type() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes exsl:object-type() re
turns a string that indicates the type of the specified object. note: most xslt object types can be coerced into each other safely; however, certain coercsions to raise error conditions. in particular, treating something that's not a node-set as a node-set will do so. this function lets authors of named templates and extension functions easily provide flexibility in parameter values. syntax exsl:object-type(object) parameters object the object whose type is to be re
turned. ...
...es can be coerced into each other safely; however, certain coercsions to raise error conditions. ...
regexp:match() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes regexp:match() performs regular expression matching on a string, re
turning the submatches found as a result. syntax regexp:match(targetstring, regexpstring[, flagsstring]) parameters targetstring the string to perform regular expression matching upon. regexpstring the javascript style regular expression to evaluate. flagsstringoptional an optional string containing character flags. the character flags are: g global match the submatches from every match in the string are re
turned. ...
...eters targetstring the string to perform regular expression matching upon. regexpstring the javascript style regular expression to evaluate. flagsstringoptional an optional string containing character flags. the character flags are: g global match the submatches from every match in the string are re
turned. if this flag isn't specified, only the submatches from the first match are re
turned. i case insensitive match if this flag is specified, the match is performed in a case insensitive fashion. re
turns a node set of match elements, each of which has the string value equal to a portion of the first parameter string as captured by the regular expression. if the match isn't a global one, the first match element has the value of the portion of the string matched by the entire r...
str:split() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:split() splits a string using a pattern string to determine where the splits should occur, re
turning a node-set containing the resulting strings. syntax str:split(string, pattern) parameters string the string to split. pattern the pattern indicating where to split the string. re
turns a node-set of token elements, each containing one token from the string. ...
... pattern string to determine where the splits should occur, re
turning a node-set containing the resulting strings. syntax str:split(string, pattern) parameters string the string to split. pattern the pattern indicating where to split the string. re
turns a node-set of token elements, each containing one token from the string. ...
str:tokenize() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:tokenize() splits a string using a set of characters as delimiters that determine where the splits should occur, re
turning a node-set containing the resulting strings. syntax str:tokenize(string, delimiters) parameters string the string to tokenize. delimiters each character in this string is used as a word separator while tokenizing. re
turns a node-set of token elements, each containing one token from the string. ...
...e splits should occur, re
turning a node-set containing the resulting strings. syntax str:tokenize(string, delimiters) parameters string the string to tokenize. delimiters each character in this string is used as a word separator while tokenizing. re
turns a node-set of token elements, each containing one token from the string. ...
Video player styling basics - Developer guides
llows the correct button image to be set via css changebuttonstate('playpause'); }); mute.addeventlistener('click', function(e) { video.muted = !video.muted; changebuttonstate('mute'); }); you might have noticed that there are new handlers where the play and pause events are reacted to on the video. there is a reason for this! even though the browser's default video control set has been
turned off, many browsers make them accessible by right clicking on the html5 video. this means that a user could play/pause the video from these controls, which would then leave the custom control set's buttons out of sync. if a user uses the default controls, the defined media api events — such as play and pause — are raised so this can be taken advantage of to ensure that the custom control but...
...are clicked, also changes — it now calls a new function called checkvolume(): var checkvolume = function(dir) { if (dir) { var currentvolume = math.floor(video.volume * 10) / 10; if (dir === '+') { if (currentvolume < 1) video.volume += 0.1; } else if (dir === '-') { if (currentvolume > 0) video.volume -= 0.1; } // if the volume has been
turned off, also set it as muted // note: can only do this with the custom control set as when the 'volumechange' event is raised, there is no way to know if it was via a volume or a mute change if (currentvolume <= 0) video.muted = true; else video.muted = false; } changebuttonstate('mute'); } var altervolume = function(dir) { checkvolume(dir); } this new checkvolume() fun...
Creating a cross-browser video player - Developer guides
</video> <figcaption>© blender foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the player's default control set is switched off later with javascript. doing things this way still allows users who have javascript
turned off (for whatever reason) to still have access to the browser's native controls. a poster image is defined for the video, and the preload attribute is set to metadata, which informs the browser that it should initially only attempt to load the metadata from the video file rather than the entire video file. this provides the player with data such as video duration and format. note: ie9 behave...
... if the browser is currently in fullscreen mode, then it must be exited and vice versa. support for the different prefixed versions of the relevant...
Audio and video manipulation - Developer guides
e src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> javascript this code handles altering the frames. ...
...for efficiency, you should consider using requestanimationframe() instead of settimeout() when running on browsers that support it. note: due to potential security issues if your video is on a different domain than your code, you'...
Challenge solutions - Developer guides
enge move the print-specific style rules to a separate css file and import them into your style4.css stylesheet. solution cut and paste the lines between /* print only */ and /* end print only */ into a file named style4_print.css. in style4.css, add the following line at the beginning of the file: @import url("style4_print.css") print; heading hover color challenge make the headings
turn blue when the mouse pointer is over them. solution the following rule achieves the desired result: h1:hover { color: blue; } javascript move box to the right challenge change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards. solution add lines to modify the margin-left property. be sure to specify it as marginleft in java...
... solution move the position of the :hover pseudo-class from a specific petal, to all petals #inner-petals { --segment-fill-fill-hover: pink; } /* non-standard way for some older browsers */ #inner-petals:hover .segment-fill { fill: pink; stroke: none; } ...
DOM onevent handlers - Developer guides
>`); log(`now even the html attribute has changed: <code> ${el.getattribute("onclick")} </code><br>`); result for historical reasons, some attributes/properties on the <body> and <frameset> elements instead set event handlers on their parent window object. (the html specification names these: onblur, onerror, onfocus, onload, and onscroll.) event handler's parameters, this binding, and the re
turn value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following parameters: event — for all event handlers except onerror. event, source, lineno, colno, and error for the onerror event handler. note that the event parameter actually contains the error message as a string. when the event handler is invoked, the this keyword ...
... event — for all event handlers except onerror. event, source, lineno, colno, and error for the onerror event handler. note that the event parameter actually contains the error message as a string. when the event handler is invoked, the this keyword inside the handler is set to the dom element on which the handler is registered. for more details, see the this keyword documentation. the re
turn value from the handler determines if the event is canceled. the specific handling of the re
turn value depends on the kind of event; for details, see "the event handler processing algorithm" in the html specification. when the event handler is invoked tbd (non-capturing listener) terminology the term event handler may refer to: any function or object that is registered to be notified of e...
HTML5 Parser - Developer guides
gecko 2 introduces a new parser, based on html5. the html parser is one of the most complicated and sensitive pieces of a browser. it controls how your html source code is
turned into web pages and, as such, changes to it are rare. the new parser is faster, complies with the html5 standard, and enables a lot of new functionality as well. the new parser introduces these major improvements: you can now use svg and mathml inline in html5 pages, without xml namespace syntax. parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. ...
...ou can now use svg and mathml inline in html5 pages, without xml namespace syntax. parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. calls to innerhtml are a lot faster. dozens of long-standing parser related bugs are now fixed. the html5 specification provides a more detailed description than previous html standards of how to
turn a stream of bytes into a dom tree. this will result in more consistent behavior across browser implementations. in other words, in supporting html5, gecko, webkit, and internet explorer (ie) will behave more consistently with each other. changed parser behaviors some changes to the way that the gecko 2 parser behaves, as compared to earlier versions of gecko, may affect web developers, dependin...
HTML5 - Developer guides
r those who have some basic familiarity and experience using html5. downloadable html5 guide a quick guide to html5, including the common html tags as well as the new html5 tags. downloadable in pdf and png formats. html5 cheat sheet a handy html 5 cheat sheet for beginners who want to master html 5, its elements, event attributes and compatibility. html5-compliant parser the parser, which
turns the bytes of an html document into a dom, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid html. this leads to far greater predictability and interoperability between html5-compliant browsers. connectivity web sockets allows creating a permanent connection between the page and the server and to exchange non-html data through that me...
...without the browser ui displayed. pointer lock api allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit. online and offline events in order to build a good offline-capable web application, you need to know when your application is actually offline. incidentally, you also need to know when your application has re
turned to an online status again. device access touch events handlers to react to events created by a user pressing touch screens. using geolocation let browsers locate the position of the user using geolocation. detecting device orientation get the information when the device on which the browser runs changes orientation. this can be used as an input device (e.g., to make games that react t...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
r sharkd on wikipedia, distributed under the cc by-sa 3.0 license. the value of the hue (h) component of an hsl color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. the value can be specified in any <angle> unit supported by css, including degrees (deg), radians (rad), gradians (grad), or
turns (
turn). but this doesn't control how vivid or dull, or how bright or dark the color is. the saturation (s) component of the color specifies what percentage of the final color is comprised of the specified hue. the rest is defined by the grey level provided by the luminance (l) component. think of it like creating the perfect paint color: you start with base paint that's the maximum intensit...
...head> <tr> <th scope="col">color in hsl notation</th> <th scope="col">example</th> </tr> </thead> <tbody> <tr> <td><code>hsl(90deg, 100%, 50%)</code></td> <td style="background-color: hsl(90deg, 100%, 50%);"> </td> </tr> <tr> <td><code>hsl(90, 100%, 50%)</code></td> <td style="background-color: hsl(90, 100%, 50%);"> </td> </tr> <tr> <td><code>hsl(0.15
turn, 50%, 75%)</code></td> <td style="background-color: hsl(0.15
turn, 50%, 75%);"> </td> </tr> <tr> <td><code>hsl(0.15
turn, 90%, 75%)</code></td> <td style="background-color: hsl(0.15
turn, 90%, 75%);"> </td> </tr> <tr> <td><code>hsl(0.15
turn, 90%, 50%)</code></td> <td style="background-color: hsl(0.15
turn, 90%, 50%);"> </td> </tr> <tr> <td><code>hsl(270deg...
HTML attribute reference - HTML: Hypertext Markup Language
example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element. the idl attribute is also known as a javascript property. these are the attributes you can read or set using javascript properties like element.foo. the idl attribute is always going to use (but might transform) the underlying content attribute to re
turn a value when you get it and is going to save something in the content attribute when you set it. in other words, the idl attributes, in essence, reflect the content attributes. most of the time, idl attributes will re
turn their values as they are really used. for example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text ...
...n essence, reflect the content attributes. most of the time, idl attributes will re
turn their values as they are really used. for example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". however, the type idl attribute will re
turn the string "text". idl attributes are not always strings; for example, input.maxlength is a number (a signed long). when using idl attributes, you read or set values of the desired type, so input.maxlength is always going to re
turn a number and when you set input.maxlength, it wants a number. if you pass another type, it is automatically converted to a number as specified by the standard javascr...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
eader), the image will be tainted and its usage restricted. when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. see cors settings attributes for additional information. currenttime reading currenttime re
turns a double-precision floating-point value indicating the current playback position, in seconds, of the audio. if the audio's metadata isn't available yet—thereby preventing you from knowing the media's start time or duration—currenttime instead indicates, and can be used to change, the time at which playback will begin. otherwise, setting currenttime sets the current playback position to the g...
...nologies (miracast, chromecast, dlna, airplay, etc). see this proposed specification for more information. in safari, you can use x-webkit-airplay="deny" as a fallback. duration read only a double-precision floating-point value which indicates the duration (total length) of the audio in seconds, on the media's timeline. if no media is present on the element, or the media is not valid, the re
turned value is nan. if the media has no known end (such as for live streams of unknown duration, web radio, media incoming from webrtc, and so forth), this value is +infinity. loop a boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio. muted a boolean attribute that indicates whether the audio will be initially silenced. i...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
the global attributes. the tabindex attribute must not be used on the <dialog> element. open indicates that the dialog is active and can be interacted with. when the open attribute is not set, the dialog shouldn't be shown to the user. usage notes <form> elements can close a dialog if they have the attribute method="dialog". when such a form is submitted, the dialog closes with its re
turnvalue property set to the value of the button that was used to submit the form. the ::backdrop css pseudo-element can be used to style behind a <dialog> element when the dialog is displayed with htmldialogelement.showmodal(). for example, to dim unreachable content behind the modal dialog. examples simple example <dialog open> <p>greetings, one and all!</p> </dialog> advanced example thi...
... living standard html 5.2the definition of '<dialog>' in that specification. recommendation initial definition ...
<input type="email"> - HTML: Hypertext Markup Language
e other explanatory text nearby. see the section pattern validation for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...xample.com"> offering suggested values taking it a step farther, you can provide a list of default options from which the user can select by specifying the list attribute. this doesn't limit the user to those options, but does allow them to select commonly-used e-mail addresses more quickly. this also offers hints to autocomplete. the list attribute specifies the id of a <datalist>, which in
turn contains one <option> element per suggested value; each option's value is the corresponding suggested value for the email entry box. <input type="email" size="40" list="defaultemails"> <datalist id="defaultemails"> <option value="jbond007@mi6.defence.gov.uk"> <option value="jbourne@unknown.net"> <option value="nfury@shield.org"> <option value="tony@starkindustries.com"> <option value=...
<input type="image"> - HTML: Hypertext Markup Language
ed to the server automatically by the browser — x and y. you can see this in action in our x y coordinates example. when you click on the image to submit the form, you'll see the data appended to the url as parameters, for example ?x=52&y=55. if the image input has a name attribute, then keep in mind that the specified name is prefixed on every attribute, so if the name is position, then the re
turned coordinates would be formatted in the url as ?position.x=52&position.y=55. this, of course, applies to all other attributes as well. these are the x and y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image. these can be used when the position the image was clicked on is significant, for example you might have a map that when clicked,...
...s well. these are the x and y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image. these can be used when the position the image was clicked on is significant, for example you might have a map that when clicked, sends the coordinates that were clicked to the server. the server-side code then works out what location was clicked on, and re
turns information about places nearby. in our above example, we could write server-side code that works out what color was clicked on by the coordinates submitted, and keeps a tally of the favorite colors people voted for. adjusting the image's position and scaling algorithm you can use the object-position property to adjust the positioning of the image within the <input> element's frame, and the o...
<input type="number"> - HTML: Hypertext Markup Language
t has no minimum value. this value must be less than or equal to the value of the max attribute. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
...each option's value is the corresponding suggested value for the number entry box. <input id="ticketnum" type="number" name="ticketnum" list="defaultnumbers"> <span class="validity"></span> <datalist id="defaultnumbers"> <option value="10045678"> <option value="103421"> <option value="11111111"> <option value="12345678"> <option value...
<input type="password"> - HTML: Hypertext Markup Language
entered anything yet, this value is an empty string (""). if the required property is specified, then the password edit box must contain a value other than an empty string to be valid. if the pattern attribute is specified, the content of a password control is only considered valid if the value passes validation; see validation for more information. note: the line feed (u+000a) and carriage re
turn (u+000d) characters are not permitted in a password value. when setting the value of a password control, line feed and carriage re
turn characters are stripped out of the value. additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, password field inputs support the following attributes: attribute description ...
...d/or punctuation characters, and so forth. see the section validation for details and an example. placeholder the placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage re
turns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid us...
<select>: The HTML Select element - HTML: Hypertext Markup Language
e number of rows in the list that should be visible at one time. browsers are not required to present a select element as a scrolled list box. the default value is 0. note: according to the html5 specification, the default value for size should be 1; however, in practice, this has been found to break some web sites, and no other browser currently does that, so mozilla has opted to continue to re
turn 0 for the time being with firefox. usage notes selecting multiple options on a desktop computer, there are a number of ways to select multiple options in a <select> element with a multiple attribute: mouse users can hold the ctrl, command, or shift keys (depending on what makes sense for your operating system) and then click multiple options to select/deselect them. warning: the mechanis...
...es sense for your operating system) and then click multiple options to select/deselect them. warning: the mechanism for selecting multiple non-contiguous items via the keyboard described below currently only seems to work in firefox. also note: on macos, the ctrl + up and ctrl + down shortcuts conflict with the os default shortcuts for mission control and application windows, so you'll have to
turn these off before it will work. keyboard users can select multiple contiguous items by: focusing on the <select> element (e.g. using tab). selecting an item at the top or bottom of the range they want to select using the up and down cursor keys to go up and down the options. holding down the shift key and then using the up and down cursor keys to increase or decrease the range of items sele...
HTML elements reference - HTML: Hypertext Markup Language
late element (<bdi>) tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. <bdo> the html bidirectional text override element (<bdo>) overrides the current directionality of text, so that the text within is rendered in a different direction. <br> the html <br> element produces a line break in text (carriage-re
turn). it is useful for writing a poem or an address, where the division of lines is significant. <cite> the html citation element (<cite>) is used to describe a reference to a cited creative work, and must include the title of that work. <code> the html <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of comput...
... javascript. certain elements support this capability. element description <canvas> use the html <canvas> element with either the canvas scripting api or the webgl api to draw graphics and animations. <noscript> the html <noscript> element defines a section of html to be inserted if a script type on the page is unsupported or if scripting is currently
turned off in the browser. <script> the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code. demarcating edits these elements let you provide indications that specific parts of the text have been altered. element description <del> the html <del> element represents a range of t...
Range - HTTP
the range http request header indicates the part of a document that the server should re
turn. several parts can be requested with one range header at once, and the server may send back these ranges in a multipart document. if the server sends back ranges, it uses the 206 partial content for the response. if the ranges are invalid, the server re
turns the 416 range not satisfiable error. the server can also ignore the range header and re
turn the whole document with a 200 status code. header type request header forbidden header name no syntax range: <unit>=<range-start>- range: <unit>=<range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range...
...usually bytes. <range-start> an integer in the given unit indicating the beginning of the request range. <range-end> an integer in the given unit indicating the end of the requested range. this value is optional and, if omitted, the end of the document is taken as the end of the range. <suffix-length> an integer in the given unit indicating the number of units at the end of the file to re
turn. examples requesting three ranges from the file. range: bytes=200-1000, 2000-6576, 19000- requesting the first 500 and last 500 bytes of the file. the request may be rejected by the server if the ranges overlap. range: bytes=0-499, -500 specifications specification title rfc 7233, section 3.1: range hypertext transfer protocol (http/1.1): range requests ...
HTTP headers - HTTP
e size of the resource, in decimal number of bytes. content-type indicates the media type of the resource. content-encoding used to specify the compression algorithm. content-language describes the human language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. content-location indicates an alternate location for the re
turned data. proxies forwarded contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request. x-forwarded-for identifies the originating ip addresses of a client connecting to a web server through an http proxy or a load balancer. x-forwarded-host identifies the original host requested that a client used to c...
...erence. response context allow lists the set of http request methods supported by a resource. server contains information about the software used by the origin server to handle the request. range requests accept-ranges indicates if the server supports range requests, and if so in which unit the range can be expressed. range indicates the part of a document that the server should re
turn. if-range creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. used to prevent downloading two ranges from incompatible version of the resource. content-range indicates where in a full body message a partial message belongs. security cross-origin-embedder-policy (coep) allows a server to declare an embedder policy for a given ...
A typical HTTP session - HTTP
everal techniques: ping the server periodically via the xmlhttprequest, fetch apis, using the websockets api, or similar protocols. sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). a client request consists of text directives, separated by crlf (carriage re
turn, followed by line feed), divided into three blocks: the first line contains a request method followed by its parameters: the path of the document, i.e. an absolute url without the protocol or domain name the http protocol version subsequent lines represent an http header, giving the server information about what type of data is appropriate (e.g., what language, what mime types),...
...t common requests are get and post: the get method requests a data representation of the specified resource. requests using get should only retrieve data. the post method sends data to a server so it may change its state. this is the method often used for html forms. structure of a server response after the connected agent has sent its request, the web server processes it, and ultimately re
turns a response. similar to a client request, a server response is formed of text directives, separated by crlf, though divided into three blocks: the first line, the status line, consists of an acknowledgment of the http version used, followed by a status request (and its brief meaning in human-readable text). subsequent lines represent specific http headers, giving the client information about ...
Introduction - JavaScript
ial declarative requirements. functions can be properties of objects, executing as loosely typed methods. javascript is a very free-form language compared to java. you do not have to declare all variables, classes, and methods. you do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. variables, parameters, and function re
turn types are not explicitly typed. java is a class-based programming language designed for fast execution and type safety. type safety means, for instance, that you can't cast a java integer into an object reference or access private memory by corrupting java bytecodes. java's class-based model means that programs consist exclusively of classes and their methods. java's class inheritance and strong...
...hift+i on windows and linux or cmd-option-k on mac), open the tools menu in firefox, and select "developer ▶ web console". the web console appears at the bottom of the browser window. along the bottom of the console is an input line that you can use to enter javascript, and the output appears in the panel above: the console works the exact same way as eval: the last expression entered is re
turned. for the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by console.log around eval, like so: function greetme(yourname) { alert("hello " + yourname) } console.log(eval('3 + 5')) multi-line input in the web console the single-line input mode of the web console is great for quick testing of javascript expressions, but ...
Groups and ranges - JavaScript
ups themselves. this becomes important when capturing groups are nested. matches are accessed using the index of the the result's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9). capturing groups have a performance penalty. if you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below). string.match() won't re
turn groups if the /.../g flag is set. however, you can still use string.matchall() to get all matches. \n where "n" is a positive integer. a back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses). for example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". \k<name> ...
...last substring matching the named capture group specified by <name>. for example, /(?<title>\w+), yes \k<title>/ matches "sir, yes sir" in "do you copy? sir, yes sir!". \k is used literally here to indicate the beginning of a back reference to a named capture group. (?<name>x) named capturing group: matches "x" and stores it on the groups property of the re
turned matches under the name specified by <name>. the angle brackets (< and >) are required for group name. for example, to extract the united states area code from a phone number, we could use /\((?<area>\d\d\d)\)/. the resulting number would appear under matches.groups.area. (?:x) non-capturing group: matches "x" but does not remember the match. the matched substring cannot be ...
extends - JavaScript
o (source). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference error. ...
... error. this.name = 'square'; } get area() { re
turn this.height * this.width; } } using extends with built-in objects this example extends the built-in date object. this example is extracted from this live demo (source). class mydate extends date { getformatteddate() { var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; re
turn this.getdate() + '-' + months[this.getmonth()] + '-' + this.getfullyear(); } } specifications specification ecmascript (ecma-262)the definition of 'extends' in that specification. ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
g browsers: /*globals define*/ // assumes all supplied string instance methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(string).filter(function(methodname) { // re
turn typeof string[methodname] === 'function'; // }); methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', 'trim', 'trimleft', 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'conca...
... 'trim', 'trimleft', 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'concat', 'localecompare' ], methodcount = methods.length, assignstringgeneric = function(methodname) { var method = string.prototype[methodname]; string[methodname] = function(arg1) { re
turn method.apply(arg1, array.prototype.slice.call(arguments, 1)); }; }; for (i = 0; i < methodcount; i++) { assignstringgeneric(methods[i]); } }()); ...
ReferenceError: deprecated caller or arguments usage - JavaScript
dn't be. they are deprecated, because they leak the function caller, are non-standard, hard to optimize and potentially a performance-harmful feature. examples deprecated function.caller or arguments.callee.caller function.caller and arguments.callee.caller are deprecated (see the reference articles for more information). 'use strict'; function myfunc() { if (myfunc.caller == null) { re
turn 'the function was called from the top!'; } else { re
turn 'this function\'s caller was ' + myfunc.caller; } } myfunc(); // warning: referenceerror: deprecated caller usage // "the function was called from the top!" function.arguments function.arguments is deprecated (see the reference article for more information). 'use strict'; function f(n) { g(n - 1); } function g(n) { console.l...
...c(); // warning: referenceerror: deprecated caller usage // "the function was called from the top!" function.arguments function.arguments is deprecated (see the reference article for more information). 'use strict'; function f(n) { g(n - 1); } function g(n) { console.log('before: ' + g.arguments[0]); if (n > 0) { f(n); } console.log('after: ' + g.arguments[0]); } f(2); console.log('re
turned: ' + g.arguments); // warning: referenceerror: deprecated arguments usage ...
TypeError: setting getter-only property "x" - JavaScript
the example below shows how to set a getter for a property. it doesn't specify a setter, so a typeerror will be thrown upon trying to set the temperature property to 30. for more details see also the object.defineproperty() page. ...
...roperty "temperature" to fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this: "use strict"; function archiver() { var temperature = null; var archive = []; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); re
turn temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { re
turn archive; }; } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getarchive(); // [{ val: 11 }, { val: 13 }] ...
ReferenceError: "x" is not defined - JavaScript
that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of execution. ...
...numbers() { var num1 = 2, num2 = 3; re
turn num1 + num2; } console.log(num1); // referenceerror num1 is not defined. however, a function can access all variables and functions defined inside the scope in which it is defined. in other words, a function defined in the global scope can access all variables defined in the global scope. ...
TypeError: Reduce of empty array with no initial value - JavaScript
array.prototype.reduce(), typedarray.prototype.reduceright()). these functions optionally take an initialvalue (which will be used as the first argument to the first call of the callback). however, if no initial value is provided, it will use the first element of the array or typedarray as the initial value. this error is raised when an empty array is provided because no initial value can be re
turned in that case. examples invalid cases this problem appears frequently when combined with a filter (array.prototype.filter(), typedarray.prototype.filter()) which will remove all elements of the list. thus leaving none to be used as the initial value. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y) // no more elements...
...n the callback after adding an unexpected dummy initial value. var names = document.getelementsbyclassname("names"); var name_list1 = ""; if (names1.length >= 1) name_list1 = array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); // name_list1 == "" when names is empty. var name_list2 = array.prototype.reduce.call(names, (acc, name) => { if (acc == "") // initial value re
turn name; re
turn acc + ", " + name; }, ""); // name_list2 == "" when names is empty. ...
JavaScript error reference - JavaScript
ter property idsyntaxerror: missing ; before statementsyntaxerror: missing = in const declarationsyntaxerror: missing ] after element listsyntaxerror: missing formal parametersyntaxerror: missing name after . ...
...lformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after re
turn statement ...
Method definitions - JavaScript
thod definitions are not constructable methods cannot be constructors! they will throw a typeerror if you try to instantiate them. ...
...method // typeerror: obj.method is not a constructor const objb = { * g() {} } new objb.g // typeerror: obj.g is not a constructor (changed in es2016) examples simple test case const obj = { a: 'foo', b() { re
turn this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names. const bar = { foo0: function() { re
turn 0 }, foo1() { re
turn 1 }, ['foo' + 2]() { re
turn 2 } } console.log(bar.foo0()) // 0 console.log(bar.foo1()) // 1 console.log(bar.foo2()) // 2 // a global function function foo() { re
turn 1 } let name = 'foo' console.log(window[name]()) // 1 specifications specification ecmascript (ecma-262)the definition of 'method definitions' in that specification. ...
Array.prototype[@@iterator]() - JavaScript
the @@iterator method is part of the iterable protocol, that defines how to synchronously iterate over a sequence of values. the initial value of the @@iterator property is the same function object as the initial value of the values() property. syntax arr[symbol.iterator]() re
turn value the initial value given by the values() iterator. by default, using arr[symbol.iterator] will re
turn the values() function. examples iteration using for...of loop html <ul id="letterresult"> </ul> javascript var arr = ['a', 'b', 'c']; var earr = arr[symbol.iterator](); var letterresult = document.getelementbyid('letterresult'); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of earr) { letterresult.innerhtml += "...
... iterate over the value, but don't know if that object is going to have a [iterable].prototype.values method. this could be a built-in object like string object or a custom object. ...
get Array[@@species] - JavaScript
the array[@@species] accessor property re
turns the array constructor. syntax array[symbol.species] re
turn value the array constructor. description the species accessor property re
turns the default constructor for array objects. subclass constructors may override it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the array constructor for array objects: array[symbol.species]; // function array() species in derived objects in a derived collection object (e.g. your custom array myarray), the myarray species is the myarray constructor. ...
...nt. examples species in ordinary objects the species property re
turns the default constructor function, which is the array constructor for array objects: array[symbol.species]; // function array() species in derived objects in a derived collection object (e.g. your custom array myarray), the myarray species is the myarray constructor. however, you might want to overwrite this, in order to re
turn parent array objects in your derived class methods: class myarray extends array { // overwrite myarray species to the parent array constructor static get [symbol.species]() { re
turn array; } } specifications specification ecmascript (ecma-262)the definition of 'get array [ @@species ]' in that specification. ...
Array.prototype.concat() - JavaScript
the concat() method is used to merge two or more arrays. this method does not change the existing arrays, but instead re
turns a new array. 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 new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a new array. if all valuen parameters are omitted, concat re
turns a shallow copy of the existing array on which it is called. see the description below for more details. re
turn value a new array instance. description the concat method creates a new array consisting of the eleme...
...ncat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). it does not recurse into nested array arguments. the concat method does not alter this or any of the arrays provided as arguments but instead re
turns a shallow copy that contains copies of the same elements combined from the original arrays. elements of the original arrays are copied into the new array as follows: object references (and not the actual object): concat copies object references into the new array. both the original and new array refer to the same object. that is, if a referenced object is modified, the changes are visible to ...
Array.prototype.join() - JavaScript
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 arr.join([separator]) parameters separator optional specifies a string to separate each pair of adjacent elements of the array. the separator is converted to a string if necessary. if omitted, the array elements are separated with a comma (","). ...
...e-examples and send us a pull request. syntax arr.join([separator]) parameters separator optional specifies a string to separate each pair of adjacent elements of the array. the separator is converted to a string if necessary. if omitted, the array elements are separated with a comma (","). if separator is an empty string, all elements are joined without any characters in between them. re
turn value a string with all array elements joined. if arr.length is 0, the empty string is re
turned. description the string conversions of all array elements are joined into one string. if an element is undefined, null or an empty array [], it is converted to an empty string. examples joining an array four different ways the following example creates an array, a, with three elements, then jo...
Array.prototype.push() - JavaScript
description the push method appends values to an array. push is intentionally generic. this method can be used with call() or apply() on objects resembling arrays. ...
... description the push method appends values to an array. push is intentionally generic. this method can be used with call() or apply() on objects resembling arrays. the push method relies on a length property to determine where to start inserting the given values. ...
Array.prototype.toString() - JavaScript
javascript calls the tostring method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ecmascript 5 semantics starting in javascript 1.8.5 (firefox 4), and consistent with ecmascript 5th edition semantics, the tostring() method is generic and can be used with any object. ...
...ing method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. ecmascript 5 semantics starting in javascript 1.8.5 (firefox 4), and consistent with ecmascript 5th edition semantics, the tostring() method is generic and can be used with any object. object.prototype.tostring() will be called, and the resulting value will be re
turned. examples using tostring const array1 = [1, 2, 'a', '1a']; console.log(array1.tostring()); // expected output: "1,2,a,1a" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification. ...
get ArrayBuffer[@@species] - JavaScript
the arraybuffer[@@species] accessor property re
turns the arraybuffer constructor. description the species accessor property re
turns the default constructor for arraybuffer objects. subclass constructors may over-ride it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the arraybuffer constructor for arraybuffer objects: arraybuffer[symbol.species]; // function arraybuffer() species in derived objects in a derived collection object (e.g. your custom array buffer myarraybuffer), the myarraybuffer species is the myarraybuffer constructor. ...
...pecies property re
turns the default constructor function, which is the arraybuffer constructor for arraybuffer objects: arraybuffer[symbol.species]; // function arraybuffer() species in derived objects in a derived collection object (e.g. your custom array buffer myarraybuffer), the myarraybuffer species is the myarraybuffer constructor. however, you might want to overwrite this, in order to re
turn parent arraybuffer objects in your derived class methods: class myarraybuffer extends arraybuffer { // overwrite myarraybuffer species to the parent arraybuffer constructor static get [symbol.species]() { re
turn arraybuffer; } } specifications specification ecmascript (ecma-262)the definition of 'get arraybuffer [ @@species ]' in that specification. ...
ArrayBuffer - JavaScript
tructor creates a new arraybuffer of the given length in bytes. you can also get an array buffer from existing data, for example from a base64 string or from a local file. constructor arraybuffer() creates a new arraybuffer object. static properties get arraybuffer[@@species] the constructor function that is used to create derived objects. ...
... from existing data, for example from a base64 string or from a local file. constructor arraybuffer() creates a new arraybuffer object. static properties get arraybuffer[@@species] the constructor function that is used to create derived objects. static methods arraybuffer.isview(arg) re
turns true if arg is one of the arraybuffer views, such as typed array objects or a dataview. re
turns false otherwise. instance properties arraybuffer.prototype.bytelength the read-only size, in bytes, of the arraybuffer. this is established when the array is constructed and cannot be changed. instance methods arraybuffer.prototype.slice() re
turns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin (inclusive) up to end (exclusive). if either begin or e...
AsyncFunction - JavaScript
from the scope in which the asyncfunction constructor was called. this is different from using eval with code for an async function expression. invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. ...
...king it as a constructor. examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { re
turn new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 're
turn await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); specifications specification ecmascript (ecma-262)the definition of 'asyncfunction object' in that specification. ...
Atomics.load() - JavaScript
exceptions throws a typeerror, if typedarray is not one of the allowed integer types. ...
...to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.load(typedarray, index) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to load from. re
turn value the value at the given position (typedarray[index]). exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror, if index is out of bounds in the typedarray. examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specifi...
Atomics.wait() - JavaScript
the static atomics.wait() method verifies that a given position in an int32array still contains a given value and if so sleeps, awaiting a wakeup or a timeout. it re
turns a string which is either "ok", "not-equal", or "timed-out". note: this operation only works with a shared int32array and may not be allowed on the main thread. syntax atomics.wait(typedarray, index, value[, timeout]) parameters typedarray a shared int32array. index the position in the typedarray to wait on. value the expected value to test. timeout optional time to wait in milliseconds. infinity, if no time is provided. re
turn value a string which is either "ok", "not-equal", or "timed-out". exceptions throws a typeerror, if typedarray is not a shared int32array. throws a rangeerror, if index is out ...
... is out of bounds in the typedarray. examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0. as long as that is true, it will not go on. however, once the writing thread has stored a new value, it will be notified by the writing thread and re
turn the new value (123). atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stores a new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; atomics.store(int32, 0, 123); atomics.notify(int32, 0, 1); specifications specification ecmascript (ecma-262)the definition of 'atomics.wait' in that specification. ...
Boolean.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified boolean object. 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 bool.tostring() re
turn value a string representing the specified boolean object. description the boolean object overrides the tostring method of the object object; it does not inherit object.prototype.tostring(). for boolean objects, the tostring method re
turns a string representation of the object. javascript calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean o...
...g method of the object object; it does not inherit object.prototype.tostring(). for boolean objects, the tostring method re
turns a string representation of the object. javascript calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean objects and values, the built-in tostring() method re
turns the string "true" or "false" depending on the value of the boolean object. examples using tostring() in the following code, flag.tostring() re
turns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification. ...
Date() constructor - JavaScript
ject, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new date() new date(value) new date(datestring) new date(year, monthindex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) note: the only correct way to instantiate a new date object is by using the new operator. if you simply call the date object directly, such as now = date(), the re
turned value is a string rather than a date object. parameters there are four basic forms for the date() constructor: no parameters when no parameters are provided, the newly-created date object represents the current date and time as of the time of instantiation. time value or timestamp number value an integer value representing the number of milliseconds since january 1, ...
... works the same way) is strongly discouraged due to browser differences and inconsistencies. support for rfc 2822 format strings is by convention only. support for iso 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as utc, not local. individual date and time component values given at least a year and month, this form of date() re
turns a date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. any missing fields are given the lowest possible value (1 for day and 0 for every other component). year integer value representing the year. values from 0 to 99 map to the years 1900 to 1999. all other values are the actual year. see the exampl...
Date.prototype.getDate() - JavaScript
examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95. ...
... examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95. ...
Date.prototype.getDay() - JavaScript
examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95. ...
... of the week for the specified date according to local time, where 0 represents sunday. for the day of the month, see date.prototype.getdate(). 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 dateobj.getday() re
turn value an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for sunday, 1 for monday, 2 for tuesday, and so on. examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95. december 25, 1995, is a monday. var xmas95 = new date('december 25, 1995 23:15:30'); va...
Date.prototype.getHours() - JavaScript
examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. ...
... examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95. ...
Date.prototype.getMonth() - JavaScript
0 corresponds to january, 1 to february, and so on. examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95. ...
...0 corresponds to january, 1 to february, and so on. examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95. ...
Date.prototype.getSeconds() - JavaScript
examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. ...
... examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95. ...
Date.prototype.getTime() - JavaScript
the gettime() method re
turns the number of milliseconds* since the unix epoch. * javascript uses milliseconds as the unit of measurement, whereas unix time is in seconds. gettime() always uses utc for time representation. for example, a client browser in one timezone, gettime() will be the same as a client browser in any other timezone. you can use this method to help assign a date and time to another date object. this method is functionally equivalent to the valueof() method. 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. ...
...you can use this method to help assign a date and time to another date object. this method is functionally equivalent to the valueof() method. 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 dateobj.gettime() re
turn value a number representing the milliseconds elapsed between 1 january 1970 00:00:00 utc and the given date. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of new date().gettime() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 5...
Date.prototype.getUTCDate() - JavaScript
examples using getutcdate() the following example assigns the day portion of the current date to the variable day. ...
... examples using getutcdate() the following example assigns the day portion of the current date to the variable day. ...
Date.prototype.getUTCDay() - JavaScript
examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday. ...
... examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday. ...
Date.prototype.getUTCHours() - JavaScript
examples using getutchours() the following example assigns the hours portion of the current time to the variable hours. ...
... examples using getutchours() the following example assigns the hours portion of the current time to the variable hours. ...
Date.prototype.getUTCMinutes() - JavaScript
examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes. ...
... examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes. ...
Date.prototype.getUTCMonth() - JavaScript
0 for january, 1 for february, 2 for march, and so on. examples using getutcmonth() the following example assigns the month portion of the current date to the variable month. ...
...rns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year). 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 dateobj.getutcmonth() re
turn value an integer number, between 0 and 11, corresponding to the month of the given date according to universal time. 0 for january, 1 for february, 2 for march, and so on. examples using getutcmonth() the following example assigns the month portion of the current date to the variable month. var today = new date(); var month = today.getutcmonth(); specifications specification ...
Date.prototype.getUTCSeconds() - JavaScript
examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds. ...
... examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds. ...
Date.prototype.setFullYear() - JavaScript
the setfullyear() method sets the full year for a specified date according to local time. re
turns new timestamp. 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 dateobj.setfullyear(yearvalue[, monthvalue[, datevalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995. monthvalue optional. an integer between 0 and 11 representing the months january through december. datevalue optional. an integer between 1 and 31 representing the day of the month. ...
...value[, monthvalue[, datevalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995. monthvalue optional. an integer between 0 and 11 representing the months january through december. datevalue optional. an integer between 1 and 31 representing the day of the month. if you specify the datevalue parameter, you must also specify the monthvalue. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the monthvalue and datevalue parameters, the values re
turned from the getmonth() and getdate() methods are used. if a parameter you specify is outside of the expected range, setfullyear() attempts to update the other parameters and the date information in the date objec...
Date.prototype.setHours() - JavaScript
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 dateobj.sethours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) versions prior to javascript 1.3 dateobj.sethours(hoursvalue) parameters hoursvalue ideally, an integer between 0 and 23, representing the hour. ...
...mented by the extra seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. ideally, a number between 0 and 999, representing the milliseconds. if a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. re
turn value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values re
turned from the getminutes(), getseconds(), and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, sethours() attempts to update the date information in t...
Date.prototype.setMonth() - JavaScript
rior to javascript 1.3 dateobj.setmonth(monthvalue) parameters monthvalue a zero-based integer representing the month of the year offset from the start of the year. so, 0 represents january, 11 represents december, -1 represents december of the previous year, and 12 represents january of the following year. dayvalue optional. an integer from 1 to 31, representing the day of the month. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the dayvalue parameter, the value re
turned from the getdate() method is used. if a parameter you specify is outside of the expected range, setmonth() attempts to update the date information in the date object accordingly. for example, if you use 15 for monthvalue, the y...
...ts to update the date information in the date object accordingly. for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month. the current day of month will have an impact on the behaviour of this method. conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to re
turn the new date. for example, if the current value is 31st august 2016, calling setmonth with a value of 1 will re
turn 2nd march 2016. this is because in 2016 february had 29 days. examples using setmonth() var thebigday = new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth = new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar ...
Date.prototype.setUTCHours() - JavaScript
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 dateobj.setutchours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) parameters hoursvalue an integer between 0 and 23, representing the hour. minutesvalue optional. an integer between 0 and 59, representing the minutes. ...
...al. an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. re
turn value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values re
turned from the getutcminutes(), getutcseconds(), and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutchours() attempts to update the date info...
Date.prototype.toDateString() - JavaScript
the todatestring() method re
turns the date portion of a date object in english in the following format separated by spaces: first three letters of the week day name first three letters of the month name two digit day of the month, padded on the left a zero if necessary four digit year (at least), padded on the left with zeros if necessary e.g. "thu jan 01 1970". 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 dateobj.todatestring() re
turn value a string representing the date portion of the given date object in human readable form in english. description date instances refer to a specific point in...
...in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). ...
Date.prototype.toUTCString() - JavaScript
using the utc time zone. based on rfc7231 and modified according to ecma-262 toutcstring, it can have negative values in the 2021 version 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 dateobj.toutcstring() re
turn value a string representing the given date using the utc time zone. description the value re
turned by toutcstring() is a string in the form www, dd mmm yyyy hh:mm:ss gmt, where: format sring description www day of week, as three letters (e.g. sun, mon, ...) dd day of month, as two digits with leading zero if required mmm month, as three lett...
...equired mmm month, as three letters (e.g. jan, feb, ...) yyyy year, as four or more digits with leading zeroes if required hh hour, as two digits with leading zero if required mm minute, as two digits with leading zero if required ss seconds, as two digits with leading zero if required prior to ecmascript 2018, the format of the re
turn value varied according to the platform. the most common re
turn value was an rfc-1123 formatted date stamp, which is a slightly updated version of rfc-822 date stamps. examples using toutcstring() let today = new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)...
Date.prototype.valueOf() - JavaScript
this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. ...
... this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. ...
Error - JavaScript
o the file that raised this error. error.prototype.linenumber a non-standard mozilla property for the line number in the file that raised this error. error.prototype.columnnumber a non-standard mozilla property for the column number in the line that raised this error. error.prototype.stack a non-standard mozilla property for a stack trace. instance methods error.prototype.tostring() re
turns a string representing the specified object. overrides the object.prototype.tostring() method. examples throwing a generic error usually you create an error object with the intention of raising it using the throw keyword. you can handle the error using the try...catch construct: try { throw new error('whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } handling a specifi...
...constructor in the stack trace when using a prototypal declaration. ...
Function.displayName - JavaScript
the function.displayname property re
turns the display name of the function. examples setting a displayname it is usually preferred by consoles and profilers over func.name to display the name of a function. ...
...the display name of the function. examples setting a displayname it is usually preferred by consoles and profilers over func.name to display the name of a function. ...
Function.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the source code of the function. 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 function.tostring() re
turn value a string representing the source code of the function. description the function object overrides the tostring method inherited from object; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring method re
turns a string containing the source text segment which was used to define the function. javascript calls the tostring method automatically when a function is to be represented as a text value, e.g. w...
...hen a function is concatenated with a string. the tostring() method will throw a typeerror exception ("function.prototype.tostring called on incompatible object"), if its this value object is not a function object. function.prototype.tostring.call('foo'); // typeerror if the tostring() method is called on built-in function objects or a function created by function.prototype.bind, tostring() re
turns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is called on a function created by the function constructor, tostring() re
turns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body. examples comparing actual source code and tostring results function functi...
Intl.Collator.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
...urns a new object with properties reflecting the locale and collation options computed during initialization of this collator object. 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 collator.resolvedoptions() re
turn value a new object with properties reflecting the locale and collation options computed during the initialization of the given collator object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs...
Intl.Collator - JavaScript
jects enable language sensitive string comparison. 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. constructor intl.collator() creates a new collator object. ...
...ect. static methods intl.collator.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.collator.prototype.compare getter function that compares two strings according to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and collation options computed during initialization of the object. examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().comp...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
at formatters. 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 intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and re
turns an array of objects containing the locale-specific tokens representing each part of the formatted date range. let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); // > 'wed, 10 jan 2007 10:00:00 gmt' // > 'wed, 10 jan 2007 11:00:00 gmt' let fmt = new intl.datetimeformat("en", { hour: 'numeric', minute: 'numeric' }); console.log(...
...te range. ...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.datetimeformat.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this datetimeformat object. 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 datetimeformat.resolvedoptions() re
turn value a new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicod...
...rted for this locale are included in locale. calendar e.g. "gregory" numberingsystem the values requested using the unicode extension keys "ca" and "nu" or filled in as default values. timezone the value provided for this property in the options argument; undefined (representing the runtime's default time zone) if none was provided. warning: applications should not rely on undefined being re
turned, as future versions may re
turn a string value identifying the runtime’s default time zone instead. hour12 the value provided for this property in the options argument or filled in as a default. weekday era year month day hour minute second timezonename the values resulting from format matching between the corresponding properties in the options argument and the available combinati...
Intl.DisplayNames.prototype.of() - JavaScript
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 displaynames.of(code); parameters code the code to provide depends on the type: if the type is "region", code should be either an iso-3166 two letters region code, or a three digits un m49 geographic regions. if the type is "script", code should be an iso-15924 four letters script code. ...
...ype is "language", code should be a languagecode ["-" scriptcode] ["-" regioncode ] *("-" variant ) subsequence of the unicode_language_id grammar in uts 35's unicode language and locale identifiers grammar. languagecode is either a two letters iso 639-1 language code or a three letters iso 639-2 language code. if the type is "currency", code should be a 3-letter iso 4217 currency code. re
turn value a language-specific formatted string. examples using the of method let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" let languagenames = new intl.displaynames(['en'], {type: 'language'}); languagenames.of('fr'); // "french" let currencynames = new intl.displaynames(['en'], {type: 'currency'}); currencynames.of('eur'); // "euro...
Intl.DisplayNames - JavaScript
region and script display names. 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. constructor intl.displaynames() creates a new intl.displaynames object. ...
...amples and send us a pull request. constructor intl.displaynames() creates a new intl.displaynames object. static methods intl.displaynames.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and re
turns a string based on the locale and options provided when instantiating intl.displaynames. intl.displaynames.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples region code display names to create an intl.displaynames for a locale and get the display name for a region code. // get...
Intl.ListFormat.prototype.format() - JavaScript
the locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list. examples using format the following example shows how to create a list formatter using the english language. ...
...the locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list. examples using format the following example shows how to create a list formatter using the english language. ...
Intl.Locale.prototype.language - JavaScript
examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag. ...
... examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag. ...
Intl.Locale.prototype.maximize() - JavaScript
tl.locale.prototype.maximize() method gets the most likely values for the language, script, and region of the locale based on existing values. 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 locale.maximize() re
turn value a locale instance whose basename property re
turns the result of the add likely subtags algorithm executed against locale.basename. description sometimes, it is convenient to be able to identify the most likely locale language identifier subtags based on an incomplete langauage id. the add likely subtags algorithm gives us this functionality. for instance, given the language id "en", the ...
...this functionality is provided to javascript programmers via the maximize() method. ...
Intl.Locale.prototype.toString() - JavaScript
the intl.locale.prototype.tostring() re
turns the locale's full locale identifier string. 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 locale.tostring() re
turn value the locale's unicode locale identifier string. description the locale object is a javascript representation of a concept unicode locale identifier. information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. to make it easier to work with these locale identifiers, the locale object was introduced to javascript. ...
...ifier string. description the locale object is a javascript representation of a concept unicode locale identifier. information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. to make it easier to work with these locale identifiers, the locale object was introduced to javascript. calling the tostring method on a locale object will re
turn the identifier string for that particular locale. the tostring method allows locale instances to be provided as an argument to existing intl constructors, serialized in json, or any other context where an exact string representation is useful. examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints...
Intl.NumberFormat() constructor - JavaScript
ysign option to "accounting". the default value is "standard". localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. notation the formatting that should be displayed for the number, the defaults is "standard" "standard" plain number formatting "scientific" re
turn the order-of-magnitude for formatted number. "engineering" re
turn the exponent of ten when divisible by three "compact" string representing exponent, defaults is using the "short" form. numberingsystem numbering system. possible values include: "arab", "arabext", " bali", "beng", "deva", "fullwide", " gujr", "guru", "hanidec", "khmr", " knda", "laoo", "latn", "limb", "mlym", " mon...
...inimumsignificantdigits the minimum number of significant digits to use. possible values are from 1 to 21; the default is 1. maximumsignificantdigits the maximum number of significant digits to use. possible values are from 1 to 21; the default is 21. examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is re
turned. let amount = 3500; console.log(new intl.numberformat().format(amount)); // → '3,500' if in us english locale decimal and percent formatting let amount = 3500; new intl.numberformat('en-us', {style: 'decimal'}).format(amount); // → '3,500' new intl.numberformat('en-us', {style: 'percent'}).format(amount); // → '350,000%' unit formatting if the style is 'unit', a unit property must...
Intl.PluralRules.select() - JavaScript
description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. ...
... description this function selects a pluralization category according to the locale and formatting options of a pluralrules object. ...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
the intl.relativetimeformat.prototype.formattoparts() method re
turns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. 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 relativetimeformat.formattoparts(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". ...
...m/mdn/interactive-examples and send us a pull request. syntax relativetimeformat.formattoparts(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. re
turn value an array of objects containing the formatted relative time in parts. description the intl.relativetimeformat.prototype.formattoparts method is a version of the format method which it re
turns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating it from other surrounding text. these objects have two properties: ...
JSON - JavaScript
r members , jsonstring : json jsonarray = [ ] or [ arrayelements ] arrayelements = json or arrayelements , json insignificant whitespace may be present anywhere except within a jsonnumber (numbers must contain no whitespace) or jsonstring (where it is interpreted as the corresponding character in the string, or would cause an error). the tab character (u+0009), carriage re
turn (u+000d), line feed (u+000a), and space (u+0020) characters are the only valid whitespace characters. static methods json.parse(text[, reviver]) parse the string text as json, optionally transform the produced value and its properties, and re
turn the value. any violations of the json syntax, including those pertaining to the differences between javascript and json, cause a syntaxerror to be ...
...by default, all instances of undefined are replaced with null, and other unsupported native data types are censored. ...
get Map[@@species] - JavaScript
the map[@@species] accessor property re
turns the map constructor. description the species accessor property re
turns the default constructor for map objects. subclass constructors may over-ride it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the map constructor for map objects: map[symbol.species]; // function map() species in derived objects in a derived collection object (e.g. your custom map mymap), the mymap species is the mymap constructor. ...
...tructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the map constructor for map objects: map[symbol.species]; // function map() species in derived objects in a derived collection object (e.g. your custom map mymap), the mymap species is the mymap constructor. however, you might want to overwrite this, in order to re
turn parent map objects in your derived class methods: class mymap extends map { // overwrite mymap species to the parent map constructor static get [symbol.species]() { re
turn map; } } specifications specification ecmascript (ecma-262)the definition of 'get map [ @@species ]' in that specification. ...
Map.prototype.forEach() - JavaScript
tax mymap.foreach(callback([value][,key][,map])[, thisarg]) parameters callback function to execute for each entry of mymap. it takes the following arguments: value optional value of each iteration. key optional key of each iteration. map optional the map being iterated (mymap in the above syntax box). thisarg optional value to use as this when executing callback. re
turn value undefined. description the foreach method executes the provided callback once for each key of the map which actually exist. it is not invoked for keys which have been deleted. however, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the entry's value the entry's key the map object being traversed if a thisarg par...
...ing to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach has finished. callback is not invoked for values deleted before being visited. new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it does not re
turn a value. examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined...
Map.prototype.get() - JavaScript
the get() method re
turns a specified element from a map object. if the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the map object. 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 mymap.get(key) parameters key the key of the element to re
turn from the map object. re
turn value the element associated with the specified key, or undefined if the key can't be found in the map object. examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // ...
...ease clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.get(key) parameters key the key of the element to re
turn from the map object. re
turn value the element associated with the specified key, or undefined if the key can't be found in the map object. examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // re
turns "foo" mymap.get('baz'); // re
turns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification. ...
Map.prototype.has() - JavaScript
the has() method re
turns a boolean indicating whether an element with the specified key exists or not. 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 mymap.has(key) parameters key the key of the element to test for presence in the map object. re
turn value true if an element with the specified key exists in the map object; otherwise false. ...
...es project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.has(key) parameters key the key of the element to test for presence in the map object. re
turn value true if an element with the specified key exists in the map object; otherwise false. examples using has() let mymap = new map() mymap.set('bar', "foo") mymap.has('bar') // re
turns true mymap.has('baz') // re
turns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification. ...
Math.atanh() - JavaScript
the math.atanh() function re
turns the hyperbolic arctangent of a number, that is ∀x∊(-1,1),math.atanh(x)=arctanh(x)= the unique ysuch thattanh(y)=x\forall x \in \left( -1, 1 \right), \mathtt{\operatorname{math.atanh}(x)} = \operatorname{arctanh}(x) = \text{ the unique } \; y \; \text{such that} \; \tanh(y) = x 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 math.atanh(x) parameters x a number. re
turn value the hyperbolic arctangent of the given number. description because atanh() is a static method of math, you always use it as math.atanh(), rather than as a method of a math object you created...
...atanh() is a static method of math, you always use it as math.atanh(), rather than as a method of a math object you created (math is not a constructor). polyfill for |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: math.atanh = math.atanh || function(x) { re
turn math.log((1+x)/(1-x)) / 2; }; examples using math.atanh() math.atanh(-2); // nan math.atanh(-1); // -infinity math.atanh(0); // 0 math.atanh(0.5); // 0.5493061443340548 math.atanh(1); // infinity math.atanh(2); // nan for values greater than 1 or less than -1, nan is re
turned. specifications specification ecmascript (ecma-262)the definition of 'math.atanh' i...
Math.exp() - JavaScript
description because exp() is a static method of math, you always use it as math.exp(), rather than as a method of a math object you created (math is not a constructor). ...
...where x is the argument, and e is euler's number (also known as napier's constant), the base of the natural logarithms. 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 math.exp(x) parameters x a number. re
turn value a number representing ex, where e is euler's number and x is the argument. description because exp() is a static method of math, you always use it as math.exp(), rather than as a method of a math object you created (math is not a constructor). examples using math.exp() math.exp(-1); // 0.36787944117144233 math.exp(0); // 1 math.exp(1); // 2.718281828459045 specifications ...
Math.expm1() - JavaScript
the math.expm1() function re
turns ex - 1, where x is the argument, and e the base of the natural logarithms. 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 math.expm1(x) parameters x a number. re
turn value a number representing ex - 1, where e is euler's number and x is the argument. description because expm1() is a static method of math, you always use it as math.expm1(), rather than as a method of a math object you created (math is not a constructor). ...
... number. re
turn value a number representing ex - 1, where e is euler's number and x is the argument. description because expm1() is a static method of math, you always use it as math.expm1(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.expm1 = math.expm1 || function(x) { re
turn math.exp(x) - 1; }; examples using math.expm1() math.expm1(-1); // -0.6321205588285577 math.expm1(0); // 0 math.expm1(1); // 1.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.expm1' in that specification. ...
Math.log10() - JavaScript
the math.log10() function re
turns the base 10 logarithm of a number, that is ∀x>0,math.log10(x)=log10(x)=the uniqueysuch that10y=x\forall x > 0, \mathtt{\operatorname{math.log10}(x)} = \log_10(x) = \text{the unique} \; y \; \text{such that} \; 10^y = x 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 math.log10(x) parameters x a number. re
turn value the base 10 logarithm of the given number. if the number is negative, nan is re
turned. description if the value of x is less than 0, the re
turn value is always nan. because log10() is a static method of math, you always use it as math.log10(), rather...
...uivalent of math.log(x) / math.log(10). for log10(e) use the constant math.log10e which is 1 / math.ln10. examples using math.log10() math.log10(2); // 0.3010299956639812 math.log10(1); // 0 math.log10(0); // -infinity math.log10(-2); // nan math.log10(100000); // 5 polyfill this can be emulated with the following function: math.log10 = math.log10 || function(x) { re
turn math.log(x) * math.log10e; }; specifications specification ecmascript (ecma-262)the definition of 'math.log10' in that specification. ...
Math.min() - JavaScript
the result is infinity if no parameters are provided. ...
...onverted into one. 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 math.min([value1[, value2[, ...]]]) parameters value1, value2, ... zero or more numbers among which the lowest value will be selected and re
turned. re
turn value the smallest of the given numbers. if any one or more of the parameters cannot be converted into a number, nan is re
turned. the result is infinity if no parameters are provided. description because min() is a static method of math, you always use it as math.min(), rather than as a method of a math object you created (math is not a constructor). if no arguments are given, the...
Math.pow() - JavaScript
the math.pow() function re
turns the base to the exponent power, that is, baseexponent. 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 math.pow(base, exponent) parameters base the base number. exponent the exponent used to raise the base. re
turn value a number representing the given base taken to the power of the given exponent. description the math.pow() function re
turns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system. because pow() is a static method of math, you always use it as math.pow(), rather than as a method of a math object...
... ...
Math.round() - JavaScript
description if the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. if it is less than 0.5, the argument is rounded to the integer with the lower absolute value. ...
... description if the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. if it is less than 0.5, the argument is rounded to the integer with the lower absolute value. ...
Math.tanh() - JavaScript
the math.tanh() function re
turns the hyperbolic tangent of a number, that is tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1} syntax math.tanh(x) parameters x a number. re
turn value the hyperbolic tangent of the given number. description because tanh() is a static method of math, you always use it as math.tanh(), rather than as a method of a math object you created (math is not a constructor). ...
...r. re
turn value the hyperbolic tangent of the given number. description because tanh() is a static method of math, you always use it as math.tanh(), rather than as a method of a math object you created (math is not a constructor). polyfill this can be emulated with the help of the math.exp() function: math.tanh = math.tanh || function(x){ var a = math.exp(+x), b = math.exp(-x); re
turn a == infinity ? 1 : b == infinity ? -1 : (a - b) / (a + b); } examples using math.tanh() math.tanh(0); // 0 math.tanh(infinity); // 1 math.tanh(1); // 0.7615941559557649 specifications specification ecmascript (ecma-262)the definition of 'math.tanh' in that specification. ...
Number.NEGATIVE_INFINITY - JavaScript
negative_infinity is nan. negative_infinity, divided by any negative value except negative_infinity, is positive_infinity. negative_infinity, divided by any positive value except positive_infinity, is negative_infinity. negative_infinity, divided by either negative_infinity or positive_infinity, is nan. you might use the number.negative_infinity property to indicate an error condition that re
turns a finite number in case of success. note, however, that isfinite would be more appropriate in such a case. because negative_infinity is a static property of number, you always use it as number.negative_infinity, rather than as a property of a number object you created. examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller tha...
...ed. examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller than the minimum value. when the if statement executes, smallnumber has the value -infinity, so smallnumber is set to a more manageable value before continuing. var smallnumber = (-number.max_value) * 2; if (smallnumber === number.negative_infinity) { smallnumber = re
turnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.negative_infinity' in that specification. ...
Number.POSITIVE_INFINITY - JavaScript
positive_infinity is nan. positive_infinity, divided by any negative value except negative_infinity, is negative_infinity. positive_infinity, divided by any positive value except positive_infinity, is positive_infinity. positive_infinity, divided by either negative_infinity or positive_infinity, is nan. you might use the number.positive_infinity property to indicate an error condition that re
turns a finite number in case of success. note, however, that isfinite would be more appropriate in such a case. because positive_infinity is a static property of number, you always use it as number.positive_infinity, rather than as a property of a number object you created. examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than t...
...r object you created. examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than the maximum value. when the if statement executes, bignumber has the value infinity, so bignumber is set to a more manageable value before continuing. var bignumber = number.max_value * 2; if (bignumber == number.positive_infinity) { bignumber = re
turnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.positive_infinity' in that specification. ...
Number.isSafeInteger() - JavaScript
rillion with full precision requires using an arbitrary precision arithmetic library. see what every programmer needs to know about floating point arithmetic for more information on floating point representations of numbers. for larger integers, consider using the bigint type. syntax number.issafeinteger(testvalue) parameters testvalue the value to be tested for being a safe integer. ...
...floating point representations of numbers. for larger integers, consider using the bigint type. syntax number.issafeinteger(testvalue) parameters testvalue the value to be tested for being a safe integer. re
turn value a boolean indicating whether or not the given value is a number that is a safe integer. ...
Number.parseInt() - JavaScript
the number.parseint() method parses a string argument and re
turns an integer of the specified radix or base. 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 number.parseint(string,[ radix]) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. be careful—this does not default to 10! re
turn value an integer parsed from the given string. if...
...hitespace in this argument is ignored. radix optional an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. be careful—this does not default to 10! re
turn value an integer parsed from the given string. if the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, nan is re
turned. polyfill if (number.parseint === undefined) { number.parseint = window.parseint } examples number.parseint vs parseint this method has the same functionality as the global parseint() function: number.parseint === parseint // true and is part of ecmascript 2015 (its purpose is modularization of globals). please see parseint() for more detail and examples. specifications ...
Number.prototype.toPrecision() - JavaScript
see the discussion of rounding in the description of the number.prototype.tofixed() method, which also applies to toprecision(). if the precision argument is omitted, behaves as number.prototype.tostring(). if the precision argument is a non-integer value, it is rounded to the nearest integer. exceptions rangeerror if precision is not between 1 and 100 (inclusive), a rangeerror is thrown. ...
... ...
Number.prototype.valueOf() - JavaScript
description this method is usually called internally by javascript and not explicitly in web code. ...
... description this method is usually called internally by javascript and not explicitly in web code. ...
Object.fromEntries() - JavaScript
rs into an object. 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 object.fromentries(iterable); parameters iterable an iterable such as array or map or other objects implementing the iterable protocol. ...
...clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.fromentries(iterable); parameters iterable an iterable such as array or map or other objects implementing the iterable protocol. re
turn value a new object whose properties are given by the entries of the iterable. description the object.fromentries() method takes a list of key-value pairs and re
turns a new object whose properties are given by those entries. the iterable argument is expected to be an object that implements an @@iterator method, that re
turns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key. object.fromentries() perform...
Object.isExtensible() - JavaScript
s if an object is extensible (whether it can have new properties added to it). 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 object.isextensible(obj) parameters obj the object which should be checked. re
turn value a boolean indicating whether or not the given object is extensible. description objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. an object can be marked as non-extensible using object.preventextensions(), object.seal(), or object.freeze(). examples using object.isextensible ...
...t.isextensible(sealed); // === false // frozen objects are also by definition non-extensible. var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply re
turn false. object.isextensible(1); // typeerror: 1 is not an object (es5 code) object.isextensible(1); // false (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isextensible' in that specification. ...
Object.isSealed() - JavaScript
the object.issealed() method determines if an object is sealed. 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 object.issealed(obj) parameters obj the object which should be checked. re
turn value a boolean indicating whether or not the given object is sealed. description re
turns true if the object is sealed, otherwise false. an object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). examples using object.issealed // objects aren't sealed by default. var empty = {}; object.issealed(empty); // === fals...
....issealed(sealed); // === true // a sealed object is, by definition, non-extensible. object.isextensible(sealed); // === false // a sealed object might be frozen, // but it doesn't have to be. object.isfrozen(sealed); // === true // (all properties also non-writable) var s2 = object.seal({ p: 3 }); object.isfrozen(s2); // === false // ('p' is still writable) var s3 = object.seal({ get p() { re
turn 0; } }); object.isfrozen(s3); // === true // (only configurability matters for accessor properties) non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object, simply re
turn true. object.issealed(1); // typeerror: 1 is not an object (es5 code) ...
Promise.resolve() - JavaScript
the promise.resolve() method re
turns a promise object that is resolved with a given value. if the value is a promise, that promise is re
turned; if the value is a thenable (i.e. has a "then" method), the re
turned promise will "follow" that thenable, adopting its eventual state; otherwise the re
turned promise will be fulfilled with the value. this function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer. syntax promise.resolve(value); parameters value argument to be resolved by this promise. can also be a promise or a thenable to resolve. re
turn value a promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. description the static promi...
...resolves to a promise that resolves to something) into a single layer. syntax promise.resolve(value); parameters value argument to be resolved by this promise. can also be a promise or a thenable to resolve. re
turn value a promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. description the static promise.resolve function re
turns a promise that is resolved. examples using the static promise.resolve method promise.resolve('success').then(function(value) { console.log(value); // "success" }, function(value) { // not called }); resolving an array var p = promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); resolving another promise var original = promise.resolve(33); var cast = promise.r...
handler.apply() - JavaScript
tps://github.com/mdn/interactive-examples and send us a pull request. syntax const p = new proxy(target, { apply: function(target, thisarg, argumentslist) { } }); parameters the following parameters are passed to the apply() method. this is bound to the handler. target the target object. thisarg the this argument for the call. argumentslist the list of arguments for the call. re
turn value the apply() method can re
turn any value. description the handler.apply() method is a trap for a function call. interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself.
... invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); re
turn argumentslist[0] + argumentslist[1] + argumentslist[2]; } }); console.log(p(1, 2, 3)); // "called: 1, 2, 3" // 6 specifications specification ecmascript (ecma-262)the definition of '[[call]]' in that specification. ...
Proxy() constructor - JavaScript
a trap for object.getownpropertynames and object.getownpropertysymbols. handler.preventextensions() a trap for object.preventextensions. handler.set() a trap for setting property values. handler.setprototypeof() a trap for object.setprototypeof. examples selectively proxy property accessors in this example the target has two properties, notproxied and proxied. ...
...ctively proxy property accessors in this example the target has two properties, notproxied and proxied. we define a handler that re
turns a different value for proxied, and lets any other accesses through to the target. const target = { notproxied: "original value", proxied: "original value" }; const handler = { get: function(target, prop, receiver) { if (prop === "proxied") { re
turn "replaced value"; } re
turn reflect.get(...arguments); } }; const proxy = new proxy(target, handler); console.log(proxy.notproxied); // "original value" console.log(proxy.proxied); // "replaced value" specifications specification ecmascript (ecma-262)the definition of 'proxy constructor' in that specification. ...
Proxy.revocable() - JavaScript
the proxy.revocable() method is used to create a revocable proxy object. syntax proxy.revocable(target, handler); parameters target a target object to wrap with proxy. it can be any sort of object, including a native array, a function, or even another proxy. handler an object whose properties are functions define the behavior of proxy p when an operation is performed on it. re
turn value a newly created revocable proxy object is re
turned. description a revocable proxy is an object with following two properties {proxy: proxy, revoke: revoke}. proxy a proxy object created with new proxy(target, handler) call. revoke a function with no argument to invalidate (switch off) the proxy. if the revoke() function gets called, the proxy becomes unusable: any trap to a handler wil...
...tion with no argument to invalidate (switch off) the proxy. if the revoke() function gets called, the proxy becomes unusable: any trap to a handler will throw a typeerror. once a proxy is revoked, it will remain revoked and can be garbage collected. calling revoke() again has no effect. ...
Reflect.deleteProperty() - JavaScript
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 reflect.deleteproperty(target, propertykey) parameters target the target object on which to delete the property. propertykey the name of the property to be deleted. re
turn value a boolean indicating whether or not the property was successfully deleted. exceptions a typeerror, if target is not an object. description the reflect.deleteproperty method allows you to delete a property on an object. it re
turns a boolean indicating whether or not the property was successfully deleted. it is almost identical to the non-strict delete operator. examples using reflect.
...her or not the property was successfully deleted. it is almost identical to the non-strict delete operator. examples using reflect.deleteproperty() let obj = { x: 1, y: 2 } reflect.deleteproperty(obj, 'x') // true obj // { y: 2 } let arr = [1, 2, 3, 4, 5] reflect.deleteproperty(arr, '3') // true arr // [1, 2, 3, undefined, 5] // re
turns true if no such property exists reflect.deleteproperty({}, 'foo') // true // re
turns false if a property is unconfigurable reflect.deleteproperty(object.freeze({foo: 1}), 'foo') // false specifications specification ecmascript (ecma-262)the definition of 'reflect.deleteproperty' in that specification. ...
Reflect.getOwnPropertyDescriptor() - JavaScript
the static reflect.getownpropertydescriptor() method is similar to object.getownpropertydescriptor(). it re
turns a property descriptor of the given property if it exists on the object, undefined otherwise. 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 reflect.getownpropertydescriptor(target, propertykey) parameters target the target object in which to look for the property. propertykey the name of the property to get an own property descriptor for. re
turn value a property descriptor object if the property exists in target object; otherwise, undefined. exceptions a typeerror, if target is not a...
...the only difference to object.getownpropertydescriptor() is how non-object targets are handled. ...
RegExp.prototype[@@match]() - JavaScript
etrieves the matches when matching a string against a regular expression. 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 regexp[symbol.match](str) parameters str a string that is a target of the match. re
turn value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. description this method is called internally in string.prototype.match(). for example, the following two examples re
turn same result. 'abc'.match(/a/); /a/[symbol.match]('abc'); this method exists for customizing match behavior within regexp subclasses. example...
...ents order. let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str); console.log(result); // ["2016", "01", "02"] using @@match in subclasses subclasses of regexp can override the [@@match]() method to modify the default behavior. class myregexp extends regexp { [symbol.match](str) { let result = regexp.prototype[symbol.match].call(this, str); if (!result) re
turn null; re
turn { group(n) { re
turn result[n]; } }; } } let re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // string.prototype.match calls re[@@match]. console.log(result.group(1)); // 2016 console.log(result.group(2)); // 01 console.log(result.group(3)); // 02 specifications specification e...
RegExp.prototype[@@search]() - JavaScript
es a search for a match between a this regular expression and a string. 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 regexp[symbol.search](str) parameters str a string that is a target of the search. re
turn value integer if successful, [@@search]() re
turns the index of the first match of the regular expression inside the string. otherwise, it re
turns -1. description this method is called internally in string.prototype.search(). for example, the following two examples re
turn the same result. 'abc'.search(/a/); /a/[symbol.search]('abc'); this method exists for customizing the search behavior...
...xcept the different this and the different arguments order. var re = /-/g; var str = '2016-01-02'; var result = re[symbol.search](str); console.log(result); // 4 using @@search in subclasses subclass of regexp can override [@@search]() method to modify the behavior. class myregexp extends regexp { constructor(str) { super(str) this.pattern = str; } [symbol.search](str) { re
turn str.indexof(this.pattern); } } var re = new myregexp('a+b'); var str = 'ab a+b'; var result = str.search(re); // string.prototype.search calls re[@@search]. console.log(result); // 3 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@search]' in that specification. ...
get RegExp[@@species] - JavaScript
the regexp[@@species] accessor property re
turns the regexp constructor. 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 species accessor property re
turns the default constructor for regexp objects. subclass constructors may over-ride it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the regexp constructor for regexp objects: regexp[symbol.species]; // function regexp() species in derived objects in a derived collection object (e.g. your custom regexp myregexp), the myregexp species is the myrege...
...mples species in ordinary objects the species property re
turns the default constructor function, which is the regexp constructor for regexp objects: regexp[symbol.species]; // function regexp() species in derived objects in a derived collection object (e.g. your custom regexp myregexp), the myregexp species is the myregexp constructor. however, you might want to overwrite this, in order to re
turn parent regexp objects in your derived class methods: class myregexp extends regexp { // overwrite myregexp species to the parent regexp constructor static get [symbol.species]() { re
turn regexp; } } specifications specification ecmascript (ecma-262)the definition of 'get regexp [ @@species ]' in that specification. ...
RegExp.prototype[@@split]() - JavaScript
ll request. syntax regexp[symbol.split](str[, limit]) parameters str the target of the split operation. limit optional integer specifying a limit on the number of splits to be found. the [@@split]() method still splits on every match of this regexp pattern (or, in the syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern. re
turn value an array containing substrings as its elements. description this method is called internally in string.prototype.split() if its separator argument is an object that has a @@split method, such as a regexp. for example, the following two examples re
turn the same result. 'a-b-c'.split(/-/); /-/[symbol.split]('a-b-c'); this method exists for customizing the behavior of split() in regexp s...
...r of arguments. let re = /-/g; let str = '2016-01-02'; let result = re[symbol.split](str); console.log(result); // ["2016", "01", "02"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior. class myregexp extends regexp { [symbol.split](str, limit) { let result = regexp.prototype[symbol.split].call(this, str, limit); re
turn result.map(x => "(" + x + ")"); } } let re = new myregexp('-'); let str = '2016-01-02'; let result = str.split(re); // string.prototype.split calls re[@@split]. console.log(result); // ["(2016)", "(01)", "(02)"] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@split]' in that specification. ...
RegExp.prototype.exec() - JavaScript
javascript regexp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). they store a lastindex from the previous match. using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with string.prototype.match(). a newer function has been proposed to simplify matching multiple parts of a string (with capture groups): string.prototype.matchall(). if you are executing a match simply to find true or false, use regexp.prototype.test() method or string.prototype.search() instead. ...
....prototype.test() method or string.prototype.search() instead. 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 regexobj.exec(str) parameters str the string against which to match the regular expression. re
turn value if the match succeeds, the exec() method re
turns an array (with extra properties index and input; see below) and updates the lastindex property of the regular expression object. the re
turned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. if the match fails, the exec() method re
turns null, and sets lastindex to 0. ...
RegExp.prototype.flags - JavaScript
the flags property re
turns a string consisting of the flags of the current regular expression object. 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. property attributes of regexp.prototype.flags writable no enumerable no configurable yes description flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). ...
...e.flags writable no enumerable no configurable yes description flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). polyfill if (regexp.prototype.flags === undefined) { object.defineproperty(regexp.prototype, 'flags', { configurable: true, get: function() { re
turn this.tostring().match(/[gimsuy]*$/)[0]; } }); } examples using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.flags' in that specification. ...
RegExp.prototype.source - JavaScript
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. property attributes of regexp.prototype.source writable no enumerable no configurable yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig". ...
... property attributes of regexp.prototype.source writable no enumerable no configurable yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig". empty regular expressions and escaping starting with ecmascript 5, the source property no longer re
turns an empty string for empty regular expressions. instead, the string "(?:)" is re
turned. in addition, line terminators (such as "\n") are escaped now. new regexp().source; // "(?:)" new regexp('\n').source === '\n'; // true, prior to es5 new regexp('\n').source === '\\n'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.
RegExp.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the regular expression. 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 regexobj.tostring(); re
turn value a string representing the given object. description the regexp object overrides the tostring() method of the object object; it does not inherit object.prototype.tostring(). for regexp objects, the tostring() method re
turns a string representation of the regular expression. examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/...
...ntation of the regular expression. examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' var foo = new regexp('bar', 'g'); console.log(foo.tostring()); // logs '/bar/g' empty regular expressions and escaping starting with ecmascript 5, an empty regular expression re
turns the string "/(?:)/" and line terminators such as "\n" are escaped: new regexp().tostring(); // "/(?:)/" new regexp('\n').tostring() === '/\n/'; // true, prior to es5 new regexp('\n').tostring() === '/\\n/'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.tostring' in that specification. ...
get Set[@@species] - JavaScript
the set[symbol.species] accessor property re
turns the set constructor. description the species accessor property re
turns the default constructor for set objects. subclass constructors may override it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the set constructor for set objects: set[symbol.species]; // function set() species in derived objects in a derived collection object (e.g. your custom set myset), the myset species is the myset constructor. ...
...tructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is the set constructor for set objects: set[symbol.species]; // function set() species in derived objects in a derived collection object (e.g. your custom set myset), the myset species is the myset constructor. however, you might want to overwrite this, in order to re
turn parent set objects in your derived class methods: class myset extends set { // overwrite myset species to the parent set constructor static get [symbol.species]() { re
turn set; } } specifications specification ecmascript (ecma-262)the definition of 'get set [ @@species ]' in that specification. ...
Set.prototype.forEach() - JavaScript
syntax myset.foreach(callback[, thisarg]) parameters callback function to execute for each element, taking three arguments: currentvalue, currentkey the current element being processed in the set. as there are no keys in set, the value is passed for both arguments. set the set object which foreach() was called upon. thisarg value to use as this when executing callback. re
turn value undefined. description the foreach() method executes the provided callback once for each value which actually exists in the set object. it is not invoked for values which have been deleted. however, it is executed for values which are present but have the value undefined. callback is invoked with three arguments: the element value the element key the set object being traversed th...
... the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach() has finished. callback is not invoked for values deleted before being visited. new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object; it does not re
turn a value. examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specificatio...
SharedArrayBuffer.prototype.slice() - JavaScript
if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. this method has the same algorithm as array.prototype.slice(). 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 sab.slice() sab.slice(begin) sab.slice(begin, end) parameters begin optional zero-based index at which to begin extraction. ...
...to but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). a negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. if end is omitted, slice extracts through the end of the sequence (sab.bytelength). re
turn value a new sharedarraybuffer containing the extracted elements. examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ...
String.prototype.endsWith() - JavaScript
the endswith() method determines whether a string ends with the characters of a specified string, re
turning true or false as appropriate. 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 str.endswith(searchstring[, length]) parameters searchstring the characters to be searched for at the end of str. length optional if provided, it is used as the length of str. defaults to str.length. re
turn value true if the given characters are found at the end of the string; otherwise, false. description this method lets you determine whether or not a string ends with another string. this method is case-sensitiv...
...yfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet. ...
String.prototype.link() - JavaScript
the link() method creates a string representing the code for an <a> html element to be used as a hypertext link to another url. syntax str.link(url) parameters url any string that specifies the href attribute of the <a> tag; it should be a valid url (relative or absolute), with any & characters escaped as &, and any " characters escaped as ". re
turn value a string containing an <a> html element. description use the link() method to create an html snippet for a hypertext link. the re
turned string can then be added to the document via document.write() or element.innerhtml. links created with the link() method become elements in the links array of the document object. see document.links. examples using link() the following example displays the word "mdn" as a hypertext...
...nt. description use the link() method to create an html snippet for a hypertext link. the re
turned string can then be added to the document via document.write() or element.innerhtml. links created with the link() method become elements in the links array of the document object. see document.links. examples using link() the following example displays the word "mdn" as a hypertext link that re
turns the user to the mozilla developer network. var hottext = 'mdn'; var url = 'https://developer.mozilla.org/'; console.log('click to re
turn to ' + hottext.link(url)); // click to re
turn to <a href="https://developer.mozilla.org/">mdn</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.link' in that specification. ...
String.prototype.normalize() - JavaScript
the normalize() method re
turns the unicode normalization form of the string. 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 str.normalize([form]) parameters form optional one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. ...
... one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. re
turn value a string containing the unicode normalization form of the given string. errors thrown rangeerror a rangeerror is thrown if form isn't one of the values specified above. description unicode assigns a unique numerical value, called a code point, to each character. for example, the code point for "a" is given as u+0041. however, sometimes more than one code point, or sequence of code ...
String.prototype.padEnd() - JavaScript
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 str.padend(targetlength [, padstring]) parameters targetlength the length of the resulting string once the current str has been padded. ...
...een padded. if the value is lower than str.length, the current string will be re
turned as-is. padstring optional the string to pad the current str with. if padstring is too long to stay within targetlength, it will be truncated: for left-to-right languages the left-most part and for right-to-left languages the right-most will be applied. the default value for this parameter is " " (u+0020). re
turn value a string of the specified targetlength with the padstring applied at the end of the current str. examples using padend 'abc'.padend(10); // "abc " 'abc'.padend(10, "foo"); // "abcfoofoof" 'abc'.padend(6, "123456"); // "abc123" 'abc'.padend(1); // "abc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype...
String.prototype.padStart() - JavaScript
ive 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 str.padstart(targetlength [, padstring]) parameters targetlength the length of the resulting string once the current str has been padded. if the value is less than str.length, then str is re
turned as-is. padstring optional the string to pad the current str with. if padstring is too long to stay within the targetlength, it will be truncated from the end. the default value is " " (u+0020 'space'). re
turn value a string of the specified targetlength with padstring applied from the start. examples basic examples 'abc'.padstart(10); // " abc" 'abc'.padstart(10, "foo"); ...
...om the start. examples basic examples 'abc'.padstart(10); // " abc" 'abc'.padstart(10, "foo"); // "foofoofabc" 'abc'.padstart(6,"123465"); // "123abc" 'abc'.padstart(8, "0"); // "00000abc" 'abc'.padstart(1); // "abc" fixed width string number conversion // javascript version of: (unsigned) // printf "%0*d" width num function leftfillnum(num, targetlength) { re
turn num.tostring().padstart(targetlength, 0); } const num = 123; console.log(leftfillnum(num, 5)); // expected output: "00123" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padstart' in that specification. ...
String.prototype.startsWith() - JavaScript
the startswith() method determines whether a string begins with the characters of a specified string, re
turning true or false as appropriate. 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 str.startswith(searchstring[, position]) parameters searchstring the characters to be searched for at the start of this string. position optional the position in this string at which to begin searching for searchstring. defaults to 0. re
turn value true if the given characters are found at the beginning of the string; otherwise, false. description this method lets you determine whether or not a string begins wi...
...s been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.startswith() with the following snippet: if (!string.prototype.startswith) { object.defineproperty(string.prototype, 'startswith', { value: function(search, rawpos) { var pos = rawpos > 0 ? rawpos|0 : 0; re
turn this.substring(pos, pos + search.length) === search; } }); } a more robust (fully es2015 specification compliant), but less performant and compact, polyfill is available on github by mathias bynens. examples using startswith() //startswith let str = 'to be, or not to be, that is the question.' console.log(str.startswith('to be')) // true console.log(str.startswith('not...
String.prototype.toLocaleLowerCase() - JavaScript
the tolocalelowercase() method re
turns the calling string value converted to lower case, according to any locale-specific case mappings. 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 str.tolocalelowercase() str.tolocalelowercase(locale) str.tolocalelowercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to lower case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. ...
....tolocalelowercase() str.tolocalelowercase(locale) str.tolocalelowercase([locale, locale, ...]) parameters locale optional the locale parameter indicates the locale to be used to convert to lower case according to any locale-specific case mappings. if multiple locales are given in an array, the best available locale is used. the default locale is the host environment’s current locale. re
turn value a new string representing the calling string converted to lower case, according to any locale-specific case mappings. exceptions a rangeerror ("invalid language tag: xx_yy") is thrown if a locale argument isn't a valid language tag. a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string. description the tolocalelowercase() method retu...
String.prototype.toUpperCase() - JavaScript
the touppercase() method re
turns the calling string value converted to uppercase (the value will be converted to a string if it isn't one). 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 str.touppercase() re
turn value a new string representing the calling string converted to upper case. exceptions typeerror when called on null or undefined, for example, string.prototype.touppercase.call(undefined). description the touppercase() method re
turns the value of the string converted to uppercase. this method does not affect the value of the string itself since javascript strings are immutable. examples ...
...the value of the string itself since javascript strings are immutable. examples basic usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non-string this values to strings this method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = string.prototype.touppercase.call({ tostring: function tostring() { re
turn 'abcdef'; } }); const b = string.prototype.touppercase.call(true); // prints out 'abcdef true'. console.log(a, b); specifications specification ecmascript (ecma-262)the definition of 'string.prototype.touppercase' in that specification. ...
String.prototype.trim() - JavaScript
whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (lf, cr, etc.). 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 str.trim() re
turn value a new string representing the str stripped of whitespace from both ends. description the trim() method re
turns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function ...
...ew string representing the str stripped of whitespace from both ends. description the trim() method re
turns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { re
turn this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whitespace from just one side. var orig = 'foo '; console.log(orig.trim()); // 'foo' specifications specification ecmascri...
String.prototype.valueOf() - JavaScript
this value is equivalent to string.prototype.tostring(). this method is usually called internally by javascript and not explicitly in code. ...
...this value is equivalent to string.prototype.tostring(). this method is usually called internally by javascript and not explicitly in code. ...
Symbol.for() - JavaScript
the symbol.for(key) method searches for existing symbols in a runtime-wide symbol registry with the given key and re
turns it if found. otherwise a new symbol gets created in the global symbol registry with this key. 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 symbol.for(key); parameters key string, required. the key for the symbol (and also used for the description of the symbol). re
turn value an existing symbol with the given key if found; otherwise, a new symbol is created and re
turned. description in contrast to symbol(), the symbol.for() function creates a symbol available in a global symbo...
...if no symbol with the given key is found, symbol.for() will create a new global symbol. ...
Symbol.iterator - JavaScript
y for...of. 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 whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the re
turned iterator is used to obtain the values to be iterated. some built-in types have a default iteration behavior, while other types (such as object) do not. the built-in types with a @@iterator method are: array.prototype[@@iterator]() typedarray.prototype[@@iterator]() string.prototype[@@iterator]() map.prototype[@@iterator]() set.prototype[@@iterator]() see also iteration protocols for m...
...using it as such is likely to result in runtime exceptions or buggy behavior: var nonwellformediterable = {} nonwellformediterable[symbol.iterator] = () => 1 [...nonwellformediterable] // typeerror: [] is not a function specifications specification ecmascript (ecma-262)the definition of 'symbol.iterator' in that ...
Symbol.search - JavaScript
this function is called by the string.prototype.search() method. for more information, see regexp.prototype[@@search]() and string.prototype.search(). 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. ...
...thub.com/mdn/interactive-examples and send us a pull request. property attributes of symbol.search writable no enumerable no configurable no examples custom string search class caseinsensitivesearch { constructor(value) { this.value = value.tolowercase(); } [symbol.search](string) { re
turn string.tolowercase().indexof(this.value); } } console.log('foobar'.search(new caseinsensitivesearch('bar'))); // expected output: 3 specifications specification ecmascript (ecma-262)the definition of 'symbol.search' in that specification. ...
get TypedArray[@@species] - JavaScript
the typedarray[@@species] accessor property re
turns the constructor of a typed array. description the species accessor property re
turns the default constructor for typed array objects. subclass constructors may over-ride it to change the constructor assignment. examples species in ordinary objects the species property re
turns the default constructor function, which is one of the typed array constructors for a given typed array object: int8array[symbol.species]; // function int8array() uint8array[symbol.species]; // function uint8array() float32array[symbol.species]; // function float32array() species in derived objects in a derived collection object (e.g. your custom typed array mytypedarray), the mytypedarray species is the mytypedarray constructor. however, you might want to o...
...ray object: int8array[symbol.species]; // function int8array() uint8array[symbol.species]; // function uint8array() float32array[symbol.species]; // function float32array() species in derived objects in a derived collection object (e.g. your custom typed array mytypedarray), the mytypedarray species is the mytypedarray constructor. however, you might want to overwrite this, in order to re
turn a parent typed array object in your derived class methods: class mytypedarray extends uint8array { // overwrite mytypedarray species to the parent uint8array constructor static get [symbol.species]() { re
turn uint8array; } } specifications specification ecmascript (ecma-262)the definition of 'get %typedarray% [ @@species ]' in that specification. ...
TypedArray.prototype.filter() - JavaScript
e 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 typedarray.filter(callback[, thisarg]) parameters callback function to test each element of the typed array. invoked with arguments (element, index, typedarray). re
turn true to keep the element, false otherwise. thisarg optional value to use as this when executing callback. re
turn value a new typed array with the elements that pass the test. description the filter() method calls a provided callback function once for each element in a typed array, and constructs a new typed array of all the values for which callback re
turns a true value. callback is invoke...
...lements of the typed array are changed, or deleted, their value as passed to callback will be the value at the time filter() visits them; elements that are deleted are not visited. examples filtering out all small values the following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed. function isbigenough(element, index, array) { re
turn element >= 10; } new uint8array([12, 5, 8, 130, 44]).filter(isbigenough); // uint8array [ 12, 130, 44 ] filtering typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. new uint8array([12, 5, 8, 130, 44]).filter(elem => elem >= 10); // uint8array [ 12, 130, 44 ] specifications specification ecmascript (ecma-262)the definition...
TypedArray.prototype.forEach() - JavaScript
ch(callback[, thisarg]) parameters callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the array. array the array foreach() was called upon. thisarg optional. value to use as this when executing callback. re
turn value undefined. description the foreach() method executes the provided callback once for each element present in the typed array in ascending order. it is not invoked for indexes that have been deleted or elided. however, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index the typed arra...
...ay after the call to foreach() begins will not be visited by callback. if the values of existing elements of the typed array are changed, the value passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. foreach() executes the callback function once for each typed array element; unlike every() and some() it, always re
turns the value undefined. examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ...
TypedArray.prototype.indexOf() - JavaScript
the indexof() method re
turns the first index at which a given element can be found in the typed array, or -1 if it is not present. this method has the same algorithm as array.prototype.indexof(). typedarray is one of the typed array types here. 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 typedarray.indexof(searchelement[, fromindex = 0]) parameters searchelement element to locate in the typed array. fromindex the index to start the search at. if the index is greater than or equal to the typed array's length, -1 is re
turned, which means the typed array will not be searched. if the provided index va...
... description indexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator). ...
TypedArray.prototype.lastIndexOf() - JavaScript
the typed array is searched backwards, starting at fromindex. this method has the same algorithm as array.prototype.lastindexof(). typedarray is one of the typed array types here. 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 typedarray.lastindexof(searchelement[, fromindex = typedarray.length]) parameters searchelement element to locate in the typed array. fromindex optional. the index at which to start searching backwards. ...
...the typed array's length, i.e. the whole typed array will be searched. if the index is greater than or equal to the length of the typed array, the whole typed array will be searched. if negative, it is taken as the offset from the end of the typed array. note that even when the index is negative, the typed array is still searched from back to front. if the calculated index is less than 0, -1 is re
turned, i.e. the typed array will not be searched. re
turn value the last index of the element in the array; -1 if not found. description lastindexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator). examples using lastindexof var uint8 = new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.la...
TypedArray.prototype.map() - JavaScript
rs mapfn a callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array. index optional the index of the current element being processed in the typed array. array optional the typed array map() was called upon. thisarg optional value to use as this when executing mapfn. re
turn value a new typed array. description the map() method calls a provided callback function (mapfn) once for each element in a typed array, in order, and constructs a new typed array from the results. mapfn is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted, or which have never been assigned v...
... [1, 4, 9] mapping a typed array of numbers using a function containing an argument the following code shows how map works when a function requiring one argument is used with it. the argument will automatically be assigned to each element of the typed array as map loops through the original typed array. const numbers = new uint8array([1, 4, 9]); const doubles = numbers.map(function(num) { re
turn num * 2; }); // doubles is now uint8array [2, 8, 18] // numbers is still uint8array [1, 4, 9] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.map' in that specification. ...
TypedArray.prototype.some() - JavaScript
x typedarray.some(callback[, thisarg]) parameters callback function to test for each element, taking three arguments: currentvalue the current element being processed in the typed array. index the index of the current element being processed in the typed array. array the typed array some was called upon. thisarg optional. value to use as this when executing callback. re
turn value true if the callback function re
turns a truthy value for any array element; otherwise, false. description the some method executes the callback function once for each element present in the typed array until it finds one where callback re
turns a true value. if such an element is found, some immediately re
turns true. otherwise, some re
turns false. callback is invoked with three arguments...
... }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable. examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10. function isbiggerthan10(element, index, array) { re
turn element > 10; } new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test. new uint8array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false new uint8array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true specific...
TypedArray.prototype.subarray() - JavaScript
the begin offset is inclusive and the end offset is exclusive. typedarray is one of the typed array types. 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 typedarray.subarray([begin [,end]]) parameters begin optional element to begin at. the offset is inclusive. the whole array will be included in the new view if this value is not specified. end optional element to end at. the offset is exclusive. ...
...a pull request. syntax typedarray.subarray([begin [,end]]) parameters begin optional element to begin at. the offset is inclusive. the whole array will be included in the new view if this value is not specified. end optional element to end at. the offset is exclusive. if not specified, all elements from the one specified by begin to the end of the array are included in the new view. re
turn value a new typedarray object. description the range specified by begin and end is clamped to the valid index range for the current array; if the computed length of the new array would be negative, it's clamped to zero. if either begin or end is negative, it refers to an index from the end of the array instead of from the beginning. also note that this is creating a new view on the existing b...
TypedArray.prototype.toLocaleString() - JavaScript
the tolocalestring() method re
turns a string representing the elements of the typed array. the elements are converted to strings and are separated by a locale-specific string (such as a comma “,”). this method has the same algorithm as array.prototype.tolocalestring() and, as the typed array elements are numbers, the same algorithm as number.prototype.tolocalestring() applies for each element. typedarray is one of the typed array types here. syntax typedarray.tolocalestring([locales [, options]]); parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. ...
...ent. typedarray is one of the typed array types here. syntax typedarray.tolocalestring([locales [, options]]); parameters the locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string re
turned are entirely implementation dependent. see the intl.numberformat() constructor for details on these parameters and how to use them. re
turn value a string representing the elements of the typed array. examples using tolocalestring var uint = new uint32array([2000, 500, 8123, 12, 4212]); uint.tolocalestring(); // if run in a de-de locale // "2.000,500,8.123,12,4.212" uint.tolocalestring(...
WeakMap.prototype.has() - JavaScript
the has() method re
turns a boolean indicating whether an element with the specified key exists in the weakmap object or not. 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 wm.has(key); parameters key required. the key of the element to test for presence in the weakmap object. re
turn value boolean re
turns true if an element with the specified key exists in the weakmap object; otherwise false. ...
.../mdn/interactive-examples and send us a pull request. syntax wm.has(key); parameters key required. the key of the element to test for presence in the weakmap object. re
turn value boolean re
turns true if an element with the specified key exists in the weakmap object; otherwise false. examples using the has method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // re
turns true wm.has('baz'); // re
turns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification. ...
WeakSet.prototype.has() - JavaScript
the has() method re
turns a boolean indicating whether an object exists in a weakset or not. 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 ws.has(value); parameters value required. the object to test for presence in the weakset. re
turn value boolean re
turns true if an element with the specified value exists in the weakset object; otherwise false. ...
...om/mdn/interactive-examples and send us a pull request. syntax ws.has(value); parameters value required. the object to test for presence in the weakset. re
turn value boolean re
turns true if an element with the specified value exists in the weakset object; otherwise false. examples using the has method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // re
turns true myset.has(obj); // re
turns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification. ...
WeakSet - JavaScript
nctions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed. ...
...l, so a weakset is more suitable (and performant) than a set for tracking object references, especially if a very large number of objects is involved. constructor weakset() creates a new weakset object. instance methods weakset.prototype.add(value) appends value to the weakset object. weakset.prototype.delete(value) removes value from the weakset. weakset.prototype.has(value) will re
turn false afterwards. weakset.prototype.has(value) re
turns a boolean asserting whether value is present in the weakset object or not. examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.
WebAssembly.CompileError - JavaScript
erited from error. webassembly.compileerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.compileerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.compileerror.prototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() re
turns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() re
turns a string representing the specified error object.. inherited from error. examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefil...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to co...
WebAssembly.LinkError - JavaScript
s error. inherited from error. webassembly.linkerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.linkerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.linkerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() re
turns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() re
turns a string representing the specified error object.. inherited from error. examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } c...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the...
WebAssembly.Memory() constructor - JavaScript
maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new memory instance there are two ways to get a webassembly.memory object. the first way is to construct it from javascript. the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will re
turn an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created ...
...i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new webassembly.memory({initial:10, maximum:100, shared:true}); this memory's buffer property will re
turn a sharedarraybuffer. specifications specification webassembly javascript interfacethe definition of 'memory' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmob...
WebAssembly.Memory.prototype.grow() - JavaScript
the grow() protoype method of the memory object increases the size of the memory instance by a specified number of webassembly pages. syntax memory.grow(number); parameters number the number of webassembly pages you want to grow the memory by (each one is 64kib in size). re
turn value the previous size of the memory, in units of webassembly pages. examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib). var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" con...
...ge (64kib), and a maximum size of 10 pages (640kib). var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" console.log(memory.buffer.bytelength / bytesperpage); // "2" note the re
turn value of grow() here is the previous number of webassembly pages. specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat...
WebAssembly.Module.exports() - JavaScript
exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). ...
...eaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exported function from inside it, then show how we can re
turn information on the available exports on a module using webassembly.module.exports. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); ...
WebAssembly.RuntimeError - JavaScript
erited from error. webassembly.runtimeerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.runtimeerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.runtimeerror.prototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() re
turns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() re
turns a string representing the specified error object.. inherited from error. examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefil...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to co...
WebAssembly.Table.prototype.set() - JavaScript
the set() prototype method of the webassembly.table object mutates a reference stored at a given index to a different value. syntax table.set(index, value); parameters index the index of the function reference you want to mutate. value the value you want to mutate the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. re
turn value void. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table ...
...is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently re
turn null). var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, an...
WebAssembly.Table - JavaScript
ebassembly table, which stores function references. a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. note: tables can currently only store function references, but this will likely be expanded in the future. constructor webassembly.table() creates a new table object. instance properties table.prototype.length re
turns the length of the table, i.e. the number of elements. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a new webassembly table instanc...
...ent:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method. the table2.wasm module contains two functions (one that re
turns 42 and another that re
turns 83) and stores both into elements 0 and 1 of the imported table (see text representation). so after instantiation, the table still has length 2, but the elements now contain callable exported webassembly functions which we can call from js. webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console...
WebAssembly.instantiateStreaming() - JavaScript
ulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. 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 the compiled module or else a webassembly.linkerror is thrown. re
turn value a promise that resolves to a resultobject which contains two fields: module: a webassembly.module object representing the compiled webassembly module. this module can be instantiated again or shared via postmessage(). instance: a webassembly.instance object that contains all the exported webassembly functions. exceptions if either of the parameters are not of the correct type or s...
...ss the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked. note: for this to work, .wasm files should be re
turned with an application/wasm mime type by the server. specifications specification webassembly features for web embeddingthe definition of 'instantiatestreaming()' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/brows...
WebAssembly.validate() - JavaScript
exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. ...
... exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. ...
WebAssembly - JavaScript
and can be efficiently shared with workers, and instantiated multiple times. webassembly.runtimeerror() error type that is thrown whenever webassembly specifies a trap. webassembly.table() an array-like structure representing a webassembly table, which stores function references. static methods webassembly.instantiate() the primary api for compiling and instantiating webassembly code, re
turning both a module and its first instance. webassembly.instantiatestreaming() compiles and instantiates a webassembly module directly from a streamed underlying source, re
turning both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary code, leaving instantiation as a separate step. webassembly.compilestreaming() compiles a webassembly.
...g both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary code, leaving instantiation as a separate step. webassembly.compilestreaming() compiles a webassembly.module directly from a streamed underlying source, leaving instantiation as a separate step. webassembly.validate() validates a given typed array of webassembly binary code, re
turning whether the bytes are valid webassembly code (true) or not (false). examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. because the instantiatestre...
decodeURIComponent() - JavaScript
by encodeuricomponent or by a similar routine. 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 decodeuricomponent(encodeduri) parameters encodeduri an encoded component of a uniform resource identifier. re
turn value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component. exceptions throws an urierror ("malformed uri sequence") exception when used wrongly. description replaces each escape sequence in the encoded uri component with the character that it represents. examples decoding a cyrillic url component decodeuricomponent('javascript_%d1...
... ...
encodeURI() - JavaScript
of the character (will only be four escape sequences for characters composed of two "surrogate" characters). 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 encodeuri(uri) parameters uri a complete uri. re
turn value a new string representing the provided string encoded as a uri. description the encodeuri() function does not encode characters that have special meaning (reserved characters) for a uri. the following example shows all the parts that a uri "scheme" can possibly contain. note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/f...
... ...
isFinite() - JavaScript
a finite number. if needed, the parameter is first converted to a number. 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 isfinite(testvalue) parameters testvalue the value to be tested for finiteness. re
turn value false if the argument is positive or negative infinity or nan or undefined; otherwise, true. description isfinite is a top-level function and is not associated with any object. you can use this function to determine whether a number is a finite number. the isfinite function examines the number in its argument. if the argument is nan, positive infinity, or negative infinity, this method ...
...alue false if the argument is positive or negative infinity or nan or undefined; otherwise, true. description isfinite is a top-level function and is not associated with any object. you can use this function to determine whether a number is a finite number. the isfinite function examines the number in its argument. if the argument is nan, positive infinity, or negative infinity, this method re
turns false; otherwise, it re
turns true. examples using isfinite isfinite(infinity); // false isfinite(nan); // false isfinite(-infinity); // false isfinite(0); // true isfinite(2e64); // true isfinite(910); // true isfinite(null); // true, would've been false with the // more robust number.isfinite(null) isfinite('0'); // true, would've ...
Equality (==) - JavaScript
the equality operator (==) checks whether its two operands are equal, re
turning a boolean result. unlike the strict equality operator, it attempts to convert and compare operands that are of different types. 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 x == y description the equality operators (== and !=) use the abstract equality comparison algorithm to compare two operands. this can be roughly summarised as follows: if the operands are both objects, re
turn true only if both operands reference the same object. if one operand is null and the other is undefined, re
turn true. if the operands are of ...
... the string to a numeric value. if one of the operands is boolean, convert the boolean operand to 1 if it is true and +0 if it is false. if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueof() and tostring() methods. if the operands have the same type, they are compared as follows: string: re
turn true only if both operands have the same characters in the same order. number: re
turn true only if both operands have the same value. +0 and -0 are treated as the same value. if either operand is nan, re
turn false. boolean: re
turn true only if operands are both true or both false. the most notable difference between this operator and the strict equality (===) operator is that the str...
Less than (<) - JavaScript
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 x < y description the operands are compared using the abstract relational comparison algorithm, which is roughly summarised below: first, objects are converted to primitives using symbol.toprimitive. if both values are strings, they are compared as strings, based on the values of the unicode code points they contain. ...
...ts they contain. otherwise javascript attempts to convert non-numeric types to numeric values: boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted to nan. strings are converted based on the values they contain, and are converted as nan if they do not contain numeric values. if either value is nan, the operator re
turns false. otherwise the values are compared as numeric values. examples string to string comparison console.log("a" < "b"); // true console.log("a" < "a"); // false console.log("a" < "3"); // false string to number comparison console.log("5" < 3); // false console.log("3" < 3); // false console.log("3" < 5); // true console.log("hello" < 5); ...
Object initializer - JavaScript
ascript 5 strict mode code, duplicate property names were considered a syntaxerror. with the introduction of computed property names making duplication possible at runtime, ecmascript 2015 has removed this restriction. function havees2015duplicatepropertysemantics() { 'use strict'; try { ({prop: 1, prop: 2}); // no error thrown, duplicate property names allowed in strict mode re
turn true; } catch(e) { // error thrown, duplicates prohibited in strict mode re
turn false; } } method definitions a property of an object can also refer to a function or a getter or setter method. let o = { property: function (parameters) {}, get property() {}, set property(value) {} } in ecmascript 2015, a shorthand notation is available, so that the keyword "function" is no lo...
... property definitions that do not use "colon" notation are not prototype mutations. they are property definitions that behave identically to similar definitions using any other name. let __proto__ = 'variable' let obj1 = {__proto__} assert(object.getprototypeof(obj1) === object.prototype) assert(obj1.hasownproperty('__proto__')) assert(obj1.__proto__ === 'variable') let obj2 = {__proto__() { re
turn 'hello'; }} assert(obj2.__proto__() === 'hello') let obj3 = {['__prot' + 'o__']: 17} assert(obj3.__proto__ === 17) specifications specification ecmascript (ecma-262)the definition of 'object initializer' in that specification. ...
Spread syntax (...) - JavaScript
oes a [[call]] and not a [[construct]]). ...
... = new date(...datefields); to use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application: function applyandnew(constructor, args) { function partial () { re
turn constructor.apply(this, args); }; if (typeof constructor.prototype === "object") { partial.prototype = object.create(constructor.prototype); } re
turn partial; } function myconstructor () { console.log("arguments.length: " + arguments.length); console.log(arguments); this.prop1="val1"; this.prop2="val2"; }; const myarguments = ["hi", "how", "are", "you", "mr", null]; const myconstructorwitharguments = applyandnew(myconstructor, myarguments); console.log(new myconstructorwitharguments); // (internal log of myconstructor): ...
Strict equality (===) - JavaScript
the strict equality operator (===) checks whether its two operands are equal, re
turning a boolean result. unlike the equality operator, the strict equality operator always considers operands of different types to be different. 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 x === y description the strict equality operators (=== and !==) use the strict equality comparison algorithm to compare two operands. if the operands are of different types, re
turn false. ...
...ub 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 x === y description the strict equality operators (=== and !==) use the strict equality comparison algorithm to compare two operands. if the operands are of different types, re
turn false. if both operands are objects, re
turn true only if they refer to the same object. if both operands are null or both operands are undefined, re
turn true. if either operand is nan, re
turn false. otherwise, compare the two operand's values: numbers must have the same numeric values. +0 and -0 are considered to be the same value. strings must have the same characters in the same order. booleans must be both true or both fa...
Unsigned right shift (>>>) - JavaScript
the source for this interactive example is stored in a github repository. ...
...https://github.com/mdn/interactive-examples and send us a pull request. syntax a >>> b description this operator shifts the first operand the specified number of bits to the right. excess bits shifted off to the right are discarded. zero bits are shifted in from the left. the sign bit becomes 0, so the result is always non-negative. unlike the other bitwise operators, zero-fill right shift re
turns an unsigned 32-bit integer. for non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. for example, 9 >>> 2 yields 2, the same as 9 >> 2: . 9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) however, this is not th...
async function expression - JavaScript
ression 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 resolveafter2seconds(x) { re
turn 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); re
turn x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds. }); (async function(x) { // async function ex...
...sync function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); re
turn 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); re
turn 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. ...
new operator - JavaScript
eters constructor a class or function that specifies the type of the object instance. arguments a list of values that the constructor will be called with. description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; re
turns this if the function doesn't re
turn an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with new. to define an object type, create a function for the object type that specifies its name and properties. an object can have a property that is itself another object. see the examples below. when the code...
...o(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype. the constructor function foo is called with the specified arguments, and with this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. the object (not null, false, 3.1415 or other primitive types) re
turned by the constructor function becomes the result of the whole new expression. if the constructor function doesn't explicitly re
turn an object, the object created in step 1 is used instead. (normally constructors don't re
turn a value, but they can choose to do so if they want to override the normal object creation process.) you can always add a property to a previously defined object. for exampl...
break - JavaScript
ave to be preceded by a loop statement. a break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of. examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then re
turns the value 3 * x. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } re
turn i * x; } break in labeled blocks the following code uses break statements with labeled blocks. a break statement must be nested within any label it references. notice that inner_block is nested within outer_block. outer_block: { inner_block: { console.
...ole.log('2'); } break within functions syntaxerrors are also generated in the following code examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break; })(); } i += 1; } re
turn i * x; } testbreak(1); // syntaxerror: illegal break statement block_1: { console.log('1'); ( function() { break block_1; // syntaxerror: undefined label 'block_1' })(); } specifications specification ecmascript (ecma-262)the definition of 'break statement' in that specification. ...
export - JavaScript
ntactically invalid despite its import equivalent: import defaultexport from 'bar.js'; // valid export defaultexport from 'bar.js'; // invalid the correct way of doing this is to rename the export: export { default as defaultexport } from 'bar.js'; examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { re
turn x * x * x; } const foo = math.pi + math.sqrt2; var graph = { options: { color:'white', thickness:'2px' }, draw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module included in your html page, we could have: import { cube, foo, graph } from './my-module.js'; graph.options = { color:'blue', thic...
...ype="module", so that it gets recognised as a module and dealt with appropriately. you can't run js modules via a file:// url — you'll get cors errors. you need to run it via an http server. ...
for...of - JavaScript
at are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.iterator] const articleparagraphs = document.queryselectorall('article > p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of loops, abrupt iteration termination can be caused by break, throw or re
turn. in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues outside of the loop } console.log('done'); iterating over generators you can also iterate over generators, i.e. functions generating an iterable object: function* fibonacci() { // a generator function let ...
...yield 3; })(); for (const o of gen) { console.log(o); break; // closes iterator } // the generator should not be re-used, the following does not make sense! for (const o of gen) { console.log(o); // never called. } iterating over other iterable objects you can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [symbol.iterator]() { re
turn { i: 0, next() { if (this.i < 3) { re
turn { value: this.i++, done: false }; } re
turn { value: undefined, done: true }; } }; } }; for (const value of iterable) { console.log(value); } // 0 // 1 // 2 difference between for...of and for...in both for...in and for...of statements iterate over something. the main difference between them i...
import - JavaScript
the default import 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 re
turned 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.
...ded not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.) use dynamic import only when necessary. the static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking. to dynamically import a module, the import keyword may be called as a function. when used this way, it re
turns a promise. import('/modules/my-module.js') .then((module) => { // do something with the module. }); this form also supports the await keyword. let module = await import('/modules/my-module.js'); examples standard import the code below shows how to import from a secondary module to assist in processing an ajax json request. the module: file.js function getjson(url, callback) { ...
JavaScript typed arrays - JavaScript
uld be helpful for javascript code to be able to quickly and easily manipulate raw binary data. this is where typed arrays come in. each entry in a javascript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers. however, typed arrays are not to be confused with normal arrays, as calling array.isarray() on a typed array re
turns false. moreover, not all methods available for normal arrays are supported by typed arrays (e.g. push and pop). buffers and views: typed array architecture to achieve maximum flexibility and efficiency, javascript typed arrays split the implementation into buffers and views. a buffer (implemented by the arraybuffer object) is an object representing a chunk of data; it has no format to speak of...
...t the implementation into buffers and views. a buffer (implemented by the arraybuffer object) is an object representing a chunk of data; it has no format to speak of and offers no mechanism for accessing its contents. in order to access the memory contained in a buffer, you need to use a view. a view provides a context — that is, a data type, starting offset, and the number of elements — that
turns the data into a typed array. arraybuffer the arraybuffer is a data type that is used to represent a generic, fixed-length binary data buffer. you can't directly manipulate the contents of an arraybuffer; instead, you create a typed array view or a dataview which represents the buffer in a specific format, and use that to read and write the contents of the buffer. typed array views typed ar...
Autoplay guide for media and Web Audio APIs - Web media technologies
taking place. example: playing video this simple example plays the first <video> element found in the document. play() won't let the playback begin unless the document has permission to automatically play media. document.queryselector("video").play(); example: handling play() failures it's much easier to detect a failure to autoplay media when you use the play() method to start it. play() re
turns a promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). when autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media. you might use code like this to accomplish the job: let startplaypromise = videoelem.play(); if...
...hatever you need to do only after playback // has begun. }).catch(error => { if (error.name === "notallowederror") { showplaybutton(videoelem); } else { // handle a load or playback error } }); } the first thing we do with the result of play() is make sure it's not undefined. we check for this because in earlier versions of the html specification, play() didn't re
turn a value. re
turning a promise to allow you to determine success or failure of the operation was added more recently. checking for undefined prevents this code from failing with an error on older versions of web browsers. if the promise re
turned by play() is resolved without error, the then() clause is run and can begin whatever needs to be done when autoplay has begun. we then add a catch() hand...
Web video codec guide - Web media technologies
ending on the codec, higher color depths may result in larger compressed file sizes. the determining factor is what internal storage format is used for the compressed data. frame rate primarily affects the perceived smoothness of the motion in the image. to a point, the higher the frame rate, the smoother and more realistic the motion will appear. eventually the point of diminishing re
turns is reached. see frame rate below for details. assuming the frame rate is not reduced during encoding, higher frame rates cause larger compressed video sizes. motion compression of video typically works by comparing frames, finding where they differ, and constructing records containing enough information to update the previous frame to approximate the appearance of the following fr...
...effect is a spatial artifact that occurs when diagonal straight or curved edges that should be smooth take on a jagged appearance, looking somewhat like a set of stair steps. this is the effect that is being reduced by "anti-aliasing" filters. wagon-wheel effect the wagon-wheel effect (or stroboscopic effect) is the visual effect that's commonly seen in film, in which a
turning wheel appears to rotate at the wrong speed, or even in reverse, due to an interaction between the frame rate and the compression algorithm. the same effect can occur with any repeating pattern that moves, such as the ties on a railway line, posts along the side of a road, and so forth. this is a temporal (time-based) aliasing issue; the speed of the rotation interferes with the frequency of th...
The "codecs" parameter in common media types - Web media technologies
to be used when adapting the decoded color to the render target. mc the two-digit value for the matrixcoefficients property. this value comes from the table in section 8.3 of the iso/iec 23001-8:2016 specification. this value indicates which set of coefficients to use when mapping from the native red, blue, and green primaries to the luma and chroma signals. these coefficients are in
turn used with the equations found in that same section. ff indicates whether to restrict the black level and color range of each color component to the legal range. for 8 bit color samples, the legal range is 16-235. a value of 00 indicates that these limitations should be enforced, while a value of 01 allows the full range of possible values for each component, even if the resulting colo...
...r in a few situations. firstly, you can use it with the <source> element when creating an <audio> or <video> element, in order to establish a group of options for the browser to choose from when selecting the format of the media to present to the user in the element. you can also use the codecs parameter when specifying a mime media type to the mediasource.istypesupported() method; this method re
turns a boolean which indicates whether or not the media is likely to work on the current device. ...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
ing the attributes being a good idea. let’s move forward a few years to the era of responsive design. to keep images from breaking out of their containers when the container becomes narrower than the image, developers started using css like the following: img { max-width: 100%; height: auto; } this is really useful for responsive layouts, but unfortunately it causes the jank problem to re
turn — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0. when the image finally loads, the same jank will occur as the page layout is shifted to make space for it. a new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsics...
...orrectly. therefore, once the image is loaded, we start using the intrinsic aspect ratio of the loaded image rather than the aspect ratio from the attributes, so it displays at the correct aspect ratio. summary so there you have it — eliminating another piece of jank from web layout! there is no need for a web developer to do anything special to their code to take advantage of this, besides re
turning to the habit of using width and height attributes in their html. they'll just get it for free. note: this new mechanism is enabled in firefox 69 in beta and nightly as the spec is worked out (controlled by the layout.css.width-and-height-map-to-aspect-ratio.enabled pref), and it is currently being implemented in chrome. it will ship with firefox 71. ...
Understanding latency - Web Performance
html includes requests for multiple css, scripts, and media files. the greater the number and size of these requests, the greater the impact of high latency on user experience. on a connection with low latency, requested resources will appear almost immediately. on a connection with high latency, there will be a discernible delay between the time that a request is sent, and the resources are re
turned. we can determine the amount of latency by measuring the speed with which the data moves from one network location to another. latency can be measured one way, for example, the amount of time it takes to send a request for resources, or the length of the entire round-trip from the browser’s request for a resource to the moment when the requested resource arrives at the browser. network thro...
... ...
Progressive web app structure - Progressive web apps (PWAs)
nttocache = appshellfiles.concat(gamesimages); the next block installs the service worker, which then actually caches all the files contained in the above list: self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then(function(cache) { console.log('[service worker] caching all: app shell and content'); re
turn cache.addall(contenttocache); }) ); }); last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); re
turn r || fetch(e.request).then(functio...
...ache); }) ); }); last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); re
turn r || fetch(e.request).then(function(response) { re
turn caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); re
turn response; }); }); }) ); }); the javascript data the games data is present in the data folder in a form of a javascript object (games.js): var games = [ { slug: 'lost-in-cy...
The building blocks of responsive design - Progressive web apps (PWAs)
r or device accessing the site to provide an optimized experience. one approach to this is to create different versions of your site/app for different platforms or browsers and serve them appropriately after detecting which browser or platform is looking at your site. but this is increasingly inefficient: browser sniffing is inherently error prone, and maintaining multiple copies of your code can
turn out to be a nightmare. it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately. this tends to be termed responsive design or adaptive design...
...dth: 480px)"> this says that the whole stylesheet will not be linked to the html unless the viewport width is 480px or less. moving on to the javascript, <script> elements don't accept media attributes, so i had to do this a different way. fortunately there is a javascript construct called window.matchmedia(), which can conditionally run javascript constructs depending on whether a media query re
turns true or not. we opened up the brick.js file and wrapped the whole lot in the following: if (window.matchmedia("(max-width: 480px)").matches) { // the whole of brick.js goes here! } this causes nothing inside the brick.js file to be run unless the viewport width is 480px or less. problem solved. really wide screens one thing you might notice is that when the viewport gets very wide (such as...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
attribute for svgelement implementation status unknown moved pathlength attribute and gettotallength() and getpointatlength() methods from svgpathelement to svggeometryelement implemented (bug 1239100) document structure change notes svgsvgelement.suspendredraw(), svgsvgelement.unsuspendredraw(), and svgsvgelement.unsuspendredrawall() deprecated
turned into no-ops (bug 734079) externalresourcesrequired attribute removed implementation status unknown auto value for width and height in <image> implementation status unknown referencing entire document with <use> implementation status unknown lang attribute on <desc> and <title> implemented (bug 721920) css transforms on outermost <svg> not...
...tes on svguseelement removed implementation status unknown <use> event flow following shadow dom spec. ...
boolean - XPath
notes a number evaluates to false if it is positive or negative zero or nan. otherwise, it evaluates true. a node-set evaluates to true if it is non-empty. a string evaluates to false if it an empty string. otherwise, it evaluates to true. ...
... notes a number evaluates to false if it is positive or negative zero or nan. otherwise, it evaluates true. a node-set evaluates to true if it is non-empty. a string evaluates to false if it an empty string. otherwise, it evaluates to true. ...
generate-id - XPath
notes the same id must be generated every time for the same node in the current document in the current transformation. ...
... notes the same id must be generated every time for the same node in the current document in the current transformation. ...
number - XPath
notes strings are converted to a number by stripping the leading whitespace in the string before the number and ignoring whitespace after the number. if the string does not match this pattern, then the string is converted to nan. ...
... notes strings are converted to a number by stripping the leading whitespace in the string before the number and ignoring whitespace after the number. if the string does not match this pattern, then the string is converted to nan. ...
string - XPath
a number is converted as follows: nan is converted to the string nan. ...
... a number is converted as follows: nan is converted to the string nan. ...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
literal result element transform, otherwise it must be an xsl:stylesheet or xsl:transform element. transforming the document you can use the xsltprocessor.transformtodocument() or xsltprocessor.transformtofragment() methods to transform a document using the imported xslt stylesheet. ...
...this is handy because appending a fragment to another node transparently appends all the children of that fragment, and the fragment itself is not merged. fragments are therefore useful for moving nodes around and storing them without the overhead of a full document object. xsltprocessor.transformtofragment() takes two arguments: the source document to be transformed (as...
Loading and running WebAssembly code - WebAssembly
the object looks like this: { module : module // the newly compiled webassembly.module object, instance : instance // a new webassembly.instance of the module object } note: usually we only care about the instance, but it’s useful to have the module in case we want to cac...
...d webassembly.module object, instance : instance // a new webassembly.instance of the module object } note: usually we only care about the instance, but it’s useful to have the module in case we want to cache it, share it with another worker or window via postmessage(), or simply create more instances. note: the second overload form takes a webassembly.module object as an argument, and re
turns a promise directly containing the instance object as the result. see second overload example. running your webassembly code once you've got your webassembly instance available in your javascript, you can then start using features of it that have been exported via the webassembly.instance.exports property. your code might look something like this: webassembly.instantiatestreaming(fetch('mymod...
Navigator.mozNotification - Archive of obsolete content
ently, these are only supported on firefox mobile and firefox os. see displaying notifications for an example. the support for this property as been dropped in favor of the standard notification constructor. method overview notification createnotification(in domstring title, in domstring description, in domstring iconurl optional); methods createnotification() creates and re
turns a notification object that can be used to display the specified message with an optional url. notification createnotification( in domstring title, in domstring description, in domstring iconurloptional ); parameters title the notification title. description the text to display in the notification. iconurl optional a url identifying the image to display in the notification. ret...
Content Scripts - Archive of obsolete content
this add-on adds a button to firefox: when the user clicks the button, the add-on attaches a content script to the active tab, sends the content script a message called "my-addon-message", and listens for a response called "my-script-response": //main.js var tabs = require("sdk/tabs"); var buttons = require("sdk/ui...
Contributor's Guide - Archive of obsolete content
allow each instance to have their own state, whereas member functions are properties that allow instances to have behavior. inheritance allows classes to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it
turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. content processes a content process was supposed to run all the code associated with a single tab. conversely, an add-on process was supposed to run all the code associated with a single add-on. neither content or add-on proceses were ever actuall...
Porting the Library Detector - Archive of obsolete content
ding to the array of library names, and use that to build the widget's html content dynamically: function buildwidgetviewcontent(librarylist) { widgetcontent = htmlcontentpreamble; librarylist.foreach(function(library) { widgetcontent += buildiconhtml(icons[library.name], library.name + "<br>version: " + library.version); }); widgetcontent += htmlcontentpostamble; re
turn widgetcontent; } function updatewidgetview(tab) { var widgetview = widget.getview(tab.window); if (!tab.libraries) { tab.libraries = []; } widgetview.content = buildwidgetviewcontent(tab.libraries); widgetview.width = tab.libraries.length * icon_width; } main.js will use the tabs module to update the widget's content when necessary (for example, when the user switches between tab...
Working with Events - Archive of obsolete content
tton = ui.actionbutton({ id: "my-button", label: "my button", icon: "./icon-16.png", onclick: handleclick }); function handleclick(state) { panel.show({ position: button }); } this wildcard feature does not yet work for the tabs or windows modules. adding listeners in constructors event emitters may be modules, as is the case for the ready event above, or they may be objects re
turned by constructors. in the latter case the options object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onopen", "onready" and so on. then in the constructor you can assign a listener function to this property as an alternative to calling the object's on() method. for example: the actionbutton object em...
clipboard - Archive of obsolete content
replace the contents of the user's clipboard with the provided data. parameters data : string the data to put on the clipboard. datatype : string the type of the data, , one of "text", "html", "image". optional. get(datatype) get the contents of the user's clipboard. parameters datatype : string retrieve the clipboard contents only if matching this type (optional). the function will re
turn null if the contents of the clipboard do not match the supplied type. properties currentflavors data on the clipboard is sometimes available in multiple types. for example, html data might be available as both a string of html (the html type) and a string of plain text (the text type). this property is an array contains all types in which the data currently on the clipboard is available. ...
indexed-db - Archive of obsolete content
b = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) re
turn; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/action").actionbutton({ id: "add", label: "add", icon: "./add.png", onclick: function() { additem(require("sdk/tabs").activetab.title); } }); var list = require("sdk/...
notifications - Archive of obsolete content
fication to the user. parameters options : object optional options: name type title string a string to display as the message's title. text string a string to display as the body of the message. iconurl string the url of an icon to display inside the message. it may be a remote url, a data uri, or a url re
turned by the self module. onclick function a function to be called when the user clicks the message. it will be passed the value of data. data string a string that will be passed to onclick. ...
page-mod - Archive of obsolete content
py of the content scripts. in this case the listener assigned to onattach is called once for each loaded document, and the add-on code will have a separate worker for each document. to learn much more about communicating with content scripts, see the guide to content scripts and in particular the chapter on communicating using port. mapping workers to tabs the worker has a tab property which re
turns the tab associated with this worker. you can use this to access the tabs api for the tab associated with a specific document: var pagemod = require("sdk/page-mod"); var tabs = require("sdk/tabs"); pagemod.pagemod({ include: ["*"], onattach: function onattach(worker) { console.log(worker.tab.title); } }); destroying workers workers generate a detach event when their associated docum...
system - Archive of obsolete content
file path var profilepath = require('sdk/system').pathfor('profd'); // get os temp files directory (/tmp) var temps = require('sdk/system').pathfor('tmpd'); // get os desktop path for an active user (~/desktop on linux // or c:\documents and settings\username\desktop on windows). var desktoppath = require('sdk/system').pathfor('desk'); parameters id : string the id of the special directory. re
turns string : the path to the directory. properties env this object provides access to environment variables. you can get the value of an environment variable by accessing the property with that name: var system = require("sdk/system"); console.log(system.env.path); you can test whether a variable exists by checking whether a property with that name exists: var system = require("sdk/system");...
chrome - Archive of obsolete content
should avoid using the api if at all possible. we intend to deprecate it in future releases. if you use this api you can expect your add-on to get an extra security review by addons.mozilla.org. this module should not be confused with the "chrome" global variable that webextensions can use to access apis. the chrome module gives an add-on sdk add-on access to the components object, which in
turn gives it access to a large set of privileged low-level firefox apis. chrome is a built-in pseudo module of the toolkit loader. see the chrome authority tutorial for more details. you can see an example of using this api in the xul migration guide. ...
console/traceback - Archive of obsolete content
e the name of the function being executed at the stack frame, or null if the function is anonymous or the stack frame is being executed in a top-level script or module. see nsiexception for more information. globals functions fromexception(exception) attempts to extract the traceback from exception. parameters exception : exception exception where exception is an nsiexception. re
turns traceback : json representation of the traceback or null if not found. get() re
turns json : re
turns the json representation of the stack at the point that this function is called. format(tborexception) given a json representation of the stack or an exception instance, re
turns a formatted plain text representation of it, similar to python's formatted stack tracebacks. if no argument is prov...
content/symbiont - Archive of obsolete content
mposed from the loader and worker traits. it inherits functions to load and configure content scripts from the loader, and functions to exchange messages between content scripts and the main add-on code from the worker. var { symbiont } = require('sdk/content/content'); var thing = symbiont.resolve({ constructor: '_init' }).compose({ constructor: function thing(options) { // `getmyframe` re
turns the host application frame in which // the page is loaded. this._frame = getmyframe(); this._init(options) } }); see the panel module for a real-world example of usage of this module. globals constructors symbiont(options) creates a content symbiont. parameters options : object optional options: name type frame object the host appli...
content/worker - Archive of obsolete content
orker 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 customized messages 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, re
turns 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 co...
net/url - Archive of obsolete content
experimental enables you to read content from a uri. globals functions readuri(uri, options) reads a uri and re
turns a promise. parameters uri : string the url, as a string, to load. options : object optional options: name type sync boolean if this option is set to true, the promise re
turned will be resolved synchronously. defaults to false if not provided. charset string the character set to use when read the content of the uri given. defaults to utf-8 if not provided. re
turns promise : the promise that will be resolved with the content of the url given. ...
util/collection - Archive of obsolete content
eration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the iteration. methods add(itemoritems) adds a single item or an array of items to the collection. any items already contained in the collection are ignored. parameters itemoritems : object an item or array of items. re
turns collection : the collection. remove(itemoritems) removes a single item or an array of items from the collection. any items not contained in the collection are ignored. parameters itemoritems : object an item or array of items. re
turns collection : the collection. properties length the number of items in the collection array. ...
Low-Level APIs - Archive of obsolete content
ons. in many cases these modules have simpler, more restricted analogs among the "high-level apis" (for example, windows or request). these modules are still in active development, and we expect to make incompatible changes to them in future releases. /loader create commonjs module loaders. chrome the chrome module gives an add-on sdk add-on access to the components object, which in
turn gives it access to a large set of privileged low-level firefox apis. console/plain-text constructor for a console instance. console/traceback functionality similar to python's traceback module. content/content re-exports three objects from three other modules: loader, worker, and symbiont. content/loader provides one of the building blocks for those modules that use content scripts to int...
Storing annotations - Archive of obsolete content
orage.annotations.push(newannotation); } this function calls a constructor for an annotation object, which we also need to supply: function annotation(annotationtext, anchor) { this.annotationtext = annotationtext; this.url = anchor[0]; this.ancestorid = anchor[1]; this.anchortext = anchor[2]; } now we need to link this code to the annotation editor, so that when the user presses the re
turn key in the editor, we create and store the new annotation: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) handlenewannotation(annotationtext, this.annotationanchor); annotationeditor.hi...
Chrome Authority - Archive of obsolete content
access to the infamous components object, which grants unfettered access to the host system. from this, the module can do pretty much anything the browser is capable of. to obtain these privileges, the module must declare its intent with a statement like the following: var {cc, ci} = require("chrome"); the "chrome" built-in pseudo module is provided by the "toolkit/loader" module. the object re
turned by require("chrome"), when unpacked with the destructuring assignment feature available in the mozilla js environment, will provide the usual components.* aliases: cc an alias for components.classes. ci an alias for components.interfaces. cu an alias for components.utils. cr an alias for components.results. cm an alias for components.manager. components an alias for components itsel...
Autocomplete - Archive of obsolete content
first, declare a panel with the "autocomplete" type, like so: <panel id="popup_autocomplete" type="autocomplete" noautofocus="true" /> now set the autocompletepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ... autocompletepopup="popup_autocomplete" /> finally, make sure that the value of the browser.formfill.enable pref is set to true. ...
Modules - Archive of obsolete content
the use of eval() will probably not be of concern because it is only being used on the exported_symbols array which should not depend on user input. function importmodule (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
Progress Listeners - Archive of obsolete content
licking a link, using the back/forward button, by typing an address in the location bar, etc.) and also when user switches tabs. var myextension = { oldurl: null, init: function() { gbrowser.addprogresslistener(this); }, uninit: function() { gbrowser.removeprogresslistener(this); }, processnewurl: function(auri) { if (auri.spec == this.oldurl) re
turn; // now we know the url is new... alert(auri.spec); this.oldurl = auri.spec; }, // nsiwebprogresslistener queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onlocationchange: function(aprogress, arequest, auri) { this.processnewurl(auri); }, onstatecha...
SVG General - Archive of obsolete content
here are some examples of using it: var circle = makesvg("circle", {id: "circle1", cx: "60", cy: "60", r: "50"}); var img = makesvg("image", {id: "img1", x: "110", y: "110", width: "100", height: "100", svghref: "bubbles.png"}); var text = makesvg("text", {id: "text1", x: "60", ...
JavaScript timers - Archive of obsolete content
ere are some code snippets which simplify and abstract the management of daemons. requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. the method takes as an argument a callback to be invoked before the repaint. performance.now() performance.now() re
turns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. this timestamp is equal to the number of milliseconds since the navigationstart attribute of the performance.timing interface. date.now() date.now() re
turns the number of milliseconds elapsed since 1 january 1970 00:00:00 utc. using javascript timers within workers workers can use timeouts and intervals jus...
Tree - Archive of obsolete content
getting the cell from a mouse click your first choice is likely to try <treecell onclick="yourfunc();"/> or something similar. but this will not work. you can't add event handlers to <treecell>. instead, you can add the event handler to the ...
XPath - Archive of obsolete content
notes and sample code for xpath and ajax (the following was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: re
turnedxml) this should be used as : re
turnedxml.evaluate(xpathexpression,re
turnedxml,namespaceresolver,re
turntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which re
turn responsexml object to parsexml function function parsexml(obj)//obj is the re
turnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); re
turn;...
Extension Packaging - Archive of obsolete content
file at the root of the zip. users can download xpi files from a website, or from a local file, and install by opening it, or dragging it into the extension manager window. the xpi file must contain only uncompressed files, or files compressed using the deflate algorithm. the mime type recognized by firefox for xpi files is application/x-xpinstall. since most http servers are not configured to re
turn this mime type for the .xpi extension by default, you will probably need to configure your http server. in the apache http server, this can be done by adding the following directive to the configuration file or .htaccess: addtype application/x-xpinstall .xpi install extension files directly if you know the location of the application (if you are installing an extension as part of the applicat...
Extension Etiquette - Archive of obsolete content
that it be indicative of the name of your add-on. generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be used elsewhere, and therefore unsuitable to the purpose. call .noconflict(true) where applicable many common libraries which create global variables provide a method called noconflict, or similar, which revert any global variables they've declared, and re
turn the object itself. for instance, calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and re
turn the jquery object itself, for future use by the caller. when available, these methods should always be used to prevent conflicts with third-party code. names and metadata naming be creative! don't be redundant and include "extension," "mozilla/firefox/thunderbi...
Hiding browser chrome - Archive of obsolete content
augmenting the behavior of the xulbrowserwindow object's hidechromeforlocation() method. note: don't simply replace the hidechromeforlocation() method; this will likely hurt the functionality of firefox itself as well as other extensions. use the technique demonstrated here. var prevfunc = xulbrowserwindow.hidechromeforlocation; xulbrowserwindow.hidechromeforlocation = function(alocation) { re
turn (/* your test goes here */) || prevfunc.apply(xulbrowserwindow, [alocation]); } this works by saving a reference to the current implementation of the hidechromeforlocation() method, then replacing it with a new method that calls through to the previous implementation. by chaining multiple implementations of the method together in this way, everyone that wants to hide chrome can do so when appropr...
Install Manifests - Archive of obsolete content
include the public part of the cryptographic key in an updatekey entry in the install.rdf of the add-on. this can be generated using the mccoy tool. any line breaks and whitespace as part of this entry are ignored. <em:updatekey>migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdk426erd/h3xtsjvab5+pjqbhj zc9edi5ocjs8r3fiobj9zhjk1txeae7jwqt9wumbwtefvws+fi9vwu8058n9chhd nyep6i4luuyj
turnn7yw/igzyij2oksya32ruxayteqawqpt/j63wbixiecxmysf awb/zh4kapiy3vnrzqidaqab</em:updatekey> updateurl a link to a custom update manifest file that specifies available updates to the add-on. the format is described below. if enabled, the add-on manager periodically checks with this manifest file to determine if newer versions are available. when not included, the add-on manager will st...
Listening to events in Firefox extensions - Archive of obsolete content
event and is used to populate the character set menu and update the ui elements associated with any detected feeds or opensearch plugins for the website. xulbrowserwindow xulbrowserwindow is an nsiwebprogresslistener used to get progress events for the currently visible browser. ...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
const prunichar *begin, *end;+ mystring.beginreading(&begin, &end); the frozen string api uses comparator functions instead of a virtual comparator class. unicharutils has been modified to provide a frozen-linkage comparator: nsstring mystring = somestring; - if (mystring.equals(otherstring, nscaseinsensitivestringcomparator())) + if (mystring.equals(otherstring, caseinsensitivecompare)) re
turn ns_ok; // woot, we're equal in all things but case when using unicharutils from frozen-linkage code, link against the unicharutil_external_s static library. the frozen string api doesn't implement the left(), mid(), or right() signatures. use stringhead(), substring(), and stringtail() instead: nsstring buffer = somestring; - nscautostring prefix;- buffer.left(prefix, 4); + const nsdependentsu...
Handling Preferences - Archive of obsolete content
ome namespacing and finally the actual name of the preference. name parts are normally separated by dots. now let's look at how we actually manage the preference values. managing preferences with xpcom we use the preferences service in order to get and set preference values: this._prefservice = cc["@mozilla.org/preferences-service;1"].getservice(ci.nsiprefbranch); // ... ...
Introduction - Archive of obsolete content
we have poured years of xul experience into it, providing many solutions for problems extension developers commonly run into. xul school was created by appcoast (formerly glaxstar), one of the few companies dedicated to building high-quality firefox extensions. a team of over a dozen xul developers conformed glaxstar at the time this tutorial was created, and the combined experiences of years creating firefox extensions are reflected here. ...
JavaScript Object Management - Archive of obsolete content
s is as follows: /** * user class. represents a hello world user (whatever that may be). */ 〈modulenamespace〉.user = function(aname, aurl) { this._name = aname; this._url = aurl; }; /** * user class methods. */ 〈modulenamespace〉.user.prototype = { /* the name of the user. */ _name : null, /* the url of the user. */ _url : null, /** * gets the user name. * @re
turn the user name. */ get name() { re
turn this._name; }, /** * gets the user url. * @re
turn the user url. */ get url() { re
turn this._url; } }; in this example we defined a fictitious user class for the hello world extension. using the function keyword to define a class is odd, but this is just the javascript way: functions are also objects. the definition of the cl...
Security best practices in extensions - Archive of obsolete content
re than just pages, and more and more add-ons are interacting with web services via an application programming interface (api). many of the items talked about so far in this document apply in this sphere, but here are some additional tips: api providers should use the https protocol, which provides better protection for data passed over the network. json has become a popular data format for re
turn formats for web services. be sure to read using native json to find out the correct way to handle it. apis can't be used with self-signed certificates. remote javascript and content there are a number of ways of remote scripts being used in extensions. they can be included in content, or downloaded at intervals. non-chrome urls in chrome xul or html such as the following example are not allo...
Setting up an extension development environment - Archive of obsolete content
quire reloading of the document overlaid. browser.dom.window.dump.enabled = true. enables the use of the dump() statement to print to the standard console. see window.dump for more info. you can use nsiconsoleservice instead of dump() from a privileged script. javascript.options.strict = true. enables strict javascript warnings in the error console. note that since many people have this setting
turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. you can filter those with console2. devtools.chrome.enabled = true. this enables to run javascript code snippets in the chrome context of the scratchpad from the tools menu. don't forget to switch from content to browser as context. devtools.debugger.remote-enabled =...
Signing an XPI - Archive of obsolete content
e: c:\projects\codesigning\> dir x509* 14/12/2005 15:13 1,031 x509.cacert 14/12/2005 15:13 798 x509.raw c:\projects\codesigning\> certutil -d . -l mytestcert u,u,cu prepare xpi file for signing create a new folder just for signing, copy your existing xpi into it, unzip* it (maintaining paths), delete the xpi and re
turn to the certificate-database folder. *assumes you have a zip utility available on your system path. this example is using the cygwin bin/zip.exe tool. you can use a graphical zip tool provided it manages the internal sub-directory structure properly. an alternative is to use winrar. the 7-zip tool doesn't work when creating mozilla xpi signed archives because it sorts the directory entries alpha...
chargingchange - Archive of obsolete content
tery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.charging boolean the system's battery charging status. re
turns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. re
turns false if the battery is discharging. read only. example navigator.getbattery().then(function(battery) { console.log("battery charging? " + (battery.charging ? "yes" : "no")); battery.addeventlistener('chargingchange', function() { consol...
chargingtimechange - Archive of obsolete content
no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.chargingtime double (float) the remaining time in seconds until the system's battery is fully charged. re
turns 0 if the battery is fully charged. re
turns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time. read only. example navigator.getbattery().then(function(battery) { console.log("battery charging time: " + battery.chargingtime + " seconds"); battery.addeventlistener('chargingtimechange', function() { console.log...
dischargingtimechange - Archive of obsolete content
properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.dischargingtime double (float) the remaining time in seconds until the system's battery is completely discharged and the system is about to be suspended. re
turns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the system. read only. example navigator.getbattery().then(function(battery) { console.log("battery discharging time: " + battery.dischargingtime + " seconds"); battery.addeventlistener('dischargingtimechange', function() { ...
levelchange - Archive of obsolete content
bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.level double (float) the system's battery charging level scaled from 0 to 1.0. re
turns 0 if the battery is empty and the system is about to suspend. re
turns 1.0 if the battery is full, if the implementation is unable to report the battery's level, or if there is no battery attached to the system. read only. example navigator.getbattery().then(function(battery) { console.log("battery level: " + battery.level * 100 + " %"); battery.addeventlistener('levelchange', funct...
Getting the page URL in NPAPI plugin - Archive of obsolete content
to do that is to get it from the npstream that is passed to npp_newstream. tradeoffs: npapi only probably works in all browsers, all versions is sort of backwards (?) advantages / disadvantages ? via dom from benjamin smedberg: the npapi gives you the ability to get access to the nsidomwindow object which contains the current plugin via the npnvdomelement enum passed to npn_getvalue. this re
turns an addrefed nsidomelement interface pointer from which you can call .ownerdocument (on nsidomnode), queryinterface that object to nsidom3document, and call .documenturi. tradeoffs: is inherently incompatible with other non-mozilla browsers (i.e. does not work in opera, safari etc.) compatible with older versions of the mozilla (probably back to mozilla 1.0) requires c++ ...
Install.js - Archive of obsolete content
+ '/' + this.extshortname + '/'; install.registerchrome(install.skin | installtype, jarpath, regpath); } // perform install var err = install.performinstall(); if (err == install.success || err == install.reboot_needed) { if (!this.silentinstall && this.extpostinstallmessage) { install.alert(this.extpostinstallmessage); } } else { this.handleerror(err); re
turn; } }, parsearguments: function() { // can't use string handling in install, so use if statement instead var args = install.arguments; if (args == 'p=0') { this.profileinstall = false; this.silentinstall = true; } else if (args == 'p=1') { this.profileinstall = true; this.silentinstall = true; } }, handleerror: function(err) { if (!this.silentinstall) { ...
Monitoring WiFi access points - Archive of obsolete content
ocument.getelementbyid("c"); c.innerhtml = "<p>" + count++ + "</p>"; }, onerror: function (value) { alert("error: " +value); }, queryinterface: function(iid) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); if (iid.equals(components.interfaces.nsiwifilistener) || iid.equals(components.interfaces.nsisupports)) re
turn this; throw components.results.ns_error_no_interface; }, } netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var listener = new test(); var wifi_service = components.classes["@mozilla.org/wifi/monitor;1"].getservice(components.interfaces.nsiwifimonitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id...
No Proxy For configuration - Archive of obsolete content
alability - not usable for local domains with numerous hostnames. not usable for large number of filters (ad blocking). mozilla implements this feature with significant limitations, users may find that writing a pac file is more suitable for their needs. testing contributors can test this feature, even without a proxy server, using a "negative proxy server test". proxy connections that fail re
turn an error "the proxy server you have configured cannot be found", so configure your browser to use a non-existent http proxy (hostname: "imaginary", port "80"). test each destination in an http: url. all proxied urls will re
turn errors, all non-proxied connections will be attempted normally (direct connection). hostnames filter test destination result basic filtering u...
Chromeless - Archive of obsolete content
apabilities of the chromeless platform is the ability to safely embed untrusted web applications inside these applications. chromeless vs prism/webrunner prism (an ex-mozilla labs project, now discontinued but kept going independently of mozilla under the [now discontinued] webrunner name) was/is a way to make web pages superficially appear to be native applications. firefox users could choose to
turn a web page into a "prism application" and have an icon added to their desktop to launch it without the firefox user interface surrounding the page. however, prism "applications", being web pages, were subject to all the normal restrictions that browsers place on a web page. for example, prism applications could not read/write files directly from/to the computer's file system. one of the ideas beh...
Finding the code to modify - Archive of obsolete content
ct a node in the tree, a red border flashes for several seconds around the visual representation of that node in the browser window. scroll down the tree to the statusbar node and select it. notice the flashing red border around the horizontal status bar at the bottom of the browser window. click the plus sign next to the statusbar node in the dom inspector and select each statusbarpanel node in
turn. notice the flashing red border around each different section of the status bar. open the navigator.xul file in a text editor. find the statusbar element within it. this is where we are going to add our tinderbox status ui. inspectorwidget the inspectorwidget extension adds a toolbar button and context menus for invoking the dom inspector (domi) for either chrome or content elements.thus this ...
Creating a Microsummary - Archive of obsolete content
crosummaries from within the pages themselves using a <link rel="microsummary"> element, f.e.: <head> <link rel="microsummary" href="index.php?view=microsummary"> </head> when firefox encounters a <link rel="microsummary"> element, it loads the url in the href attribute. if the url points to a generator, it uses the generator to generate the microsummary for the page. otherwise, if the url re
turns plain text content (or html content that can be converted to plain text), firefox uses the content as the microsummary for the page. beginnings generators are expressed as xml documents whose root element is the <generator> element in the http://www.mozilla.org/microsummaries/0.1 namespace. to begin building the generator, create a new empty text file and add an xml declaration and empty <gene...
Block and Line Layout Cheat Sheet - Archive of obsolete content
h margins apply by default). the flag is also set when reflowing a frame whose computed bottom border padding is zero. (why?) brs_applytopmargin this flag is set if the top margin should be considered when placing a linebox that contains a block frame. it may be set as a side-effect of calling nsblockframe::shouldapplytopmargin(); once set, shouldapplytopmargin() uses it as a fast-path way to re
turn whether the top margin should apply. if the flag hasn't been set in the block reflow state, then shouldapplytopmargin() will crawl the line list to see if a block frame precedes the specified frame. if so, the top margin should be applied, and the flag set to cache the result. (if not, the top margin will be applied as a result of the generational margin collapsing logic in nsblockreflowcontext::...
Downloading Nightly or Trunk Builds - Archive of obsolete content
ds. as a development organization, the mozilla community tends to describe things from the bottom up. so to figure out how to download a cutting edge or bleeding edge or 'beta' version of firefox, you need to look for a "build" (which is developer-speak for the packaged files you can download) of 1.9.1 (the number of the underlying 'platform' called 'gecko' or 'mozilla' that firefox uses). as it
turns out there is a platform number for every firefox number, but they are not the same number. firefox 3.0 corresponds to mozilla 1.9.0; firefox 3.5 corresponds to mozilla 1.9.1; firefox 3.6 corresponds to mozilla 1.9.2. however, the numbers are not used all of the time. sometimes the firefox releases are described by a code name. for example "shiretoko" is used for firefox 3.5. and very often neit...
CRMF Request object - Archive of obsolete content
to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. rfc 4211, the internet x.509 public key infrastructure certificate request message format (crmf), defines a certreqmessage. the object re
turned by generatecrmfrequest() contains one of those. ...
generateCRMFRequest() - Archive of obsolete content
ion set for keyusage.) "dh-ex" "ec-ex" "ec-dual-use" "ec-sign" "ec-sign-nonrepudiation" "ec-nonrepudiation" the generatecrmfrequest() method will cause the user to be presented with a key generation dialog. the dialog describes the key generation process and gives the user the opportunity to cancel the operation. the method generatecrmfrequest() will re
turn an instance of a crmf request object. the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the re
turned object to get the result of the crmf generation. the string found by accessing crmfobject.request is the base-64 encoded crmf message to be sent to the ca/ra, or an error string. the possible error strings are: error string de...
Enabling Experimental Jetpack Features - Archive of obsolete content
t are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list() arrayre
turns an array of the set of potential stringmountpath as used in jetpack.future.import(). this is an example of how to get this array. a quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list();console.log(list); open the firebug console to view. ...
Enabling - Archive of obsolete content
s that are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list()re
turns an array of the set of potential stringmountpath as used in jetpack.future.import(). this is an example of how to get this array. a quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list(); console.log(list); open the firebug console to view. ...
Enabling Experimental Jetpack Features - Archive of obsolete content
are available, see the method below. string here is an example of how to import a feature (the clipboard) from the future. jetpack.future.import("clipboard"); the goal here is to be able to remove the jetpack.future.import() call when the feature has been formally accepted into the core without additionally changing the script (barring any other changes made during integration). list() arrayre
turns an array of the set of potential stringmountpath as used in jetpack.future.import(). this is an example of how to get this array. a quick way of displaying the list is to write it to the console.log. var list = jetpack.future.list(); console.log(list); open the firebug console to view. ...
Microsummary topics - Archive of obsolete content
esponse to a microsummary-related request. for example, you might include the following header in your response to prevent firefox from making another microsummary-related request for one hour: cache-control: max-age=3600 note: because of a technical limitation (bug 346820), firefox uses the same cache for both microsummary-related requests and user-initiated requests, so the cache headers you re
turn apply to both. thus if your cache headers tell firefox not to refresh a page on your site more than once per hour, and the user reloads the page within that time period, the user will see the cached version of your page, which may not be what you want. to mitigate this effect, only re
turn microsummary-specific cache headers in response to microsummary-related requests. then only microsummary user...
NSC_SetPIN - Archive of obsolete content
_setpin( ck_session_handle hsession, ck_char_ptr poldpin, ck_ulong uloldlen, ck_char_ptr pnewpin, ck_ulong ulnewlen ); parameters nsc_setpin takes five parameters: hsession [input] poldpin [input] . uloldlen [input] .; pnewpin [input] .; ulnewlen [input] . description nsc_setpin modifies the pin of user that is currently logged in. this is only valid for the private_key_slot. re
turn value ckr_ok examples #include <assert.h> see also fc_setpin ...
New Security Model for Web Services - Archive of obsolete content
do.mozilla.org, etc. will be granted access. implementation nsiwebscriptsaccessservice this interface provides a way to check whether the running script has access to the server that the script wishes to communicate. boolean canaccess(in nsiuri atransporturi, in astring atype); atransporturi - the service uri atype - type requested by the script ( ex. soapv, soap, load, etc. ) re
turn pr_true if access granted else pr_false void invalidatecache(in string atransporturi); invalidate cached entry for the given transport uri. empty the cache by passing in a empty string nswebscriptsaccess(implements nsiwebscriptsaccessservice) maintains access information, for servers, in an access-info-cache ( hashtable ). if an entry was not found in the cache creates one ...
Porting NSPR to Unix Platforms - Archive of obsolete content
vely orthogonal source code in the thread management, thread synchronization, and i/o area. the pthreads source files are in <tt>mozilla/nsprpub/pr/src/pthreads</tt>. i use the netbsd port i recently received as an example to illustrate the mechanical part of the porting process. there are a few new files you need to add: <tt>mozilla/nsprpub/config/netbsd.mk</tt> the name of this file is the re
turn value of <tt>uname -s</tt> on the platform, plus the file suffix <tt>.mk</tt>. if the re
turn value of <tt>uname -s</tt> is too long or ambiguous, you can modify it in <tt>mozilla/nsprpub/config/arch.mk</tt> (the makefile variable <tt>os_arch</tt>). <tt>mozilla/nsprpub/pr/include/md/_netbsd.cfg</tt> we have a program <tt>mozilla/nsprpub/pr/include/gencfg.c</tt> to help you generate partof this f...
Configuration - Archive of obsolete content
to the web application, but also to you. this identifier becomes the name of the profile folder where your webapp is installed: google.mail@your.name uri the uri/url of the web app: http://mail.google.com name the display name of the application: gmail icon the icon you want to use for the prism window when running this web app. the actual icon file should be stored in the webapp bundle. status
turns the status messages on or off for this web app: yes or no location
turns the readonly location bar on or off for this web app: yes or no navigation
turns the hotkey history navigation (alt+left, alt+right and alt+home) on or off for this web app: yes or no splashscreen filename of an html page to be displayed while the app is loading. the file must be located in the web app home directory: splas...
Scripting - Archive of obsolete content
the webapp script). this file will be loaded into the prism chrome window very much like a firefox extension is loaded into the browser chrome window. it can contain the following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. re
turning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called plat...
New Skin Notes - Archive of obsolete content
_and_guidelines page) (dria: fix catlinks style) the arrows that appear if you select "enhanced recent changes" in your preferences have an ugly border around them. --nickolay 04:43, 25 aug 2005 (pdt) the radio buttons on history page are jumping in a weird way because the selected row becomes bold. --nickolay 04:46, 25 aug 2005 (pdt) the sidebar overrides content on diff pages --nickolay
turns out this was fixed for 1.5 already. --dria the buttons in the upper-right of the horizontal nav-bar don't really feel like buttons; maybe add a pseudo-class for onhover that gives them an underline? --beltzner the "+" item under the "views" menu of a discussion page looks really out of place. can we replace it with "add section" or something? --beltzner i'll look into it, but i think this ...
Remote debugging - Archive of obsolete content
ould at least know how to run a debugger, if not how to use it, and should have a debug build of firefox handy. this requires quite a bit of trust, in both directions. the developer trusts that his time is not being wasted: the crash is a real bug in firefox. (that is, there's a legitimate reason it happens only on some computers, but that reason just hasn't been discovered.) the crash victim, in
turn, trusts the developer with full access to his computer. a good place to start is a detailed stack (in gdb, use bt followed by bt full). there give more information about the stack than a breakpad crash report: not only the names of the functions on the stack, but also the values they were passed. core dump a core dump includes all of the memory of a crashed program. it allows you to see the cras...
SpiderMonkey coding conventions - Archive of obsolete content
-private and static data use underscores, not intercaps (but library-private data do use a js_ prefix). scalar type names are lowercase and js-prefixed: jsdouble. aggregate type names are js-prefixed and mixed-case: jsobject. macros are generally all_caps and underscored, to call out potential side effects, multiple uses of a formal argument, etc. linkage dll entry points have their re
turn type expanded within a js_public_api() macro call, to get the right windows secret type qualifiers in the right places for all build variants. dll entry points that are not public apis use js_friend_api() instead. ...
open - Archive of obsolete content
sequent methods to examine or modify the file. certain methods of file, such as read and write should not be used when the file is not open. other methods, such as remove may not be used when the file is open. valid file types are text, binary and unicode. text indicates ascii text without nul characters. binary indicates utf-8 files. unicode indicates ucs-2 files. for all file types, carriage re
turns and linefeeds are treated in a platform-agnostic way. examples example: using open in the following example, myfile is a file object: myfile.open("read", "text"); see also ...
Supporting per-window private browsing - Archive of obsolete content
var inprivatebrowsing = components.classes["@mozilla.org/privatebrowsing;1"]. getservice(components.interfaces.nsiprivatebrowsingservice). privatebrowsingenabled; if (!inprivatebrowsing) { ... } } catch(e) { components.utils.reporterror(e); re
turn; } } obtaining an nsiloadcontext for privacy-sensitive apis some apis (such as nsitransferable and nsiwebbrowserpersist) take nsiloadcontext arguments that are used to determine whether they should be classed as private or not (for example, whether the uri being persisted by saveuri should be added to the permanent download history). to do this, import resource://gre/modules/pr...
Table Layout Strategy - Archive of obsolete content
<col width="30%"><col width="60%"><tbody></tbody>foobar <col width="33%"><col><tbody></tbody>foobar <table border width="200px"> <col width="30%"><col width="60%"> <tbody> <tr><td>foo</td><td>bar</td></tr> </tbody> </table> the columns reach here only 90 % percent of the width so the remaining 20px need to be redistributed between the cols. the second table has <col width="33%"><col> lets re
turn to the first case but now but with more than 100%: <col width="40%"><col width="80%"><tbody></tbody>foobar <col width="40%"><col><tbody></tbody>foobar <table border width="200px"> <col width="40%"><col width="80%"> <tbody> <tr><td>foo</td><td>bar</td></tr> </tbody> </table> the algorithm tries to satisfy the requirements on a first come first serve base. the second table has <col width="40...
Actionscript Acceptance Tests - Archive of obsolete content
he same contents that will apply to the entire directory. testname.as.avm_args files will take precedence over the dir.avm_args file testname.as.tz if a test is only valid for certain timezones, the timezones can be specified in this support file. below is a sample file that covers the 4 main us timezones: # place all timezones that this file applies to. # these values correspond to the value re
turned by time.tzname tuple. # (see http://docs.python.org/library/time.html for details) # e.g.: eastern standard time/eastern daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable error. the first line must contain the expected error (without the extr...
Cmdline tests - Archive of obsolete content
vmshell -d test.abc, set breakpoint on a line, show local variable value, quit from cmdutils import * def run(): r=runtestlib() r.run_test( 'debugger locals', '%s -d testdata/debug.abc'%r.avmrd, input='break 53\ncontinue\nnext\ninfo locals\nnext\ninfo locals\nquit\n', expectedout=['local1 = undefined','local2 = 10','local2 = 15'] ) use case 2: test -memstats re
turns memory logs to stdout test contents: start avmshell -memstats test.abc, assert stdout contains 'gross stats', 'sweep m reclaimed n pages.' from cmdutils import * def run(): r=runtestlib() r.run_test(name='memstats', command="%s -memstats testdata/memstats.abc" % r.avm, expectedout=[ 'gross stats', 'man...
Running Tamarin acceptance tests - Archive of obsolete content
b push avmshell /data/local/tamarin/avmshell $ adb shell 'chmod 777 /data/local/tamarin/avmshell' copy android_runner.sh, if it doesn't already exist on the phone in /data/local/tamarin $ adb push tamarin-redux/platform/android/android_runner.sh /data/local/tamarin/android_runner.sh $ adb shell 'chmod 777 /data/loca/android_runner.sh' test it out with a simple .abc or no args for usage (should re
turn exitcode=0) $ tamarin-redux/platform/android/android_shell.py hello.abc hello exitcode=0 test it out by retrieving the version information of the shell on the android device $ $avm -dversion shell 1.4 debug build 6299:455bca954565 features avmsystem_32bit;avmsystem_unaligned_int_access;avmsystem_little_endian;avmsystem_arm;avmsystem_unix; avmfeature_jit;avmfeature_abc_interp;avmfeature_selftest;a...
Tamarin build documentation - Archive of obsolete content
libs to create the necessary 'libcrypto.a' and 'libssl.a' static libraries. alternatively, run make, in which case the process will complete with errors when it tries to create the shared lib crt0.o: $ /android-public/android-ndk/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/../lib/gcc/arm-eabi/4.4.0/../../../../arm-eabi/bin/ld: crt0.o: no such file: no such file or directory collect2: ld re
turned 1 exit status make[2]: *** [link_app.] error 1 make[1]: *** [openssl] error 2 make: *** [build_apps] error 1 you can ignore these errors. the necessary static files 'libcrypto.a' and 'libssl.a' are made correctly and are present in the /openssl folder. more information on why this happens on mac os is here: http://developer.apple.com/library/mac/#qa/qa2001/qa1118.html - create a /frameworks/b...
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
well as the current build against the vm in flash player 10. buildsize flash10576k tc-700740k tc-703655k known issues known failures in the acceptance testsuite include: number failures in testsuite when running on linux windows mobile system.privatebytes and -memstats privatebytes always re
turns 0 amd64 longjmp hack needs reengineering on non-windows platforms different runtime errors when -dforcemir set in acceptance test run arm: math failures running with thumb or arm jit and interp. recursive pcre testcases kills the stack on pocketpc builds ...
The life of an HTML HTTP request - Archive of obsolete content
reates a contentviewer. in most cases (including this) it also creates a nsidocument (nshtmldocument) and binds it to the contentviewer. the contentviewer is then embed():ed into the contentviewercontainer (the webshell). (4) the document then creates a nsiparser for parsing the input stream. for html document this is an nsparser, which also implements nsistreamlistener. this streamlistener is re
turned to the documentloader and connected to the nsichannel of the request. (5) the document (nshtmldocument) also creates a nsicontentsink (nshtmlcontentsink) and connects it to the parser and the document. the parser then parses the stream it gets via its streamlistener interface and converts it to nsiparsernodes which it places in the contentsink. the parser typically gets data from the stream i...
The new nsString class implementation (1999) - Archive of obsolete content
they share a global allocator). note: the com rules imply that everyone needs to use the same allocators, that they acquire via a global com service called cogetmalloc(). our nsstrimpl uses an allocator pattern so that programmers can install their own policy, but this may also make allocation simpler in a multiprocess environment. i'm wondering if this is sufficient, namely, that a string can re
turn it's own (shared) allocator for this purpose. our minimalistic nsimemoryagent interface is just rich enough to support the nsstring idiom, and could be extended to serve as the general memory allocation idiom. here's it's api: class nsimemoryagent : nsisupports { void* new(nsint32 asize)=0; //used for both alloc and realloc void* delete(void* aptr)=0; }; internationalization the new nsstrim...
Treehydra Manual - Archive of obsolete content
alue or state. meet. meet is a relation on abstract values used to filter states at conditional statements. for example, if the current abstract value of a variable x is nonzero, and the analysis goes inside an if statement with the condition x == 1, then in the new abstract value of x will be nonzero meet 1. esp uses a user-defined meet function supplied to the analysis constructor that should re
turn the intersection of two abstract values. it is also acceptable for meet to re
turn a value that contains the intersection--this may cause the analysis to have more false positives but will not introduce false negatives. join. join is a relation on abstract values used to merge states at control flow merge points. for example, if esp reaches a point where two control flow paths merge, and on one si...
Tuning Pageload - Archive of obsolete content
up fully loaded before the delay expires. the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load 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 re
turn 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 pars...
Venkman Internals - Archive of obsolete content
scriptmanager.instances array, in the order that they were loaded. from here, you can set and clear breakpoints in all instances. scriptmanager.transients is a hash of all of the "transient" scripts from this url, where a transient script is something compiled as a the result of an eval, settimeout, or setinterval. try starting up venkman and type "/watch-expr client.scriptmanagers", make sure to
turn on "include functions". this tree should give you a pretty good idea of how it all fits together. ...
Venkman Introduction - Archive of obsolete content
in the interactive session's input field, enter this.fpaused venkman evaluates the expression, giving you [boolean] false back. press step into to follow the steps until you have finished debugging the function, and the fishes have paused. in addition to step in, which will execute a single line of javascript and stop, step over can be used to step over a impending function call, and re
turn control to the debugger when the call re
turns. step out executes until the current function call exits. click the "pause" link again on the fishcam page to resume the demo. this starts the dhtml down the other codepath in start() and makes the fishes start swimming again. as you can see, this is a very modest introduction to the functionality of the javascript debugger and the comple...
Binding Attachment and Detachment - Archive of obsolete content
document.removebinding; these were subsequently discarded as redundant and not implemented. var checkbox = document.getelementbyid("mycheckbox"); checkbox.style.mozbinding = "url(http://www.mozilla.org/xbl/htmlbindings.xml#checkbox)"; this attachment is not necessarily synchronous. scripts that invoke this method should not assume that the binding is installed immediately after this method re
turns. see binding documents for more information. when a binding is attached using the dom, it inherits from the current most derived binding that may already be attached to the element. any bindings attached to an element will remain on the element until the element is destroyed or the corresponding style rule is removed. if a binding is attached and it already specifies an inherited binding using...
Example Sticky Notes - Archive of obsolete content
irtual" property for the bound element. unlike <field> these are really two functions (getter and setter). within the virtual properties you cannot set or get the named property itself. say an attempt to assign this.innertext='something' will lead to circular setter call and stack overflow. --> <getter><![cdata[ var st = this.innerhtml || ''; if (st != '') { var re = /<\/?[^>]+>/gi; re
turn st.replace(re,''); } else { re
turn ''; } ]]></getter> <setter><![cdata[ // "val" in setter contains the assignment value. // here we simply echoing it back: re
turn val; ]]></setter> </property> <method name="setborder"> <!-- new method for the bound element. unlike virtual property it is called in function context: this.setborder(arg) you also may define any amount of named argum...
Creating XPI Installer Modules - Archive of obsolete content
manage either through registration as part of an installation process (as described in this tutorial) or by way of a shortcut file called installed-chrome.txt, in which developers can point at their new contents.rdf files and have them registered as they develop (a process we do not describe here). one way of another, the chrome registry is shown the contents.rdf files; the contents.rdf files in
turn point to new resources, and the resources are then registered with mozilla and accessible to the user. creating a new package the package described in this section is a very simple one, but it uses the new packaging scheme and the chrome registry to make itself a piece of self-contained and redistributable software. once you have created a package like the one described here, mozilla users can do...
File.windowsShortcut - Archive of obsolete content
"1.1.1.1"; initinstall( "windows shortcut", "test", vi, 0); f = getfolder("windows"); g = getfolder("temporary"); addfile( "miscshortcut", "2.2.2.2", xpisrc, f, xpisrc, true); target = getfolder(f, xpisrc); shortcutpath = getfolder("program"); err = file.windowsshortcut( target, shortcutpath, "misc shortcut", g, "", target, 0); logcomment("file.windowsshortcut re
turns: " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
Trigger Scripts and Install Scripts - Archive of obsolete content
nstallations. install scripts use the install, file, installversion and platform-specific installation object methods to initialize, queue, manage, and perform the installation of one or more software packages. these install scripts are typically located at the top level of the xpi archives in which the installations are stored. a trigger script may trigger the downloading of a xpi, which in
turn will use its own install.js script to manage the complete installation. ...
copy - Archive of obsolete content
summary makes a queued copy of the specified file. method of file object syntax int copy( filespecobject source, filespecobject dest ) parameters the copy method has the following parameters: source a filespecobject object reprsenting the file to be copied. dest a filespecobject object representing the destination directory. re
turns an integer error code. for a list of possible values, see re
turn codes. description the destination can be a directory or a filename. if destination does not exist a new file will be created. ...
dirRemove - Archive of obsolete content
s a directory. method of file object syntax int dirremove( filespecobject dirtoremove [, boolean recursive] ); parameters the dirremove method has the following parameters: dirtoremove a filespecobject representing the directory to be removed. recursive an optional boolean value indicating whether the remove operation is to be performed recursively (1) or not (0). re
turns an integer error code. for a list of possible values, see re
turn codes. ...
dirRename - Archive of obsolete content
dirrename renames a directory in place. method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed. newname the new terminal (or leaf) name of the directory. re
turns an integer error code. for a list of possible values, see re
turn codes. ...
execute - Archive of obsolete content
ct syntax int execute ( filespecobject executablefile, [string aparameters] ); parameters the execute method has the following parameters: executablefile a filespecobject representing the local file already on disk to be executed. note that file names are case sensitive. aparameters an optional parameter string that is passed to the executable. (ignored on mac os) re
turns an integer error code. for a list of possible values, see re
turn codes. description the specified file is not actually executed until the performinstall method is called. see performinstall for more information about queued commands during the installation process. example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be ...
exists - Archive of obsolete content
exists re
turns a value indicating whether the specified file or directory exists. method of file object syntax boolean exists( filespecobject target ) parameters the exists method has the following parameters: target a filespecobject representing the file or directory being tested for existence. re
turns a boolean value specifying whether the file or directory does indeed exist or does not. example f = getfolder( "program", "sample.txt" ); if ( file.exists(f) ) // do something with the file ...
isDirectory - Archive of obsolete content
summary re
turns a boolean value indicating whether the specified filespecobject is a directory. method of file object syntax boolean isdirectory ( filespecobject nativefolderpath ); parameters the isdirectory method has the following parameters: nativefolderpath a filespecobject representing the queried directory. re
turns a boolean value indicating whether the object is a directory or not. ...
isFile - Archive of obsolete content
summary re
turns a boolean value indicating whether the given filespecobject is a file. method of file object syntax boolean isfile (filespecobject nativefolderpath); parameters the isfile method has the following parameter: nativefolderpath a filespecobject representing the queried file object. re
turns a boolean value indicating whether the filespecobject is a file or not. example f = getfolder( "program", "sample.txt" ); if ( file.isfile(f) ) // the object represents a file ...
macAlias - Archive of obsolete content
a filespecobject that represents the directory into which the program file will be installed. filename a string representing the name of the file to be installed. aliasdir a filespecobject that represents the directory into which the alias file will be installed (e.g.,"mac desktop"). aliasname a string representing the name of the alias itself. re
turns an integer error code. for a list of possible values, see re
turn codes. example see file.macalias in the script examples chapter. ...
move - Archive of obsolete content
move moves a file from one location to another. method of file object syntax int move( filespecobject source, filespecobject dest ); parameters the move method has the following parameters: source a filespecobject representing the source file. dest a filespecobject representing the target directory. re
turns an integer error code. for a list of possible values, see re
turn codes. description you must create a filespecobject for the destination directory to pass in for this function. if the destination doesn't already exist a file name for the destination is assumed. example source = getfolder("program", "file.txt"); dest = getfolder("chrome"); err = file.move(source, dest); ...
remove - Archive of obsolete content
summary deletes a specified file. method of file object syntax int remove( filespecobject file ) parameters the remove method has the following parameters: file a filespecobject representing the file to be removed. re
turns an integer error code. for a list of possible values, see re
turn codes. ...
rename - Archive of obsolete content
summary renames a specified file in place. method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed. newname the new terminal (or leaf) name of the file. re
turns an integer error code. for a list of possible values, see re
turn codes. ...
size - Archive of obsolete content
summary re
turn the size of the given file in bytes. method of file object syntax int size (string nativefolderpath); parameters the size method has the following parameters: nativefolderpath the full pathname to the file. re
turns a number representing the size, in bytes, of the queried file. ...
windowsGetShortName - Archive of obsolete content
summary re
turns a path that conforms to the windows 8.3 file naming convention. method of file object syntax string windowsgetshortname( object localdirspec ) parameters the windowsregisterserver method has the following parameter: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. re
turns a string with the windows shortname. if the path already conforms to 8.3, the re
turn value is null. example flongfilepath = getfolder(fprogram, "longfilename.file"); sshortfilepath = file.windowsgetshortname(flongfilepath); if(sshortfilepath) { // do something } ...
windowsRegisterServer - Archive of obsolete content
summary windowsregisterserver registers installed dlls with the windows registry. method of file object syntax int windowsregisterserver( object localdirspec ) parameters the windowsregisterserver method has the following parameters: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. re
turns an integer error code. for a list of possible values, see re
turn codes. example filecdtool = getfolder("file:///", faod + "cdtool.dll"); err = file.windowsregisterserver(filecdtool); ...
windowsShortcut - Archive of obsolete content
h to the working dir for where atarget will is to be run from. aparams parameters that atarget requires. aicon a filespecobject representing the absolute path (including fiilename) to a file that contains icons. can be either .ico, .dll, .exe, or any other binary file that contains icons. aiconid index of the icon from aicon to use for this shortcut. re
turns an integer error code. for a list of possible values, see re
turn codes. example see file.windowsshortcut in the script examples chapter. ...
toString - Archive of obsolete content
summary converts an installversion init object to a string. method of installversion object syntax string version = installversion.tostring ( initobj ); parameters the tostring method has the following parameter: initobj initobj is an installversion object whose init method has been called. re
turns the major, minor, revision, and build numbers represented as a single string. the init() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. to get the version number out of an installversion object in order to compare it with other versions, you can call tostring() and get back the version as a string in the format "maj.min.rev.bld." example var vi = new installversion(); vi.in...
addDirectory - Archive of obsolete content
ing representing the directory to the getfolder method. subdir the name of a directory to append to localdirspec, using '/' as the path separator regardless of the platform.if subdir is missing, null, or "", the filenames are appended directly to the folder name specified by localdirspec. flags an optional field; reserved for future use. pass 0 as the default value. re
turns an integer error code. for a list of possible values, see re
turn codes. in some situations, adddirectory may re
turn other errors. description the adddirectory method puts the files in the specified directory in a temporary location. to move the files and all other subcomponents to their final location, call the performinstall method after you've successfully added all subcomponents. also see th...
addFile - Archive of obsolete content
h a pathname relative to the localdirspec parameter. the file is installed in this location on the user's machine. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. flags an optional field; reserved for future use. pass 0 as the default value. re
turns an integer error code. for a list of possible values, see re
turn codes. description the addfile method puts the file in a temporary location. to move this and all other files to their final location, call the performinstall method after you've successfully added all files. note: if you are installing binary files on a macintosh, be aware that the binary format for those files must be applesing...
cancelInstall - Archive of obsolete content
summary aborts installation of the software; performs cleanup of temporary files. method of install object syntax void cancelinstall() void cancelinstall( int errorcode ) parameters none. re
turns an integer error code. the optional argument is an error code that can be re
turned to the triggering page. for most purposes, it's recommended that one of the standard re
turn codes be used. but a script can, in fact, re
turn any valid integer. for a list of possible values, and any custom errorcode created by install writer, see re
turn codes. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... err = getlasterror(); if (!err) perf...
deleteRegisteredFile - Archive of obsolete content
zilla do not currently support this method.) deletes the specified file and removes its entry from the client version registry. method of install object syntax int deleteregisteredfile (string registryname); parameters the deleteregisteredfile method has the following parameter: registryname the pathname in the client version registry for the file that is to be deleted. re
turns an integer error code. for a list of possible values, see re
turn codes. description the deleteregisteredfile method deletes the specified file and removes the file's entry from the client version registry. if the file is currently being used, the name of the file that is to be deleted is saved and netscape 6 attempts to delete it each time it starts up until the file is successfully deleted. th...
execute - Archive of obsolete content
itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. re
turns an integer error code. for a list of possible values, see re
turn codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to actually execute the file. you can use this method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: ...
gestalt - Archive of obsolete content
gestalt (macintosh only) retrieves information about the operating environment. method of install object syntax int gestalt ( string selector ); parameters the gestalt method takes the following parameters: selector the selector code for the information you want. re
turns re
turns the requested information. the format depends on the select code specified in the selector parameter. description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. for information on that function, see inside macintosh: operating system utilities. this method re
turns null on unix and windows platforms. ...
getLastError - Archive of obsolete content
getlasterror re
turns the most recent nonzero error code. method of install object syntax int getlasterror (); parameters none. re
turns the most recent nonzero error code. for a list of possible values, see re
turn codes. description use getlasterror method to obtain the most recent nonzero error code since initinstall or reseterror were called. this method allows you to defer checking for error codes each time you call addfile or adddirectory until the last addfile or adddirectory call. the getlasterror method does not re
turn errors from methods that re
turn objects, such as getfolder. example the following example calls getlasterror after a series of addfile calls: addfile("npplug", ...); addfile("/ms/shared/ctl3d.dll", ...); addfile("/nethelp/royalplug/royalhelp.html",...); err = get...
getWinProfile - Archive of obsolete content
object folder, string file); parameters the getwinprofile method has the following parameters: folder an object representing a directory. you create this object by passing a string representing the directory to the getfolder method. file a relative pathname to an initialization file in the directory specified by the folder parameter, such as "royal/royal.ini". re
turns a winprofile object. description the getwinprofile method creates an object for manipulating the contents of a windows .ini file. once you have this object, you can call its methods to retrieve strings from the file or to add strings to the file. for information on the re
turned object, see winprofile. this method re
turns null on unix and macintosh platforms. example to edit the win.ini file, you...
getWinRegistry - Archive of obsolete content
getwinregistry (windows only) constructs an object for working with the windows registry. method of install syntax winreg getwinregistry(); parameters none. re
turns a winreg object. description use the getwinregistry method to create an object for manipulating the contents of the windows registry. once you have this object, you can call its methods to retrieve or change the registry's content. for information on the re
turned object, see winreg. this method re
turns null on unix and macintosh platforms. ...
initInstall - Archive of obsolete content
distinction is important when you add components with the addfile method. version an installversion object or a string representing the version of the package being installed. when version is a string it should be up to four integer values delimited by periods, such as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. re
turns an integer error code. for a list of possible values, see re
turn codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it fin...
loadResources - Archive of obsolete content
loadresources loads a properties file. method of install object syntax object loadresources( string xpipath ); parameters the sole input parameter for loadresources is a string representing the path to the properties file in the xpi in which the key/value pairs are defined. re
turns a javascript object whose property names are the keys from that file and whose values are the strings. description the format of the properties file expected by loadresources is the same as that of the chrome locale .properties files. this method is used to internationalize installation scripts by allowing the installer to retrieve localized string values from a separate file. be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates. exa...
logComment - Archive of obsolete content
logcomment adds a comment line to the installation log. method of install object syntax int logcomment( string acomment ); parameters the sole input parameter is a string whose value will be written to the log during the installation process. re
turns an integer error code. for a list of possible values, see re
turn codes. description the install log is created in the product directory by default (where the browser executable is) if it can be, and if the installation doesn't have proper permission, the install log is written to the user's profile directory. respectively, these directories correspond to the "program" and "current user" keywords for the getfolder method. ...
refreshPlugins - Archive of obsolete content
refreshplugins refreshes the list of plug-ins registered for the browser. method of install object syntax int refreshplugins( [ areloadpages ] ); parameters the refreshplugins method has the following parameter: areloadpages areloadpages is an optional boolean value indicating whether you want to reload the open web pages after you have refreshed the plug-in list. re
turns nothing. description refreshplugins lets you register new plug-ins without having to restart the browser. when you use this method in an installation script, as the example below demonstrates, you can install new plug-ins and use them to display the requested media in a web page without interrupting the experience of the user. note that refreshplugins must be called after the performinstall method tha...
registerChrome - Archive of obsolete content
nstallation. filespecobjects like that required by this function are created using the getfolder method on the install object. xpipath xpipath is the path within the xpi in where the contents.rdf file defining the chrome is located. for example, "locale/mylocale/aim," points to the locale/mylocale/aim subdirectory of the same xpi file in which the installation script is located. re
turns an integer error code. for a list of possible values, see re
turn codes. in some situations the method may re
turn other errors. in a few cases you may get a registry error. description when the third parameter is omitted (pointing to a specific location within the xpi file), this function is being used in a somewhat deprecated way. in this case, registerchrome is supporting the old format of ins...
setPackageFolder - Archive of obsolete content
setpackagefolder sets the default package folder. method of install object syntax void setpackagefolder ( object folder); parameters the setpackagefolder method has the following parameter: folder an object representing a directory. you create this object by passing a string representing the directory to the getfolder or getcomponentfolder method. re
turns none. description the setpackagefolder method to set the default package folder that is saved with the root node. when the package folder is set, it is used as the default for forms of addfile and other methods that have an optional localdirspec parameter. you should only call this method once, and you should always call it immediately after you call initinstall. if you call setpackagefolder multiple times, the las...
Install Object - Archive of obsolete content
nstall with the name of the installation and the necessary registry and version information. add the files to the installation add files to the installation by calling getfolder to get file objects and passing those object refs to addfile as many times as necessary. perform installation check that the files have been added successfully (e.g., by checking the error re
turn codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples. ...
getString - Archive of obsolete content
getstring retrieves a value from a .ini file. method of winprofile object syntax string getstring ( string section, string key); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers". key the key in that section whose value to re
turn. re
turns the value of the key or an empty string if none was found. description the getstring method is similar to the windows api function getprivateprofilestring. unlike that function, this method does not support using a null key to re
turn a list of keys in a section. example to get the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); var wallpapervalue = ini.getstring ("deskt...
writeString - Archive of obsolete content
summary changes a value in a .ini file. method of winprofile object syntax boolean writestring ( string section, string key, string value); parameters the method has the following parameters: section section in the file, such as "boot" or "drivers". key the key in that section whose value to change. value the new value. re
turns true if successfully scheduled, otherwise, false. description the writestring method is similar to the windows api function writeprivateprofilestring. to delete an existing value, supply null as the value parameter. unlike the writeprivateprofilestring function, this method does not support using a null key to delete an entire section. values are not actually written until performinstall is called. example to s...
createKey - Archive of obsolete content
ntax int createkey ( string subkey, string classname); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". classname usually an empty string. for information on this parameter, see the description of regcreatekeyex in your windows api documentation. re
turns 0 if it succeeded; a nonzero number if it failed to schedule the creation. for a list of possible values, see re
turn codes. description the createkey method adds a key to the registry. you must add a key to the registry before you can add a value for that key. ...
deleteKey - Archive of obsolete content
deletekey removes a key from the registry. method of winreg object syntax int deletekey ( string subkey); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". re
turns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. for a list of possible values, see re
turn codes. ...
deleteValue - Archive of obsolete content
removes the value of an arbitrary key. method of winreg object syntax int deletevalue ( string subkey, string valname); parameters the deletevalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair you want to remove. re
turns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. ...
enumKeys - Archive of obsolete content
ry subkeys for the given key. method of winreg object syntax string enumkeys ( string key, int subkeyindex ); parameters the enumkeys method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". subkeyindex an integer representing the 0-based index of the subkey being sought. re
turns the name if it succeeded; null if the referenced value does not exist. description enumkeys can be used to iterate through the subkeys at a given key location. the following example shows how to use enumkeys to find the plugins subdirectory below the various mozilla-based browser installations. var winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_local_machine); var index = 0; var baseke...
enumValueNames - Archive of obsolete content
f a given key. method of winreg object syntax string enumvaluenames ( string key, int subkeyindex ); parameters the enumvaluenames method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". subkeyindex an integer representing the 0-based index of the key value being sought. re
turns the value of the key as a string if it succeeded; null if the referenced subkey does not exist. description enumvaluenames can be used to iterate through the values for a given key. the following brief example retrieves a key value using this method. var winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_local_machine); v1 = winreg.enumvaluenames("software\\mozilla\\", 0); logcomment("the ...
getValue - Archive of obsolete content
ves the value of an arbitrary key. method of winreg object syntax winregvalue getvalue ( string subkey, string valname); parameters the getvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. re
turns a winregvalue object representing the value of the named value-name/value pair or null if there is no value or if there is an error. see winregvalue for information about these values. description the getvalue method retrieves the value of an arbitraty key. use this method if the value you want is not a string. if the value is a string, the getvaluestring method is more convenient. ...
getValueNumber - Archive of obsolete content
hen that value is a number. method of winreg object syntax number getvaluenumber ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. re
turns number value of the specified key or null if there's an error, the value is not found, or the value is not a string. ...
getValueString - Archive of obsolete content
hen that value is a string. method of winreg object syntax string getvaluestring ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want. re
turns a string representing the value of the named value-name/value pair or null if there's an error, the value is not found, or the value is not a string. description the getvaluestring method gets the value of a string. if the value is not a string, use the getvalue method instead. ...
setRootKey - Archive of obsolete content
description the setrootkey changes the root key. when you create a winreg object, it is set to access keys under the hkey_classes_root portion of the registry. if you want to access keys in another portion, you must use this method to change the root key. ...
setValue - Archive of obsolete content
lue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a winregvalue object representing the new non-string value. see winregvalue for information about these values. re
turns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see re
turn codes. description the setvalue method sets the value of an arbitrary key. use this method if the value you want to set is not a string. if the value is a string, the setvaluestring method is more convenient. ...
setValueNumber - Archive of obsolete content
mber ( string subkey, string valname, number value ); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a number representing the new string value. re
turns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see re
turn codes. description the setvaluenumber method sets the value of a key when that value is a number. use this method if the value you want to set is a number. if the value is not a number, use the setvalue or setvaluestring methods instead. ...
setValueString - Archive of obsolete content
ect syntax int setvaluestring ( string subkey, string valname, string value); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value the new string value. re
turns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see re
turn codes. description the setvaluestring method sets the value of a key when that value is a string. use this method if the value you want to set is a string. if the value is not a string, use the setvalue method instead. ...
WinRegValue - Archive of obsolete content
little_endian = 4 winregvalue.reg_dword_big_endian = 5 winregvalue.reg_link = 6 winregvalue.reg_multi_sz = 7 winregvalue.reg_resource_list = 8 winregvalue.reg_full_resource_descriptor = 9 winregvalue.reg_resource_requirements_list = 10 regdata a java byte array containing the data. re
turns a new winregvalue object, with the data members type and data set to the values passed to this constructor. description advanced windows developers can use this object to manipulate non-string values for the windows registry. an object of this type has two fields: the type of the data and the value. for information on the possible data types for a registry value, see your windows api documentati...
XPInstall API reference - Archive of obsolete content
no properties methods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueexists winregvalue constructor other information re
turn codes see complete list examples trigger scripts and install scripts code samples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install ...
XPJS Components Proposal - Archive of obsolete content
omponent manager will load up the xpjsmanager's module and call the native nsgetfactory it finds there. that native nsgetfactory function will check the information it stored in the registry to see that the js factory for the given clsid is in a given .js file. it will load that .js file (if not already loaded) and call the nsgetfactory function. our friend xpconnect will convert the js object re
turned from the js module's nsgetfactory function into an xpcom object. the component manager (and anyone else with a reference to that factory) can then call the factory's createinstance method at will. the js module is free to implement factories and components and services that the factories construct on command. any code anywhere and implemented in any language can get to these things via the com...
A XUL Bestiary - Archive of obsolete content
ntent/ default/ navigator.xul ... skin/ default/ navigator.css nav-icon.gif ... mynewskin/ newskin.css newgifs.gif ... locale/ us-en/ navigator.dtd to load chrome information stored in a new package directory like this, you can use the following chrome url, chrome://navigator/skin/mynewskin/newskin.css which in
turn loads the graphics in that subdirectory as needed. skin the skin is the css and graphics that makes up the look or presentation of xul. xul itself contains very little provision for how widgets are to be presented in the interface. even prior to the skinning that takes place with the global skin, which is loaded in almost every xul file you see in mozilla (and whose absence from your own xul fi...
textbox.label - Archive of obsolete content
« xul reference label type: string sets the label attribute. gets the label attribute if it is present and not empty. otherwise it re
turns the value of the associated label element, if applicable. otherwise it re
turns the placeholder or emptytext property. the getter is mostly useful for screen readers. note: prior to firefox 3, and always in thunderbird and seamonkey, the label property of an autocomplete textbox re
turns its value, for compatibility with the menulist element. ...
uri - Archive of obsolete content
« xul reference uri type: ? used to specify the variable name for the content. when a rule is evaluated, it scans through each resource in the rdf datasource looking for a match. each resource is placed in the variable specified in the uri attribute in
turn. then, the other rules are evaluated for a match. this attribute should always be present. ...
Actions - Archive of obsolete content
the query is defined. this action contains only one element, but you can put as many or as few elements as you need. in this case, a button will be created for each result. there are three results, so three buttons will be created. here is the [example], and an image of what it looks like: the template builder iterates through the three results, processing the body of the action for each one in
turn. the uri attribute on the button is used to specify the ending or member variable. in this example, there's only one variable to use, ?relateditem, since ?start is the starting point and the start and end points cannot be the same. there are a number of things that will happen for each result. let's look at the results again: (?start = http://www.xulplanet.com/rdf/a, ?relateditem = http://www.xul...
Building Trees - Archive of obsolete content
ributes to determine what to display. the tree builder implements the nsitreeview interface, so it becomes the tree’s view—in other words, the tree’s view and the tree’s builder are the same object. when the tree is displayed, it asks the view for the contents of each cell. the builder looks at the label for the corresponding cell, translates any variables or predicates into values, and re
turns the value. in the example above, the first cell should display the title. the builder doesn’t compute any labels until the view asks for them. when the view requests a label for the first cell, the builder looks up the ‘http://purl.org/dc/elements/1.1/title’ predicate for the row in question and re
turns it. the content builder generates content in the template body and substitutes data fro...
Static Content - Archive of obsolete content
ith recursive content and multiple rules. what's going on here is that the xul parser first creates the outer menulist element. the static content outside the template will also be created. the result will be a xul display that looks just like the code above, except that the template and its content is hidden. at this point, the menulist will have a menupopup as a child, and the menupopup will in
turn have one menuitem child. next, the template is examined and two results are generated. remember that only the content at the uri attribute or below inside the action are copied for each result. when processing the action body, the builder looks at the first element inside the action, in this case, the menupopup. this element doesn't have a uri attribute, so the builder knows that this element sho...
Template Logging - Archive of obsolete content
fortunately, some debugging and logging support is provided with templates that may help. logging template results there are two main ways in which template errors may be detected. ...
Using Recursive Templates - Archive of obsolete content
lts. the output for groups is a groupbox with a caption containing the name. the output for non-groups is a label. you could further expand this process for other levels. disabling recursion the recursion on a template occurs automatically. in fact, it has occured with all of the examples so far. however, in most cases, there either aren't any children or the next iteration of the query doesn't re
turn any results, so no output is generated. sometimes, you will not want a template generate recursive content. you can do this by adding a flag. <vbox datasources="people.xml" ref="*" querytype="xml" flags="dont-recurse"> here, the flags attribute is set to dont-recurse. this disables the recursion and only generates one level of results. « previousnext » ...
XML Assignments - Archive of obsolete content
« previousnext » sometimes, you will want to use a more complex substitution apart from just taking an attribute from the xml. for instance, you might want to display not the name of a person, but the length of their name. xpath provides syntax to retrieve this using the built-in string-length method. however, you cannot use a expression that re
turns a number in the query, as the query must re
turn dom nodes as results. in this case, we use an expression that re
turns the nodes as in earlier examples, and use some additional syntax of the query to get the length of the names. to do this, we use an additional element, the assign element. this element allows the use of additional xpath expressions to get more data from the xml data. here is an example: <vbox datasources="people.xm...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
ls – web development – javascript console. copy the following code. it is one very long line ending in path—make sure that you get all of it: components.classes["@mozilla.org/file/directory_service;1"].getservice( components.interfaces.nsiproperties).get("achrom", components.interfaces.nsifile).path in the javascript console window, paste the code in the field near the top. presss the re
turn or enter key, or the evaluate button. the console displays the location of seamonkey's chrome directory. explanation: the chrome directory contains program files that are part of seamonkey itself, together with other files that are provided by extensions. your toolbar button will be an extension. 2. delete these two files: chrome.rdf overlays.rdf explanation: ...
Adding Event Handlers - Archive of obsolete content
ttach an event listener dynamically and listen for events during the capturing phase. the syntax is as follows: example 3 : source view <button id="okbutton" label="ok"/> <script> function buttonpressed(event){ alert('button was pressed!'); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command', buttonpressed, true); </script> the getelementbyid() function re
turns the element with a given id, in this case the button. the addeventlistener() function is called to add a new capturing event listener. the first argument is the name of the event to listen to. the second argument is the event listener function which will be called when the event occurs. finally, the last argument should be true for capturing listeners. you can also listen during the bubbling pha...
Advanced Rules - Archive of obsolete content
t.com/rdf/weather/cities'. if you look at the rdf above, the 'http://www.xulplanet.com/rdf/weather/cities' resource has four children, one for each different city. the template builder iterates through each one, matching the child against the value of the child attribute. in this case, it is just set to the variable 'city'. so the builder will set the 'city' variable to the each child resource in
turn. because there are no more conditions, the condition matches for each of those four resources and the builder will generate content for each of the four. of course, the example above doesn't have any content. we'll add that later. triple element the next element is the triple element. it is used to check for the existence of a given triple (or assertion) in the rdf datasource. a triple is like a ...
Anonymous Content - Archive of obsolete content
it through a script in the normal way. to the xul, it's as if there was only one single element, even though it is really made up of a number of elements. if you look at a scroll bar in a mozilla window, you will see that it is made up of an arrow button, a slider, a thumb inside it and a second arrow button at the end, which are the elements that appear in the xbl above. these elements would in
turn be bound to other bindings that use the base xul elements. notice that the content elements need the xul namespace (they appear preceded with xul:), because they are xul elements and aren't valid in xbl. this namespace was declared on the bindings tag. if you don't use the namespace on xul elements, mozilla will assume that the elements are xbl, not understand them, and your elements won't work c...
Creating a Window - Archive of obsolete content
.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the error console. choose tools – error console, type a line of javascript, and press the evaluate button, or the re
turn or enter key. the findfile.xul example let's begin by creating the basic file for the find file dialog. create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section). add the xul template shown at the top of this page to the file and save it. you can use the command-line parameter '-chrome' to specify the ...
Features of a Window - Archive of obsolete content
cond xul file with the window code in it. as in html, you can use the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() function to open the second window. this function will re
turn a reference to the newly opened window. you can use this reference to call functions of the other window. the open function takes three arguments. the first is the url of the file you wish to open. the second is an internal name of the window. the third is a list of display flags. the flag 'chrome' is important to open the window as a chrome file. if you do not add the 'chrome' flag, the file wi...
Focus and Selection - Archive of obsolete content
you can use a special style property -moz-user-focus. this property controls whether an element can be focused. for instance, you could make a label focusable, as in the example below. example 4 : source view <label id="focused" style="-moz-user-focus: normal;" onkeypress="alert('label focused');" value="focus me"/> the style property is set to normal. you can also set it to ignore to
turn off the focus for an element. this shouldn't be used for disabling an element, however; the disabled attribute or property should be used instead, since that is what it is designed for. once the label in the example is focused, it can respond to key presses. naturally, the label gives no indication that it is focused, since it isn't normally expected to ever be focused. changing the focus there a...
Grids - Archive of obsolete content
lex="1"/> </row> <row> <label control="docpath" value="path:"/> <hbox flex="1"> <textbox id="docpath" flex="1"/> <button label="browse..."/> </hbox> </row> </rows> </grid> notice in the image how the first column of elements containing the labels has only a single element in each row. the second column contains a box in its second row, which in
turn contains two elements, a textbox and a button. you could add additional nested boxes or even another grid inside a single cell. if you resize the window of the last example, you will see that the textboxes resize, but no other elements do. this is because of the flex attributes added to the textboxes and the second column. the first column does not need to be flexible as the labels do not need t...
Input Controls - Archive of obsolete content
the check box. for radio buttons, you should use the selected attribute instead of the checked attribute. set it to true to have a radio button selected by default, or leave it out for other radio buttons. radiogroup element in order to group radio buttons together, you need to use the radiogroup element. only one of the radio buttons in a radio group can be selected at once. clicking one will
turn off all of the others in the same group. the following example demonstrates this. example 3 : source view <radiogroup> <radio id="orange" label="orange"/> <radio id="violet" selected="true" label="violet"/> <radio id="yellow" label="yellow"/> </radiogroup> attributes like buttons, check boxes and radio buttons are made up of a label and an image, where the image switches between checke...
Keyboard Shortcuts - Archive of obsolete content
or the function keys). the key attribute can only be used for printable characters. another attribute, keycode can be used for non-printable characters. the keycode attribute should be set to a special code which represents the key you want. a table of the keys is listed below. not all of the keys are available on all keyboards. ...
More Event Handlers - Archive of obsolete content
popup will not be displayed. the default action can be prevented with the event object's preventdefault method, as in the example below. example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just re
turn false from the code. note that preventing the default action is not the same as stopping event propagation with the stoppropagation method. even if the default action has been prevented, the event will still continue to propagate. similarly, calling the stoppropagation method won't prevent the default action. you must call both methods to stop both from occuring. note that once propagation or the...
Progress Meters - Archive of obsolete content
let's add a progress meter to our find file dialog. we would normally put an indeterminate progress meter as we don't know how many files we'll be searching or how long the search will take. however, we'll add a normal one for now as an animating one can be distracting during development. the progress meter would normally only appear while the search is taking place. we'll add a script later to
turn it on and off. <textbox id="find-text"/> <html:progress value="50" max="100" style="margin: 4px;"/> <button id="find-button" label="find" default="true"/> the value has been set to 50% so that we can see the meter on the window. a margin has been set to 4 pixels so that it is separated from the edge of the window. as was stated earlier, we only want the progress bar to be displayed while the...
The Chrome URL - Archive of obsolete content
advantage over other url types is that they automatically handle multiple themes and locales. for example, a chrome url lets you refer to a file in the theme such as an image without needing to know which theme the user is using. as long as the filenames are the same in each theme, you can refer to the file using a chrome url. mozilla will take care of determining where the file is located and re
turn the right data. this also means that it doesn't matter where the package is installed to be able to access it. the chrome urls are independent of where the files might physically be located. this makes it much easier to write applications that have lots of files since you don't have to worry about the details of locating files. the basic syntax of a chrome url is as follows: chrome://<package nam...
Using nsIXULAppInfo - Archive of obsolete content
= components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo).id; } else { try { id = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefbranch) .getcharpref("app.id"); } catch(e) { // very old version dump(e); } } re
turn id; } alert(getappid()); see also mxr: nsixulappinfo.idl ...
Using spell checking in XUL - Archive of obsolete content
dd spell checking capabilities to your firefox extension. see controlling spell checking in html forms for details on adding spell check support to html forms for your website. checking the spelling of a word to check the spelling of a word, you must first create an interface to the mozispellcheckingengine component and then call the check() method on the string you wish to test. this method re
turns true if the word is correctly spelled, or false if it's not. you may also want to check to see if the word is in the user's personal dictionary, since sometimes a word might be correctly spelled but in the dictionary. // different versions of firefox have different contract ids var spellclass = "@mozilla.org/spellchecker/myspell;1"; if ("@mozilla.org/spellchecker/hunspell;1" in components.clas...
XUL Parser in Python/source - Archive of obsolete content
source code for the xul parser in python. import sys, glob, xmllib import os, re el_list = {} w = open('res.html', 'w') # unfortunately, i had to put this hack in here to suppress the printing out of the resolved namespace: # "xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc. ...
XULBrowserWindow - Archive of obsolete content
r about:addons and any other pages in the in content whitelist. you can augment the functionality of this method using chaining in order to hide chrome for other locations. see hiding browser chrome for details and an example. boolean hidechromeforlocation( in string alocation ); parameters alocation the url to check to see if chrome should be hidden while that location is displayed. re
turn value true if chrome should be hidden while displaying the specified location; otherwise false. ...
XUL controls - Archive of obsolete content
formed when the main part of the button is pressed. <button type="menu-button" label="new"> <menupopup> <menuitem label="new document"/> <menuitem label="new image"/> </menupopup> </button> more information about this type of menu button element. button reference related elements: menupopup menuitem <checkbox> a control that may be
turned on and off, typically used to create options which may be enabled or disabled. <checkbox label="show toolbar labels" checked="true"/> more information about the checkbox element. checkbox reference <colorpicker> a control that may be used to select a color. <colorpicker color="#ff0000"/> colorpicker reference ...
checkbox - Archive of obsolete content
this is most commonly rendered as a box when the element is off and a box with a check when the element is on. the user can switch the state of the check box by selecting it with the mouse. a label, specified with the label attribute, may be added beside the check box. more information is available in the xul tutorial. ...
content - Archive of obsolete content
l not match because they are directly inside a treeitem. this attribute is useful to provide different rules for outer and inner elements. uri type: ? used to specify the variable name for the content. when a rule is evaluated, it scans through each resource in the rdf datasource looking for a match. each resource is placed in the variable specified in the uri attribute in
turn. then, the other rules are evaluated for a match. this attribute should always be present. métodos inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsb...
listitem - Archive of obsolete content
he contents, as visible to the user, are read and set using the menulist.value syntax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. properties accesskey type: character gets and sets the value of the accesskey attribute. accessible type: nsiaccessible re
turns the accessibility object for the element. checked type: boolean gets and sets the value of the checked attribute. control type: element id gets and sets the value of the control attribute. crop type: string gets and sets the value of the crop attribute. current type: boolean gets and sets the value of the current attribu...
query - Archive of obsolete content
s, the query should contain one content element as well as member and/or triple elements. for xml datasources, the query should have an expr attribute and may optionally contain assign elements. for sql datasources, the query should contain an sql statement as text. attributes expr examples (example needed) attributes expr type: string for xml queries, an xpath expression which re
turns results. any namespace prefixes declared on the element may be used within the expression. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, mi...
richlistitem - Archive of obsolete content
data() (future-proof and clean, but not easily serializable). for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. properties accessible type: nsiaccessible re
turns the accessibility object for the element. control type: element id gets and sets the value of the control attribute. disabled type: boolean gets and sets the value of the disabled attribute. label type: string gets the concatentation of text from any child label elements. does not support setting label values. use the child elements direct...
scale - Archive of obsolete content
insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata decrease() re
turn type: no re
turn value decreases the value of the scale or number box by the increment. decreasepage() re
turn type: no re
turn value decreases the value of the scale by the pageincrement. increase() re
turn type: no re
turn value increases the value of the scale or number box by the increment. increasepage() re
turn type: no re
turn v...
tabbox - Archive of obsolete content
e node where keyboard navigation events listener is set up. the initial value for this property is determined by the value of the eventnode attribute. handlectrlpageupdown type: boolean gets and sets the value of the handlectrlpageupdown attribute. handlectrltab type: boolean gets and sets the value of the handlectrltab attibute. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel within a <tabbox> element. assigning a value to this property will modify the selected panel. a select even...
tabpanels - Archive of obsolete content
tafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible re
turns the accessibility object for the element. selectedindex type: integer re
turns the index of the currently selected item. you may select an item by assigning its index to this property. by assigning -1 to this property, all items will be deselected. re
turns -1 if no items are selected selectedpanel type: element holds a reference to the currently selected panel withi...
toolbargrippy - Archive of obsolete content
inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style,...
Application Update - Archive of obsolete content
we use a separate boolean toggle for this to make // the ui easier to construct. pref("app.update.auto", true); // defines how the application update service notifies the user about updates: // // aum set to: minor releases: major releases: // 0 download no prompt download no prompt // 1 ...
Deploying XULRunner - Archive of obsolete content
app could be installed to the registered xulrunner and appear in start menus, lists of installed programs, etc. (bonus points for checking the operating system and downloading the right xulrunner on the fly, or bundling them into your installer). registration and app installation are performed with command line switches as outlined in the xulrunner section of article command line options. it may
turn out to be easier to create a self contained portable application, as described here, and deploy it with a generic installer that would create shortcuts to scripts that launch your application in the unregistered bundled xulrunner. the responsibility still lies with the developer to provide the correct version of xulrunner per platform. in the end, most users are afraid of links that don't have a ...
XULRunner Hall of Fame - Archive of obsolete content
ps://github.com/matthewkastor/xulrunner-examples/ exch a currency conversion tool using updated data from http://finance.yahoo.com/currency. you can use the firefox extension or the stand-alone xul application. opendocument viewer cross-platform viewer for opendocument files. taskpool taskpool is a little application to help keep track of time. you can add tasks to a pool,
turn them on and off, and it will tick off seconds. svgclock an svg-based clock. crowbar a web scraping environment based on the use of a server-side headless mozilla-based browser. 30b a xulrunner-based wrapper for 30boxes.com xul explorer "a lightweight xul ide... an easy way to experiment with xul" xulexplorer a patched version of xul explorer to re-enable ap...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
nents (specifically alpha-transparency) creating a high cpu load on os/2. title case capitalization rules in firefox discussion regarding rules for capitalizing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas
turn into great products. mozilla is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 dis...
2006-10-06 - Archive of obsolete content
nents (specifically alpha-transparency) creating a high cpu load on os/2. title case capitalization rules in firefox discussion regarding rules for capitalizing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas
turn into great products. mozilla is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 dis...
NPN_GetURL - Archive of obsolete content
instance window. the default is _self, if the plug-in instance's document is already at the top. use for breaking out of a deep frame nesting. if the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the mime type of the url. in general, if a url works in the location box of the browser, it works here, except for the _self target. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description npn_geturl() is used to load a url into the current window or another target or stream. plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the networ...
NPN_GetValueForURL - Archive of obsolete content
retrieved (npnurlvcookie or npnurlvproxy) url the url for which to fetch information. value out parameter. the browser passes back the requested information. if the function succeeds, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the value may have internal null bytes and may not be null-terminated. when multiple cookies are re
turned for a given url, the format of the re
turn value is: cookie1=value1;cookie2=value2;cookie3=value3 len out parameter. the length of the re
turned value buffer. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description this entry point is designed to allow plugins which implement their ...
NPN_HasMethod - Archive of obsolete content
specified npobject has a particular method. syntax #include <npruntime.h> bool npn_hasmethod(npp npp, npobject *npobj, npidentifier methodname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object on which to look for the method. methodname a string identifier indicating the name of the method to look for. re
turns true if the method exists on the specified object, otherwise false. ...
NPN_HasProperty - Archive of obsolete content
rty. syntax #include <npruntime.h> bool npn_hasproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance is making the request. <tt>npobj</tt> the object on which to look for the property. <tt>propertyname</tt> a string identifier indicating the name of the property to look for. re
turns true if the property exists on the specified object, otherwise false. ...
NPN_IntFromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary re
turns the integer value corresponding to the given integer identifier. syntax #include <npruntime.h> int32_t npn_intfromidentifier(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the integer identifier whose corresponding integer value should be re
turned. re
turns an integer corresponding to the specified <tt>identifier</tt>. note: the behavior of this function is undefined if <tt>identifier</tt> isn't an integer identifier. ...
NPN_MemAlloc - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary allocates memory from the browser's memory space. syntax #include <npapi.h> void *npn_memalloc (uint32 size); parameters the function has the following parameters: size size of memory, in bytes, to allocate in the browser's memory space. re
turns if successful, the function re
turns a pointer to the allocated memory, in bytes. if insufficient memory is available, the plug-in re
turns null. description the plug-in calls npn_memalloc to allocate a specified amount of memory in the browser's memory space. if you allocate saved instance data with npp_destroy, be sure to use npn_memalloc to allocate memory. this ensures that the browser can free the saved data at a later time with the equivalent of npn_memfr...
NPN_MemFlush - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary note: this function is only implemented on mac os x. requests that the browser free a specified amount of memory. syntax #include <npapi.h> uint32 npn_memflush(uint32 size); parameters the function has the following parameters: size size of memory, in bytes, to free in the browser's memory space. re
turns if successful, the function re
turns the amount of freed memory, in bytes. if no memory can be freed, the browser re
turns 0. description the plug-in calls npn_memflush() when it is not possible to call npn_memalloc(), for example, when calling system apis that indirectly allocate memory. to request that the browser free as much memory as possible, call npn_memflush() repeatedly until it re
turns 0. on the...
NPN_ReleaseObject - Archive of obsolete content
reference count of the given npobject. if the reference count reaches 0, the npobject is deallocated by calling its deallocate function if one is provided; if one is not provided, free() is used. syntax #include <npruntime.h> void npn_releaseobject(npobject *npobj); parameters the function has the following parameter: <tt>npobj</tt> the npobject whose reference count should be decremented. re
turns nothing. ...
NPN_RemoveProperty - Archive of obsolete content
d npobject. syntax #include <npruntime.h> bool npn_removeproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object on which a property is to be deleted. propertyname a string identifier indicating the name of the property to remove. re
turns true if the property was removed successfully, otherwise false. ...
NPN_SetValue - Archive of obsolete content
einstance nppvpluginscriptableiid nppvjavascriptpushcallerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set. re
turns if successful, the function should re
turn nperr_no_error. if unsuccessful, the function should re
turn the most relevant npapi error code. for possible values, see error codes. description a good place to set plugin operation mode such as windowless mode is npp_new, so the browser knows right away what mode the plugin is designed to operate in. nppvpluginwindowbool (windows and unix) spec...
NPN_SetValueForURL - Archive of obsolete content
n has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be changed. the only supported type is npnurlvcookie. url the url for which to change information. value the new associated information for the url. note: the value may have internal null bytes and may not be null-terminated. len the length of the value buffer. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description this entry point is designed to allow plugins to affect the cookies sent by the browser back to the server. see also npn_getvalueforurl, npn_getauthenticationinfo ...
NPN_UTF8FromIdentifier - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary re
turns the utf-8 string corresponding to the given string identifier. syntax #include <npruntime.h> nputf8 *npn_utf8fromidentifier(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the string identifier whose corresponding string should be re
turned. re
turns a utf-8 string as a sequence of nputf8 bytes, or null if the specified <tt>identifier</tt> isn't a string identifier. description once the caller is done with the re
turned string, the caller is responsible for deallocating the memory used by the string by calling npn_memfree(). ...
NPP - Archive of obsolete content
o creates an npp structure for each plug-in instance and passes a pointer to it to npp_new(). this pointer--which is an opaque instance handle of a plug-in--identifies the instance on which api calls should operate. npp contains private instance data for both the plug-in and the browser. the npp_destroy() function informs the plug-in when the npp instance is about to be deleted; after this call re
turns, the npp pointer is no longer valid. see also npp_new() npp_destroy() ...
NPP_DestroyStream - Archive of obsolete content
. values: npres_done (most common): completed normally; all data was sent to the instance. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. npres_network_err: stream failed due to problems with network, disk i/o, lack of memory, or other problems. re
turns if successful, the plug-in should re
turn nperr_no_error. if unsuccessful, the plug-in should re
turn an error code. for possible values, see error codes. description the browser calls the npp_destroystream function when a data stream sent to the plug-in is finished, either because it has completed successfully or terminated abnormally. after this, the browser deletes the npstream object. ...
NPP_GetValue - Archive of obsolete content
getvalue(void *instance, nppvariable variable, void *value); parameters the function has the following parameters: instance pointer to the plugin instance from which the value should come. variable variable for which the browser (caller) would like a value. the full list is in the npapi headers. value value for the requested variable. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description npp_getvalue retrieves instance variables. see also npp_setvalue, npn_getvalue, npn_setvalue ...
NPP_HandleEvent - Archive of obsolete content
); parameters the function has the following parameters: instance pointer to the current plug-in instance. event platform-specific value representing the event handled by the function. values: ms windows: pointer to npevent structure mac os: pointer to a standard mac os eventrecord unix/x11: pointer to a standard xlib xevent for a list of possible events, see npevent. re
turns if the plug-in handles the event, the function should re
turn true. if the plug-in ignores the event, the function re
turns false. description the browser calls npp_handleevent to tell the plug-in when events take place in the plug-in's window or drawable area. the plug-in either handles or ignores the event, depending on the value given in the event parameter of this function. for a list o...
NPP_NewStream - Archive of obsolete content
: file download. like np_asfileonly except that data is delivered to the plug-in as it is saved to the file (as in mode np_normal). np_seek: stream data randomly accessible by the plug-in as needed, through calls to npn_requestread. implementation note: some plugins, notably silverlight, do not set this outparam, and rely on the outparam being initialized to a default np_normal value. re
turns if successful, the function should re
turn nperr_no_error. if unsuccessful, the function should re
turn one of the nperror error codes. this will cause the browser to destroy the stream without calling npp_destroystream. description npp_newstream notifies the plug-in when a new stream is created. the npstream* pointer is valid until the stream is destroyed. the plug-in can store plug-in-pr...
NPP_SetValue - Archive of obsolete content
le information controlled by the browser. syntax #include <npapi.h> nperror npp_setvalue(void *instance, npnvariable variable, void *value); parameters the function has the following parameters: instance pointer to plugin instance on which to set the variable. variable the variable being set. value value for the variable being set. re
turns if successful, the function should re
turn nperr_no_error. if unsuccessful, the function should re
turn the most relevant npapi error code. for possible values, see error codes. description none see also npp_new, npp_getvalue, npn_setvalue, npn_getvalue ...
NPP_SetWindow - Archive of obsolete content
p_setwindow(npp instance, npwindow *window); parameters the function has the following parameters: instance pointer to the current plug-in instance. must be embedded or full-screen. window pointer to the window into which the instance draws. the window structure contains a window handle and values for top left corner, width, height, and clipping rectangle (see note on unix below). re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description the browser calls npp_setwindow after creating the instance to allow drawing to begin. subsequent calls to npp_setwindow indicate changes in size or position; these calls pass the same npwindow object each ...
NP_GetValue - Archive of obsolete content
alue); parameters the function has the following parameters: instance pointer to the current plug-in instance. instance parameter is null because no instance has been created. variable plug-in information the call gets. values: nppvpluginnamestring: gets the name of the plug-in nppvplugindescriptionstring: gets the description string of the plug-in value plug-in name, re
turned by the function. re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the function re
turns an error code. for possible values, see error codes. description none. see also npp_setvalue ...
NP_Initialize - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary provides global initialization for a plug-in. syntax windows #include <npapi.h> nperror winapi np_initialize(npnetscapefuncs *anpnfuncs) unix #include <npapi.h> nperror np_initialize(npnetscapefuncs *anpnfuncs, nppluginfuncs *anppfuncs) re
turns if successful, the function re
turns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function re
turns an error code. for possible values, see error codes. description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. this is the first function that the browser calls. np_initialize tells the plug-in that the browser has loaded it and provides global initialization. allocate any memory or r...
Writing a plugin for Mac OS X - Archive of obsolete content
is posted under a bsd-style license that means you can use it for anything, even if you don't plan to release your source code. getting started if you check out the mozilla source code in mac os x, you can simply open basicplugin.xcodeproj in xcode, click build, and you're done. xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in
turn contains a "release" directory with the plugin inside it. to install the plugin, just copy it into one of these two locations: /library/internet plugins/ ~/library/internet plugins/ from this point, you can simply modify the sample plugin to do whatever you want. notes and tips this section provides some additional information that may be helpful if you're trying to get a plugin building...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
many peoplewrite in html information and formatting is lost with the rss <description> element. however, it has become common practice to putxml escaped html data in it. (even through you are not suppose to.) for example, if your blog post was: this is <b>bold</b>. then the <description> would be: <description>this is <b>bold</b>.</description> note that the "<" has been
turned into "<". and the ">" has been
turned into ">". this greatly bloats the size of contents but is necessary since certain characters are no allowed in xml. xml does however have the cdata convention. you can put (almost) whatever you want in a cdata section. including "<" and ">" without having to escape them. using the example above we'd have: <description><![cdata[this is <b>bold</b>...
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): startdoc...
Introduction to Public-Key Cryptography - Archive of obsolete content
certificate signature is verified using the public key in the issuer's certificate. if the issuer's certificate is trusted by the verifier in the verifier's certificate database, verification stops successfully here. otherwise, the issuer's certificate is checked to make sure it contains the appropriate subordinate ca indication in the red hat certificate type extension, and chain verification re
turns to step 1 to start again, but with this new certificate. figure 8 presents an example of this process. figure 8 shows what happens when only root ca is included in the verifier's local database. if a certificate for one of the intermediate cas shown in figure 8, such as engineering ca, is found in the verifier's local database, verification stops with that certificate, as shown in figure 9. ...
Theme changes in Firefox 3.5 - Archive of obsolete content
nstripe. bug 450944 changed the way window shadow is handled on mac os x. before that change, opaque windows always had a shadow and transparent windows never had a shadow. after that change, transparent windows also have a shadow by default. this can result in unwanted shadows in your theme, e.g. under the autoscroll icon or the identity panel. if you don't want the shadow, you can
turn it off by setting the new -moz-window-shadow css property to none on the affected element. browser.xul bug 463189 added a new attribute on the xul window element of browser.xul named browsingmode. the value of this attribute is normal when the private browsing mode is inactive, and private when it's active. this attribute can be used to style different parts of the browser window in...
Scratchpad - Archive of obsolete content
will be added to the global object for that tab. there are four execution options available. run when you choose the run option, the selected code is executed. this is what you'd use to execute a function or other code that manipulates the content of your page without needing to see the result. inspect the inspect option executes the code just like the run option; however, after the code re
turns, an object inspector is opened to let you examine the re
turned value. for example, if you enter the code: window then choose inspect, the object inspector is shown that looks something like this: display the display option executes the selected code, then inserts the result directly into your scratchpad editor window as a comment, so you can use it as a repl. reload and run the reload ...
Developing cross-browser and cross-platform pages - Archive of obsolete content
jects or features in the browser's dom implementation, but they serve to illustrate clearly how object support detection works. the top-level if clause looks to see if there is support for a method called getelementbyid on the document object, which is the one of the most basic levels of support for the dom in a browser. if there is, the code sees if document.getelementbyid(id_attribute_value) re
turns a reference to an existing element, which it then checks for a style object. if the style object exists on the element, then it sets that object's visibility property. the browser will not error if you set this unimplemented property, so you do not need to check that the visiblity property itself exists. so, instead of needing to know which browsers and browser versions support a particular dom...
Using workers in extensions - Archive of obsolete content
ker's. line 22 sends a message to the ticker thread to tell it what symbol to monitor. the observe() method this method's job is to update which stock is being monitored when the user changes the preferences. it needs to be updated to post a message to the worker to tell it which stock symbol to track. observe: function(subject, topic, data) { if (topic != "nspref:changed") { re
turn; } switch(data) { case "symbol": this.tickersymbol = this.prefs.getcharpref("symbol").touppercase(); this.worker.postmessage(this.tickersymbol); break; } }, the key here is line 10, which sends the new ticker symbol to monitor to the ticker thread by calling its postmessage() method. this results in the ticker's onmessage handler being called. the w...
-moz-window-shadow - Archive of obsolete content
the -moz-window-shadow css property specifies whether a window will have a shadow. it only works on mac os x. this property is not standard and from firefox 44 onwards cannot be used on websites anymore. firefox 3 added support for transparent windows on mac os x. however, for these windows shadows were
turned off and there was no way to
turn them on. in firefox 3.5 the default changed, with all windows having a shadow. this version introduced the -moz-window-shadow css property to provide a way to
turn off unwanted shadows. initial valuedefaultapplies toall elements that create native windows, e.g. <window>, <panel>inheritednocomputed valueas specifiedanimation typediscrete syntax the -moz-window-shadow property is specified as one of the keyword values listed below. values def...
::-ms-fill - Archive of obsolete content
if it has a value attribute set; otherwise it is indeterminate. an indeterminate progress bar can be selected with the :indeterminate pseudo-class.) by default, internet explorer and edge display a moving dots animation for an indeterminate progress bar. by setting animation-name on ::-ms-fill, you can change the animation, as shown in this table: value description none
turns off the animation so that no dots are displayed. -ms-bar shows animated dots that flow in a bar pattern. -ms-ring shows animated dots that flow in a ring pattern. allowable properties only the following css properties can be used in a rule with ::-ms-fill in its selector. other properties are ignored. animation-name background-clip, background-color, backgroun...
Displaying notifications (deprecated) - Archive of obsolete content
r downward. creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4. you should take some action. right now!"); this re
turns a new notification object, but does not actually display the notification. this lets you configure the event listeners before the notification is shown, if you need to be notified when the notification is dismissed. setting up event listeners on the notification there are two events you can listen to on created notifications: onclick this event is fired when the user clicks (or taps) on th...
Array comprehensions - Archive of obsolete content
/ [2006, 2010, 2014] [for (year of years) if (year > 2000) if (year < 2010) year]; // [2006], the same as below: [for (year of years) if (year > 2000 && year < 2010) year]; // [2006] array comprehensions compared to map and filter an easy way to understand array comprehension syntax, is to compare it with the array map and filter methods: var numbers = [1, 2, 3]; numbers.map(function (i) { re
turn i * i }); numbers.map(i => i * i); [for (i of numbers) i * i]; // all are [1, 4, 9] numbers.filter(function (i) { re
turn i < 3 }); numbers.filter(i => i < 3); [for (i of numbers) if (i < 3) i]; // all are [1, 2] array comprehensions with two arrays using two for-of iterations to work with two arrays: var numbers = [1, 2, 3]; var letters = ['a', 'b', 'c']; var cross = [for (i of numbers) for...
Expression closures - Archive of obsolete content
to the function body. paramn the name of an argument to be passed to the function. a function can have up to 255 arguments. expression the expression which comprise the body of the function. description this addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical lambda notation. javascript 1.7 and older: function(x) { re
turn x * x; } javascript 1.8: function(x) x * x this syntax allows you to leave off the braces and 're
turn' statement - making them implicit. there is no added benefit to writing code in this manner, other than having it be syntactically shorter. examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the a...
Function.arity - Archive of obsolete content
the arity property used to re
turn the number of arguments expected by the function, however, it no longer exists and has been replaced by the function.prototype.length property. specifications not part of any standard. ...
ActiveXObject - Archive of obsolete content
this object is used only to instantiate automation objects, and has no members. syntax let newobj = new activexobject(servername.typename[, location]) parameters servername the name of the application providing the object. typename the type or class of the object to create. location optional the name of the network server where the object is to be created. remarks automation servers provide at least one type of object. ...
Date.getVarDate() - Archive of obsolete content
warning: this method is supported in internet explorer only. the getvardate method re
turns a vt_date value from a date object. syntax dateobj.getvardate() parameters the required dateobj reference is a date object. re
turn value re
turns a vt_date value. remarks the getvardate() method is used when javascript code interacts with com objects, activex objects, or other objects that accept and re
turn date values in vt_date format. these include objects in visual basic and visual basic scripting edition (vbscript). the actual format of the re
turned value depends on regional settings. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and int...
Enumerator - Archive of obsolete content
b = drv.totalsize / bytespergb; drivestring += freegb.tofixed(3) + " gb free of "; drivestring += totalgb.tofixed(3) + " gb"; } else{ drivestring += "not ready"; } drivestring += "<br />";; e.movenext(); } document.write(drivestring); // output: <drive information properties the enumerator object has no properties. methods enumerator.atend re
turns a boolean value indicating if the enumerator is at the end of the collection. enumerator.item re
turns the current item in the collection. enumerator.movefirst resets the current item in the collection to the first item. enumerator.movenext moves the current item to the next item in the collection. requirements supported in the following document modes: quirks, internet explorer 6 standa...
Error.description - Archive of obsolete content
syntax object .description [= stringexpression] parameters object required. any instance of an error object. stringexpression optional. a string expression containing a description of the error. remarks the description property contains the error message string associated with a specific error. use the value contained in this property to alert a user to an error. ...
Error.number - Archive of obsolete content
the error object's default property is number. syntax object .number [= errornumber] parameters object any instance of the error object. errornumber an integer representing an error. remarks an error number is a 32-bit value. the upper 16-bit word is the facility code, and the lower word is the error code. to determine the error code, use the & (bitwise and) operator to combine the number property with the hexadecimal number 0xffff. ...
ScriptEngine() - Archive of obsolete content
the scriptengine function gets the name of the scripting language in use. syntax scriptengine() remarks the scriptengine function re
turns "jscript", which indicates that javascript is the current scripting engine. example the following example illustrates the use of the scriptengine function: if (window.scriptengine) { console.log(window.scriptengine()); } // output: jscript requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
ScriptEngineBuildVersion - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the scriptenginebuildversion function bets the build version number of the scripting engine in use. syntax scriptenginebuildversion() remarks the re
turn value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. example the following example illustrates the use of the scriptenginebuildversion function: if(window.scriptenginebuildversion) { console.log(window.scriptenginebuildversion()); } // output: <current build version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 st...
ScriptEngineMajorVersion - Archive of obsolete content
non-standard. do not use! this object is a microsoft extension and is only supported in internet explorer. the scriptenginemajorversion function gets the major version number of the scripting engine in use. syntax scriptenginemajorversion() remarks the re
turn value corresponds directly to the version information contained in the dynamic-link library (dll) for the scripting language in use. example the following example illustrates the use of the scriptenginemajorversion function: if (window.scriptenginemajorversion) { console.log(window.scriptengine()); } output: <current major version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, inter...
VBArray.getItem - Archive of obsolete content
syntax safearray.getitem(dimension1[, dimension2, ...], dimensionn) parameters safearray a vbarray object. dimension1, ..., dimensionn specifies the exact location of the desired element of the vbarray. n equals the number of dimensions in the vbarray. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. ...
VBArray.toArray - Archive of obsolete content
syntax safearray.toarray( ) remarks the required safearray reference is a vbarray object. the conversion translates the multidimensional vbarray into a single dimensional javascript array. each successive dimension is appended to the end of the previous one. for example, a vbarray with three dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). ...
VBArray - Archive of obsolete content
e="text/javascript"> <!-- function vbarraytest(vbarray){ var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties. methods vbarray.dimensions re
turns the number of dimensions in a vbarray. vbarray.getitem re
turns the item at the specified location. vbarray.lbound re
turns the lowest index value used in the specified dimension of a vbarray. vbarray.toarray re
turns a standard javascript array converted from a vbarray. vbarray.ubound re
turns the highest index value used in the specified dimension of the vbarray. requirements supported ...
New in JavaScript 1.1 - Archive of obsolete content
eval() is now a method of every object (was previously a built-in function); it evaluates a string of javascript code in the context of the specified object. math.random() now works on every platform. tostring(): added radix parameter, which specifies the base to use for representing numeric values. isnan() now works on every platform (not only unix anymore) parsefloat() and parseint() now re
turn nan on all platforms, if the first character of the specified string cannot be converted to a number; in previous releases, it re
turned nan on solaris and irix and zero on all other platforms. ...
New in JavaScript 1.8 - Archive of obsolete content
ructuring for..in one change that occurred in the release of javascript 1.8 was a bug fix related to the key/value destructuring of arrays introduced in javascript 1.7. previously it was possible to destructure the keys/values of an array by using for ( var [key, value] in array ). however, that made it impossible to destructure the values of an array - that were arrays (i.e., when an iterator re
turns an array of the current key-value pair). this has been resolved now. (bug 366941). one can, however, use for ( var [key, value] in iterator(array)). ...
Object.getNotifier() - Archive of obsolete content
the object.getnotifer() method was used to create an object that allows to synthetically trigger a change, but has been deprecated and removed in browsers. syntax object.getnotifier(obj) parameters obj the object to retrieve the notifier of. re
turn value the notifier object associated with the object being passed to the function. description the notifier is used to trigger synthetic changes that will be observed by object.observe(). specifications not part of any standard. strawman proposal specification. ...
Object.unobserve() - Archive of obsolete content
the object.unobserve() method was used to remove observers set by object.observe(), but has been deprecated and removed from browsers. you can use the more general proxy object instead. syntax object.unobserve(obj, callback) parameters obj the object to stop observing. callback the reference to the observer to stop calling each time changes are made on the object obj. re
turn value the specified object. description object.unobserve() should be called after object.observe() in order to remove an observer from an object. the callback should be a reference to a function and not an anonymous function, because this reference will be used to unset the previous observer. it's useless to call object.unobserve() with an anonymous function as callback, it will not remove any obs...
Object.prototype.unwatch() - Archive of obsolete content
firefox 58+. in addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. you can usually use setters and getters or proxies instead. the unwatch() method removes a watchpoint set with the watch() method. syntax obj.unwatch(prop) parameters prop the name of a property of the object to stop watching. re
turn value undefined. description the javascript debugger has functionality similar to that provided by this method, as well as other debugging options. for information on the debugger, see venkman. by default, this method is inherited by every object descended from object. note: the reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing"...
Reflect.enumerate() - Archive of obsolete content
the static reflect.enumerate() method used to re
turn an iterator with the enumerable own and inherited properties of the target object, but has been removed in ecmascript 2016 and is deprecated in browsers. syntax reflect.enumerate(target) parameters target the target object on which to get the property. re
turn value an iterator with the enumerable own and inherited properties of the target object. exceptions a typeerror, if target is not an object. description the reflect.enumerate method re
turns an iterator with the enumerable own and inherited properties of the target object. examples using reflect.enumerate() var obj = { x: 1, y: 2 }; for (var name of reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" specifications not part of any standar...
String.prototype.quote() - Archive of obsolete content
obsolete since gecko 37 (firefox 37 / thunderbird 37 / seamonkey 2.34)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the non-standard quote() method re
turns a copy of the string, replacing various special characters in the string with their escape sequences and wrapping the result in double-quotes ("). syntax str.quote() re
turn value a new string representing the original string wrapped in double-quotes, with any special characters escaped. examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes. also note the third column where a wrapped eval() evaluates the escape sequences again. str...
JSObject - Archive of obsolete content
lic object eval(string s) getmember method. retrieves the value of a property of a javascript object. equivalent to "this.name" in javascript. declaration public object getmember(string name) getslot method. retrieves the value of an array element of a javascript object. equivalent to "this[index]" in javascript. declaration public object getslot(int index) getwindow static method. re
turns a jsobject for the window containing the given applet. this method is useful in client-side javascript only. declaration public static jsobject getwindow(applet applet) removemember method. removes a property of a javascript object. declaration public void removemember(string name) setmember method. sets the value of a property of a javascript object. equivalent to "this.name = value" ...
ParallelArray - Archive of obsolete content
w parallelarray() new parallelarray([element0, element1, ...]) new parallelarray(arraylength, elementalfunction) parallelarray instances properties length reflects the number of elements in the parallelarray. methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { re
turn v + 1; }); ...
forEach - Archive of obsolete content
sire. jswisher 15 aug 2011 <hr> is this a from _core_ of javascript 1.5? if so, is js 1.5 gecko only? those extra features like foreach are gecko only, and it should be mentioned that they should *_not_* be used on web pages. --gandalf 07:18, 31 may 2005 (pdt) is there a way to make foreach make use of break? [1].foreach(function(value, index, array){ print(value); //break? if (value>1){ re
turn false;//we could have some way to break when we re
turn false } }); //woulld print 1 2 --porfirio 11:17, 22-06-2008 another option would be to throw stopiteration and catch it within foreach(). --bencollver 11:18, 13-08-2008 ...
Writing JavaScript for XHTML - Archive of obsolete content
... /*]]>*/--></style> see this document for more on the issues related to application/xhtml+xml and text/html (at least as far as xhtml 1.* and html 4; html5 addresses many of these problems). problem: names in xhtml and html are represented in different cases scripts that used getelementsbytagname() with an upper case html name no longer work, and attributes like nodename or tagname re
turn upper case in html and lower case in xhtml. solution: use or convert to lower case for methods like getelementsbytagname(), passing the name in lower case will work in both html and xhtml. for name comparisons, first convert to lower case before doing the comparison (e.g., "el.nodename.tolowercase() === 'html'"). this will ensure that documents in html will compare correctly and will do no harm...
XForms Switch Module - Archive of obsolete content
introduction xforms switch module define a switch construct that allows the creation of user interfaces where the user interface can be varied based on user actions and events. the module defines for this switch, case and toggle elements. switch element the element (see the spec) is used in conjunction with case and toggle elements. the switch element contains case elements which in
turn contain markup. only the contents of a single case may be displayed at one time. the toggle element is an action that when triggered will make a case selected and visible and thereby hiding all other case elements contained by the same switch. attributes single-node binding type restrictions the switch element can be bound to a node containing data of any type. actually, the switch element does...
Mozilla XForms User Interface - Archive of obsolete content
o a way to apply model item properties (for example, relevancy) to the elements. elements in this section do not have any behaviors that are dependent on the host language. group this element is used to logically group xforms elements together (see the spec). switch this element is used in conjunction with case and toggle elements (see the spec). the switch element contains case elements which in
turn contain markup. only the contents of a single case may be displayed at one time. the toggle element is used (as an event handler) to make a case visible and thereby hiding all other case elements contained by the same switch. repeat a repeat element contains markup and is itself bound to a nodeset in an instance document (see the spec). for each node in the nodeset, the contents of the repeat ele...
Using XForms and PHP - Archive of obsolete content
to do that, you need to use the header() php function: <?php header("content-type: application/xhtml+xml; charset=utf-8"); ... ?> but remember this (quote from php documentation): remember that header() must be called before any actual output is sent, either by normal html tags, blank lines in a file, or from php. ...
Archived open Web documentation - Archive of obsolete content
ore familiar to javascript programming. talk:array.foreach() ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document. iterator the iterator function re
turns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. liveconnect (please update or remove as needed.) msx emulator (jsmsx) old proxy api proxies are objects for which the programmer has to define the semantics in javascript. the default object semantics are imp...
Describing microformats in JavaScript - Archive of obsolete content
l. properties a structure describing the properties of the microformat. property specifications each property in the properties structure is specified by its name, and may include additional attributes if the property so requires. standard attributes are: plural a boolean value indicating that, if true indicates that the property can have multiple values. if a property is plural, it is re
turned as an array. virtual a boolean value indicating whether or not the property is virtual. if it's virtual, the virtualgetter() method will be called to attempt to create the property if it doesn't exist. virtualgetter a function that is called to get a virtual property's value. this is only used if virtual is true. value the property's default value. subproperties it's possible for a prop...
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
lied to hyperlinks, this will work fine. however, rules of this type are usually seen in conjunction with markup like this: <td class="nav"> <a href="one.html" class="nav">one</a> | <a href="two.html" class="nav">two</a> | <a href="thr.html" class="nav">three</a> | <a href="fou.html" class="nav">four</a> </td> because the enclosing table cell has a class of nav, the vertical-bar characters will
turn red when the user moves the mouse pointer anywhere within the table cell. the links will also
turn red when they are hovered. gecko behavior in browsers based on netscape gecko builds later than 20020410 (netscape 6.1+), :hover styles can be applied to any element in a document. thus authors who have used bare pseudo-classes, or bare class-pseudo-class combinations, are at risk of seeing hover ...
Popup Window Controls - Archive of obsolete content
to open a popup window that is the direct result of user action, such as clicking on a hyperlink, should succeed in opening popup windows even if the user has popup controls enabled on your site. detecting suppressed popups windows if a user has popup controls enabled for your site, any attempt to call window.open in global script, in an onload handler or in settimeout() or setinterval() will re
turn null rather than a reference to the opened window. <html> <head> <title>detecting popup controls</title> <script type="text/javascript"> <!-- // attempt to open an unsolicited window var popup = window.open('about:blank', 'popup'); if (!popup) { // the user has suppressed the popup } // --> </script> </head> <body> <!-- your page here --> </body> ...
RDF in Mozilla FAQ - Archive of obsolete content
(an <rdf:seq>, for example), you can use nsirdfcontainerutils which can be instantiated as a service with the following contractid: @mozilla.org/rdf/container-utils;1 you can use this service to detect if something is an rdf container using isseq(), isbag(), and isalt(). you can "make a resource into a container" if it isn't one already using makeseq(), makebag(), or makealt(). these methods re
turn an nsirdfcontainer which allows you to do container-like operations without getting your hands too dirty. alternatively, if your datasource already has an object that is an rdf container, you can instantiate an nsirdfcontainer object with the @mozilla.org/rdf/container;1 contractid and init() it with the datasource and resource as parameters. note that this will fail if the resource isn't alr...
XQuery - Archive of obsolete content
ample is available. notes for developers wishing to access xquery in their own extensions at present, the extension works simply by using liveconnect to work with berkeley db xml's java api (and via a java wrapper class which circumvents liveconnect's current inability to handle some types of java exceptions properly). however, use of the approach of the java firefox extension might be used to
turn the above extension concept into an xpcom component (giving it access to all open windows), and for berkeley db xml, possibly implementing it in c++ instead, which is that database's original language of development. however, the extension demonstrates a technique which does not depend on using xpcom, while still giving full privileges. tutorials w3schools learn xquery in 10 minutes an int...
XUL Parser in Python - Archive of obsolete content
t some quicker way of looking at the xul--at particular builds, at particular widgets, at which elements had which attributes, etc. the script writes out all the attributes and none of the values, but the parser itself is seeing the elements, their attributes, and the values of those attributes, and you just have to ask for them if you want them. for example, you could easily adapt this to: re
turn the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e. new "packages") on the fly using search and replace. as i adapt the script in these ways and try to further generalize the actual code as i get time, i will make it available here. in the explanation section below, i try to say a little something about how this scr...
Common causes of memory leaks in extensions - Extensions
function startup(data, reason) { // this assumes your add-on did register some chrome components.utils.import("chrome://myaddon/content/mymodule.jsm"); } function shutdown(data, reason) { // no need to do regular clean up when the application is closed // unless you need to break circular references that might negatively // impact the shutdown process. if (reason == app_shutdown) re
turn; // your add-on needs to unload all modules it ships and imported! components.utils.unload("chrome://myaddon/content/mymodule.jsm"); } note: modules not belonging to your add-on — such as services.jsm — should not be unloaded by your add-on, as this might cause errors and/or performance regressions and will actually increase the memory usage. other information also see using xpcom in...
Examples - Game development
stic aliens-esque isometric 3rd person shooter demo, made with unity3d. nutmeg cute retro scrolling platforming action. back to candyland a match-3 (candy crush) style game. biolab disaster side-scrolling platform shooter. x-type vertically scrolling space shooter demo. xibalba retro (doom-style) first person shooter. gorescript another retro style first person shooter. the wizard a
turn-based, dungeon puzzle game. hextris tetris-like hexagonal puzzle game. 2048 a sliding number tiles puzzle game. bananabread a multiplayer, 3d first-person shooter game developed using emscripten, webgl, and webrtc. monster madness a webgl and asm.js-based multiplayer online shooter, developed by nom nom games and trendy entertainment. auralux webgl and asm.js-based strategy game: captur...
2D collision detection - Game development
"></script> #cr-stage { position: static !important; height: 200px !important; } crafty.init(200, 200); var dim1 = {x: 5, y: 5} var dim2 = {x: 20, y: 20} crafty.c("circle", { circle: function(radius, color) { this.radius = radius; this.w = this.h = radius * 2; this.color = color || "#000000"; this.bind("move", crafty.drawmanager.drawall) re
turn this; }, draw: function() { var ctx = crafty.canvas.context; ctx.save(); ctx.fillstyle = this.color; ctx.beginpath(); ctx.arc( this.x + this.radius, this.y + this.radius, this.radius, 0, math.pi * 2 ); ctx.closepath(); ctx.fill(); ctx.restore(); } }); var circle1 = cra...
Build the brick field - Game development
; var brickoffsettop = 30; var brickoffsetleft = 30; here we've defined the number of rows and columns of bricks , their width and height, the padding between the bricks so they won't touch each other and a top and left offset so they won't start being drawn right from the edge of the canvas. we will hold all our bricks in a two-dimensional array. it will contain the brick columns (c), which in
turn will contain the brick rows (r), which in
turn will each contain an object containing the x and y position to paint each brick on the screen. add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and...
2D maze game with device orientation - Game development
unction(e) {}, finishlevel: function() {} }; the create and update functions are framework-specific, while others will be our own creations: initlevels initializes the level data. showlevel prints the level data on the screen. updatecounter updates the time spent playing each level and records the total time spent playing the game.. managepause pauses and resumes the game. manageaudio
turns the audio on and off. wallcollision is executed when the ball hits the walls or other objects. handleorientation is the function bound to the event responsible for the device orientation api, providing the motion controls when the game is running on a mobile device with appropriate hardware. finishlevel loads a new level when the current level is completed, or finished the game if the final l...
Gecko FAQ - Gecko Redirect 1
bel attribute of option, alternate text of area elements, longdesc various metadata attributes: cite, datetime, lang, hreflang bidirectional text layout, which is only used in hebrew and arabic (ibm has begun work to add bidi support in a future release) style sheets css 1 - full support, except for: the application of styles to html column elements the ability to
turn off author styles the names of certain mozilla extension pseudo-classes lack the moz- prefix css 2 - partial support is expected and has already been built into gecko, including support for css2 positioning, but no commitment has been made to achieve a specific level of support dom level 0 level 1 core: full support making entityreferences available throu...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
another piece of software (such as a server), and continue to do other things while waiting for a reply. for example, the ajax (asynchronous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being re
turned when available rather than immediately. software design asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete. when the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the...
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
rs and relevant properties for each selector in the form of a tree, with a root node, sibling, descendant, child, and other relationship. the cssom is very similar to the document object model (dom). both of them are part of the critical rendering path which is a series of steps that must happen to properly render a website. the cssom, together with the dom, to build the render tree, which is in
turn used by the browser to layout and paint the web page. cssom api the css object model is also a set of apis allowing the manipulation of css from javascript. it is much like the dom, but for the css rather than the html. it allows users to read and modify the css style dynamically. see also populating the page: how browsers work ...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
php (and the like) includes many control structures, including conditionals, loops and functions. parts of a script may also be set to execute when events occur. for example, the above excerpt might be inside a function that runs when the user clicks the submit button for the form. the function could also include a loop, which iterates through all of the fields in the form, checking each one in
turn. looking back at the code in the if and else sections, the lines promptuser and submitform could also be calls to other functions in the script. as you can see, control structures can dictate complex flows of processing even with only a few lines of code. control flow means that when you read a script, you must not only read from start to finish but also look at program structure and how it affe...
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
<!doctype html>" doctype ensures that the browser makes a best-effort attempt at following the relevant specifications, rather than using a different rendering mode that is incompatible with some specifications. learn more general knowledge definition of the doctype in the html specification quirks mode and standards mode technical reference document.doctype, a javascript method that re
turns the doctype ...
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
the values of 'slow-2g', '2g', '3g', and '4g' are determined using observed round-trip times and downlink values. table of effective connection types ect minimum rtt maximum downlink explanation slow-2g 2000ms 50 kbps the network is suited for small transfers only such as text-only pages. 2g 1400ms 70 kbps the network is suited for transfers of small images. ...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
only if they have the [[ishtmldda]] internal slot. this slot only exists in document.all and cannot be set using javascript. examples examples of falsy values in javascript (which are coerced to false in boolean contexts, and thus bypass the if block): if (false) if (null) if (undefined) if (0) if (-0) if (0n) if (nan) if ("") the logical and operator, && if the first object is falsy, it re
turns that object false && "dog" // ↪ false 0 && "dog" // ↪ 0 specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification. learn more truthy boolean ...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
unning in a worker has a workerglobalscope object as its global object. scripts running under node.js have an object called global as their global object. window object in the browser the window object is the global object in the browser. any global variables or functions can be accessed as properties of the window object. access global variables var foo = "foobar"; foo === window.foo; // re
turns: true after defining a global variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the global object window.foo. explanation: the global variable foo was stored in the window object, like this: foo: "foobar" access global functions function greeting() { console.log("hi!"); } window.greeting(); // it is the same as ...
Grid container - MDN Web Docs Glossary: Definitions of Web-related terms
when an element becomes a grid container it establishes a grid formatting context. the direct children can now lay themselves out on any explicit grid defined using grid-template-columns and grid-template-rows, or on the implicit grid created when an item is placed outside of the explicit grid. ...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
is is because of how context execution works in javascript. hoisting works well with other data types and variables. the variables can be initialized and used before they are declared. only declarations are hoisted javascript only hoists declarations, not initializations. if a variable is declared and initialized after using it, the value will be undefined. for example: console.log(num); // re
turns undefined, as only declaration was hoisted, no initialization has happened at this stage var num; // declaration num = 6; // initialization the example below only has initialization. no hoisting happens so trying to read the variable results in referenceerror exception. console.log(num); // throws referenceerror exception num = 6; // initialization below are more examples demonstrating hoisti...
Keyword - MDN Web Docs Glossary: Definitions of Web-related terms
a keyword is a word or phrase that describes content. online keywords are used as queries for search engines or as words identifying content on websites. when you use a search engine, you use keywords to specify what you are looking for, and the search engine re
turns relevant webpages. for more accurate results, try more specific keywords, such as "blue mustang gto" instead of simply "mustang". webpages also use keywords in a meta tag (in the <head> section) to describe page content, so search engines can better identify and organize webpages. learn more general knowledge keyword on wikipedia ...
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
a long task is a task that takes more than 50ms to complete. it is an uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different
turns of the event loop that exceeds 50 ms. see also long task api ...
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
ractically speaking, if i divide two variables in a javascript program, the result may be nan, which is predefined in javascript as "undefined". hence this division may break the program. now, if this computation was a small part of a much larger algorithm, it would be really painful to figure out where the error actually occurs. fortunately, since the result will be nan and i know my divisor may
turn out to be 0, i can set up testing conditions that prevent any such computations in the first place or notify me of where they happen. learn more general knowledge nan on wikipedia technical information nan in javascript ...
Null - MDN Web Docs Glossary: Definitions of Web-related terms
ints, generally intentionally, to a nonexistent or invalid object or address. the meaning of a null reference varies among language implementations. in javascript, null is marked as one of the primitive values, because its behaviour is seemingly primitive. but in certain cases, null is not as "primitive" as it first seems! every object is derived from null value, and therefore typeof operator re
turns object for it: typeof null === 'object' // true ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement re
turn false. learn more general knowledge operator (computer programming) on wikipedia technical reference javascript operators ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
, without affecting the original. primitive wrapper objects in javascript except for null and undefined, all primitive values have object equivalents that wrap around the primitive values: string for the string primitive. number for the number primitive. bigint for the bigint primitive. boolean for the boolean primitive. symbol for the symbol primitive. the wrapper's valueof() method re
turns the primitive value. learn more general knowledge introduction to javascript data types primitive data type on wikipedia ...
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
hing 'or'1'='1 after clicking on the login button, the sql query will work as follows: "select count(*) from users where username=' admin ' and password=' anything 'or'1'='1 ' "; just take a closer look at the above query's password section. password=' anything 'or'1'='1 ' the password is not 'anything', hence password=anything results in false, but '1'='1' is a true statement and hence re
turns a true value. finally, due to the or operator, the value ( false or true ) is true, so authentication bypasses successfully. just due to a simple string (magical string) the entire database is compromised. how to prevent before executing the queries for the user credentials, make some changes like the following: $id = $_get['id'] (1) $id = stripslashes($id) (2) $id = mysql_real_escape_st...
STUN - MDN Web Docs Glossary: Definitions of Web-related terms
stun (session traversal utilities for nat) is an auxiliary protocol for transmitting data around a nat (network address translator). stun re
turns the ip address, port, and connectivity status of a networked computer behind a nat. learn more general knowledge stun on wikipedia webrtc protocols technical reference specification ...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) semantics in javascript in javascript, consider a function that takes a string parameter, and re
turns an <li> element with that string as its textcontent. would you need to look at the code to understand what the function did if it was called build('peach'), or createliwithcontent('peach')? semantics in css in css, consider styling a list with li elements representing different types of fruits. would you know what part of the dom is being selected with div > ul > li, or .fruits__item? semantics in html in html, for example, the <h1> element is a se...
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
nous refers to real-time communication where each party receives (and if necessary, processes and replies to) messages instantly (or as near to instantly as possible). a human example is the telephone — during a telephone call you tend to respond to another person immediately. many programming commands are also synchronous — for example when you type in a calculation, the environment will re
turn the result to you instantly, unless you program it not to. learn more technical reference asynchronous synchronous and asynchronous requests using the xmlhttprequest() api ...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
that ack is received, the congestion window is incremented until the cwnd is less than ssthresh. slow start also terminates when congestion is experienced. congestion control congestion itself is a state that happens within a network layer when the message traffic is too busy it slows the network response time. the server sends data in tcp packets, the user's client then confirms delivery by re
turning acknoledgements, or acks. the connection has a limited capacity depending on hardware and network conditions. if the server sends too many packets too quickly, they will be dropped. meaning, there will be no acknowledgement. the server registers this as missing acks. congestion control algorithms use this flow of sent packets and acks to determine a send rate. see also populating the page:...
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
in order to establish a secure connection. it is possible for both the client and server to mutually authenticate each other, if both parties provide their own individual digital certificates. note: tls 1.0 and 1.1 support will be removed from all major browsers in early 2020; you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, firefox will re
turn a secure connection failed error when connecting to servers using the older tls versions (bug 1606734). ...
TOFU - MDN Web Docs Glossary: Definitions of Web-related terms
erver. to do that, clients will look for identifiers (for example public keys) stored locally. if an identifier is found, the client can establish the connection. if no identifier is found, the client can prompt the user to determine if the client should trust the identifier. tofu is used in the ssh protocol, in http public key pinning (hpkp) where the browsers will accept the first public key re
turned by the server, and in strict-transport-security (hsts) where a browser will obey the redirection rule. learn more http public key pinning (hpkp) public-key-pins wikipedia: tofu ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
y document.write() has been parsed. however, only unusual uses of document.write() cause trouble. here are the things to avoid: don't write unbalanced trees. <script>document.write("<div>");</script> is bad. <script>document.write("<div></div>");</script> is ok. don't write an unfinished token. <script>document.write("<div></div");</script> is bad. don't finish your writing with a carriage re
turn. <script>document.write("hello world!\r");</script> is bad. <script>document.write("hello world!\n");</script> is ok. note that writing balanced tags may cause other tags to be inferred in a way that makes the write unbalanced. e.g. <script>document.write("<div></div>");</script> inside the head element will be interpreted as <script>document.write("</head><body><div></div>");</script> which is ...
MDN Web Docs Glossary: Definitions of Web-related terms
t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident truthy ttl
turn type type coercion type conversion u udp (user datagram protocol) ui undefined unicode uri url urn usenet user agent utf-8 ux v validator value variable vendor prefix viewport visual view...
Accessible multimedia - Learn web development
srclang="en"> </video> this will result in a video that has subtitles displayed, kind of like this: for more details, please read adding captions and subtitles to html5 video. you can find the example that goes along with this article on github, written by ian devlin (see the source code too.) this example uses some javascript to allow users to choose between different subtitles. note that to
turn the subtitles on, you need to press the "cc" button and select an option — english, deutsch, or español. note: text tracks and transcriptions also help you with seo, since search engines especially thrive on text. text tracks even allow search engines to link directly to a spot partway through the video. other multimedia content the above sections don't cover all types of multimedia conte...
Test your skills: HTML accessibility - Learn web development
rap them in an element that associates them all together as a single related group. give the group a description/title that summarises all of the information as personal data. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html accessibility 3 in this task you are required to
turn all the information links in the paragraph into good, accessible links. the first two links just go to regular web pages. the third link goes to a pdf, and it's large — 8mb. the fourth link goes to a word document, so the user will need some kind of application installed that can handle that. try updating the live code below to recreate the finished example: download the starting poi...
Test your skills: WAI-ARIA - Learn web development
arate landmark on the page by screenreaders, to make it easily findable? how can you give the search input a suitable label, without explicitly adding a visible text label to the dom? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. wai-aria 3 for this final wai-aria task, we re
turn to an example we previously saw in the css and javascript skilltest. as before, we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box below the list. here, we are starting with a mouse- and keyboard-accessible version. the problem we have now is that when the dom changes to show a new decriptio...
Backgrounds and borders - Learn web development
nghand properties that we will meet in this lesson. if you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once. .box { background: linear-gradient(105deg, rgba(255,255,255,.2) 39%, rgba(51,56,57,1) 96%) center center / 400px 200px no-repeat, url(big-star.png) center no-repeat, rebeccapurple; } we'll re
turn to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in css, by looking at the individual background properties. background colors the background-color property defines the background color on any element in css. the property accepts any valid <color>. a background-color extends underneath the content and padding box o...
Organizing your CSS - Learn web development
m overly complex, especially for smaller projects. build systems for css another way to organise css is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing css. there are a number of tools which we refer to as pre-processors and post-processors. a pre-processor runs over your raw files and
turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster. using any of these tools will require that your development environment can run the scripts that do the pre and post-processing. many code editors can do this for you, or you can install command line tools to help. the most popul...
CSS values and units - Learn web development
n is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer. functions are usually associated with languages like javascript, python, or c++, but they do exist in css too, as property values. we've already seen functions in action in the colors section — rgb(), hsl(), etc. the value used to re
turn an image from a file — url() — is also a function. a value that behaves more like something you might find in a traditional programming language is the calc() css function. this function gives you the ability to do simple calculations inside your css. it's particularly useful if you want to work out values that you can't define when writing the css for your project, and need the browser to w...
Test your skills: Writing Modes and Logical Properties - Learn web development
t? your example should look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is
turned vertically. your end result should look like the image below. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task three use logical versions of the margin, border, and padding properties so that the edges of the box ...
Floats - Learn web development
previous overview: css layout next originally for floating images inside blocks of text, the float property became one of the most commonly used tools for creating multiple column layouts on webpages. with the advent of flexbox and grid it has now re
turned to its original purpose, as this article explains. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create floated features on webpages, and to use the clear property and other methods of clearing floats. the background of floats the float property was introduced to allow web developers to implement simple layouts involving an image floating inside a column of text, with the text wrapping around the left or ...
Multiple-column layout - Learn web development
eu urna eget velit cursus viverra quis vestibulum sem. aliquam tincidunt eget purus in interdum. cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> </div> columns and fragmentation the content of a multi-column layout is fragmented. it essentially behaves the same way as content behaves in paged media — such as when you print a webpage. when you
turn your content into a multicol container it is fragmented into columns, and the content breaks to allow this to happen. sometimes, this breaking will happen in places that lead to a poor reading experience. in the live example below, i have used multicol to lay out a series of boxes, each of which have a heading and some text inside. the heading becomes separated from the text if the columns fragm...
Practical positioning examples - Learn web development
so that rounds off our look at positioning — by now, you should have an idea of how the basic mechanics work, as well as understanding how to start applying these to build some interesting ui features. don't worry if you didn't get this all immediately — positioning is a fairly advanced topic, and you can always work through the articles again to aid your understanding. the next subject we'll
turn to is flexbox. in this module introduction to css layout normal flow flexbox grid floats positioning multiple-column layout responsive design beginner's guide to media queries legacy layout methods supporting older browsers fundamental layout comprehension assessment ...
CSS layout - Learn web development
at make building complex layouts straightforward. this article will give you all you need to know to get started with page layout, then test your grid skills before moving on. floats originally for floating images inside blocks of text, the float property became one of the most commonly used tools for creating multiple column layouts on webpages. with the advent of flexbox and grid it has now re
turned to its original purpose, as this article explains. positioning positioning allows you to take elements out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport. this article explains the different position values, and how to use them. multiple-column layout the multi...
Getting started with CSS - Learn web development
the first panel is linked to the html document, just as we have with our document above. styling html elements by making our heading red we have already demonstrated that we can target and style an html element. we do this by targeting an element selector — this is a selector that directly matches an html element name. to target all paragraphs in the document you would use the selector p. to
turn all paragraphs green you would use: p { color: green; } you can target multiple selectors at once, by separating the selectors with a comma. if i want all paragraphs and all list items to be green my rule looks like this: p, li { color: green; } try this out in the interactive editor below (edit the code boxes), or in your local css document. changing the default behavior of element...
How CSS is structured - Learn web development
h of this box to be 90% of the containing block width, minus 30 pixels. the result of the calculation isn't something that can be computed in advance and entered as a static value. another example would be the various values for transform, such as rotate(). <div class="box"></div> .box { margin: 30px; width: 100px; height: 100px; background-color: rebeccapurple; transform: rotate(0.8
turn) } the output from the above code looks like this: look up different values of properties listed below. write css rules that apply styling to different html elements: transform background-image, in particular gradient values color, in particular rgb/rgba/hsl/hsla values @rules css @rules (pronounced "at-rules") provide instruction for what css should perform or how it should behave.
How CSS works - Learn web development
prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, and html basics (study introduction to html.) objective: to understand the basics of how css and html are parsed by the browser, and what happens when a browser encounters css it does not understand. ...
CSS first steps - Learn web development
ng started with css in this article we will take a simple html document and apply css to it, learning some practical things about the language along the way. how css is structured now that you have an idea about what css is and the basics of using it, it is time to look a little deeper into the structure of the language itself. we have already met many of the concepts discussed here; you can re
turn to this one to recap if you find any later concepts confusing. how css works we have learned the basics of css, what it is for and how to write simple stylesheets. in this lesson we will take a look at how a browser takes css and html and
turns that into a webpage. using your new knowledge with the things you have learned in the last few lessons you should find that you can format simple text...
Fundamental text and font styling - Learn web development
at had many a story to tell. but it was a rare occasion such as this that he did.</p> html { font-size: 10px; } h1 { font-size: 5rem; } p { font-size: 1.5rem; color: red; font-family: helvetica, arial, sans-serif; } font style, font weight, text transform, and text decoration css provides four common properties to alter the visual weight/emphasis of text: font-style: used to
turn italic text on and off. possible values are as follows (you'll rarely use this, unless you want to
turn some italic styling off for some reason): normal: sets the text to the normal font (
turns existing italics off.) italic: sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead. oblique: sets the text to use a...
How do you make sure your website works properly? - Learn web development
503: service unavailable usually resulting from a shortterm system overload. the server has some sort of problem. try again in a little while. as beginners checking our (simple) website, we'll deal most often with 200, 304, 403, and 404. fixing the 404 so what went wrong? at first glance, the image we asked for seems to be in the right place... but the network tool reported a "404". it
turns out that we made a typo in our html code: unicorn_pics.png rather than unicorn_pic.png. so correct the typo in your code editor by changing the image's src attribute: save, push to the server, and reload the page in your browser: there you go! let's look at the http statuses again: 200 for / and for unicorn_pic.png means that we succeeded in reloading the page and the image. 304 for ba...
What are browser developer tools? - Learn web development
ee what you get. alert('hello!); document.cheeseselector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mybanana.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.queryselector('h1').appendchild(mywordmark); you'll start to see the kind of errors that the browser re
turns. often these errors are fairly cryptic, but it should be pretty simple to figure these problems out! find out more find more out about the javascript console in different browsers: firefox web console ie javascript console chrome javascript console (opera's inspector works the same as this) safari console ...
What is a URL? - Learn web development
ays of the web, a path like this represented a physical file location on the web server. nowadays, it is mostly an abstraction handled by web servers without any physical reality. ?key1=value1&key2=value2 are extra parameters provided to the web server. those parameters are a list of key/value pairs separated with the & symbol. the web server can use those parameters to do extra stuff before re
turning the resource. each web server has its own rules regarding parameters, and the only reliable way to know if a specific web server is handling parameters is by asking the web server owner. #somewhereinthedocument is an anchor to another part of the resource itself. an anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at t...
What is accessibility? - Learn web development
se it without being trapped in it. the basics of web accessibility a few necessities for basic web accessibility include: whenever your site needs an image to convey meaning, include text as an alternative for visually-challenged users or those with slow connections. make sure all users can operate graphical interfaces (like unfolding menus) solely with a keyboard (e.g., with tab and the re
turn key). provide an attribute explicitly specifying your content's language, so that screen readers read your text properly. make sure that a user can navigate to all widgets on a page solely with the keyboard, without getting trapped. (at least let them tab in and out.) and that's just the beginning. accessibility champions since 1999, the w3c has operated a working group called the web acces...
Advanced form styling - Learn web development
't support appearance, your custom design will be lost, but they will still look like checkboxes and be usable. note: while internet explorer doesn't support any version of appearance, the input[type=checkbox]::-ms-check enables the targeting of checkboxes in ie only. this technique works for radio buttons too, despite the name -ms-check. what can be done about the "ugly" elements? now let's
turn our attention to the "ugly" controls — the ones that are really hard to thoroughly style. in short, these are drop-down boxes, complex control types like color and datetime-local, and feedback—oriented controls like <progress> and <meter>. the problem is that these elements have very different default looks across browsers, and while you can style them in some ways, some parts of their inte...
Example 3 - Learn web development
.3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) re
turn; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) re
turn; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optli...
CSS property compatibility table for form controls - Learn web development
ou master those side effects first. no the property simply doesn't work or is so inconsistent that it's not reliable. n.a. the property has no meaning for this type of widget. rendering for each property there are two possible renderings: n (normal) indicates that the property is applied as it is t (tweaked) indicates that the property is applied with the extra rule below: * { /*
turn off the native look and feel */ -webkit-appearance: none; appearance: none; /* for internet explorer */ background: none; } compatibility tables global behaviors some behaviors are common to many browsers at a global level: border, background, border-radius, height using one of these properties can partially or fully
turn off the native look & feel of widgets on some browsers. be ca...
Test your skills: Basic controls - Learn web development
antically. create a submit button inside the remaining list item, with button text of "log in". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. basic controls 2 the next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels.
turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. make it so that the first radio button is selected upon page load.
turn the second <fieldset>'s content into a set of checkboxes. add a couple more hotdog choices of your own. try updating the live code below to recreate the finished example: download the starting...
Your first form - Learn web development
in the basic native form controls article later on. in our simple example, we use the value <input/text> for the first input — the default value for this attribute. it represents a basic single-line text field that accepts any kind of text input. for the second input, we use the value <input/email>, which defines a single-line text field that only accepts a well-formed e-mail address. this
turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user. it also causes a more appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to appear on devices with dynamic keyboards, like smartphones. you'll find out more about form validation in the client-side form validation article later on.
Dealing with files - Learn web development
de your test-site folder. scripts folder: this folder will contain all the javascript code used to add interactive functionality to your site (e.g. buttons that load data when clicked). create a folder called scripts, inside your test-site folder. note: on windows computers, you might have trouble seeing the file names, because windows has an option called hide extensions for known file types
turned on by default. generally, you can
turn this off by going to windows explorer, selecting the folder options... option, unchecking the hide extensions for known file types check box, then clicking ok. for more specific information covering your version of windows, you can search on the web. file paths to make files talk to one another, you have to provide a file path between them — basicall...
Add a hitmap on top of an image - Learn web development
<map name="example-map-1"> <area shape="circle" coords="200,250,25" href="page-2.html" alt="circle example" /> <area shape="rect" coords="10, 5, 20, 15" href="page-3.html" alt="rectangle example" /> </map> step 3: make sure it works for everybody you aren’t done until you test image maps rigorously on many browsers and devices. try following links with your keyboard alone. try
turning images off. if your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. it's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image. if you must use image maps, you may want to look into matt stow's jquery plugin. alternatively, dudley storey demonstrates a way to use sv...
Use JavaScript within a webpage - Learn web development
d 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. have a plan b for users without javascript. people may have javascript
turned off to improve speed and security, and users often face network issues that prevent loading scripts. moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts. at a minimum, leave a short message with <noscript> like this: <noscript>to use this site, please enable javascript.</noscript> ideally, replicate the javascript functionality with html a...
Test your skills: HTML text basics - Learn web development
assessment or further help section at the bottom of this page. html text basics 1 in this task we want you to mark up the provided html using semantic heading and paragraph elements. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 2 in this task we want you to
turn the first un-marked up list into an unordered list, and the second one into an ordered list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 3 in this task you are provided with a paragraph, and your aim is to use some inline elements to mark up a couple of appr...
Test your skills: Links - Learn web development
m of this page. links 1 in this task we want you to help fill in the links on our whales information page: the first link should be linked to a page called whales.html, which is in the same directory as the current page. we'd also like you to give it a tooltip when moused over that tells the user that the page includes information on blue whales and sperm whales. the second link should be
turned into a link you can click to open up an email in the user's default mail application, with the recipient set as "whales@example.com". you'll get a bonus point if you also set it so that the subject line of the email is automatically filled in as "question about whales". note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens th...
From object to iframe — other embedding technologies - Learn web development
you can add permissions back one by one (inside the sandbox="" attribute value) — see the sandbox reference entry for all the available options. one important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case, the embedded content could bypass the same-origin policy that stops sites from executing scripts, and use javascript to
turn off sandboxing altogether. note: sandboxing provides no protection if attackers can fool people into visiting malicious content directly (outside an iframe). if there's any chance that certain content may be malicious (e.g., user-generated content), please serve it from a different domain to your main site. configure csp directives csp stands for content security policy and provides a set of...
HTML table advanced features and accessibility - Learn web development
ach headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces. this gives your html table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. for it to work well, the table really needs both column and row headers. ...
Test your skills: Conditionals - Learn web development
rinted to the output panel. you need to create an if...else structure that checks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on. inside the first, you need to nest an if...else if...else that puts appropriate messages into the response variable depending on what the value of score is — if the machine is
turned on. the different conditional tests (and resulting responses) are as follows: score of less than 0 or more than 100 — "this is not possible, an error has occurred." score of 0 to 19 — "that was a terrible score — total fail!" score of 20 to 39 — "you know some things, but it's a pretty bad score. needs improvement." score of 40 to 69 — "you did a passable job, not bad!" score o...
Test your skills: Loops - Learn web development
previous task. download the starting point for this task to work in your own editor or in an online editor. loops 3 in this final task, you are provided with the following: i — starts off with a value of 500; intended to be used as an iterator. para — contains a reference to a paragraph, which will be used to report the results. isprime() — a function that, when passed a number, re
turns true if the number is a prime number, and false if not. you need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and run the provided isprime() function on them. for each number that isn't a prime number, continue on to the next loop iteration. for each one that is a prime number, add it to the paragraph's textcontent along with some kind of sep...
Client-side web APIs - Learn web development
ry powerful graphics programming tools, from the scalable vector graphics (svg) language, to apis for drawing on html <canvas> elements, (see the canvas api and webgl). this article provides an introduction to the canvas api, and further resources to allow you to learn more. video and audio apis html5 comes with elements for embedding rich media in documents — <video> and <audio> — which in
turn come with their own apis for controlling playback, seeking, etc. this article shows you how to do common tasks such as creating custom playback controls. client-side storage modern web browsers feature a number of different technologies that allow you to store data related to web sites and retrieve it when necessary allowing you to persist data long term, save sites offline, and more. this arti...
JavaScript First Steps - Learn web development
cle we will get down to the real basics, looking at how to work with the most basic building blocks of javascript — variables. basic math in javascript — numbers and operators at this point in the course we discuss maths in javascript — how we can combine operators and other features to successfully manipulate numbers to do our bidding. handling text — strings in javascript next we'll
turn our attention to strings — this is what pieces of text are called in programming. in this article we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in string, and joining them together. useful string methods now we've looked at the very basics of strings, let's move up a gear and start thinking a...
Adding features to our bouncing balls demo - Learn web development
ff the edge of the screen, and stop it from doing so. again, you can mostly just copy the ball.prototype.update definition, but there are a few changes you should make: get rid of the last two lines — we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below. inside the if() statements, if the tests re
turn true we don't want to update velx/vely; we want to instead change the value of x/y so the evil circle is bounced back onto the screen slightly. adding or subtracting (as appropriate) the evil circle's size property would make sense. setcontrols() this method will add an onkeydown event listener to the window object so that when certain keyboard keys are pressed, we can move the evil circle aro...
Object building practice - Learn web development
rt (the area that the webpage appears on — this can be gotten from the window.innerwidth and window.innerheight properties). note that we are chaining multiple assignments together, to get the variables all set quicker — this is perfectly ok. the last bit of the initial script looks as follows: function random(min, max) { const num = math.floor(math.random() * (max - min + 1)) + min; re
turn num; } this function takes two numbers as arguments, and re
turns a random number in the range between the two. modeling a ball in our program our program will feature lots of balls bouncing around the screen. since these balls will all behave in the same way, it makes sense to represent them with an object. let's start by adding the following constructor to the bottom of our code. function ba...
Test your skills: Object basics - Learn web development
dinfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 3 finally for our object basics assessment, we want you to re
turn to the cat object literal from task #1. we want you to rewrite the greeting() method so that it logs "hello, said bertie the cymric." to the browser devtools' console, but in a way that will work across any cat object of the same structure, regardless of its name or breed. when you are done, write your own object called cat2, which has the same structure, exactly the same greeting() method, but ...
JavaScript — Dynamic client-side scripting - Learn web development
ch as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features,
turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. introducing javascript objects in javascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javas...
Aprender y obtener ayuda - Learn web development
ty properties, or the javascript date.settime() method, you should just search for the feature's name. if you are looking for some more specific information, you can add other keywords as modifiers, for example "<video> element autoplay attribute", or "date.settime parameters". if you want to search for something that has less obvious buzzwords, you need to think about what is most likely to re
turn what you want. run code after several promises are fulfilled play a video stream from a webcam in the browser create a linear gradient in the background of your element error messages if you are having a problem with some code and a specific error message is coming up, it is often a good idea to just copy the error message into your search engine and use it as the search term. if other pe...
CSS performance optimization - Learn web development
and then repainting it once styles are parsed would be bad user experience. for this reason, css is render blocking, unless the browser knows the css is not currently needed. the browser can paint the page once it has downloaded the css and built the css object model. browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in
turn requires both the dom and the cssom trees. to optimize the cssom construction, remove unnecessary styles, minify, compress and cache it, and split css not required at page load into additional files to reduce css render blocking. optimizing for render blocking css can scope styles to particular conditions with media queries. media queries are important for a responsive web design and help us op...
What is web performance? - Learn web development
ond, 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 above, you really should understand some specifics about how browsers work. this includes: how the browser works. when you request a url and hit enter / re
turn, the browser finds out where the server is that holds that website's files, establishes a connection to it, and requests the files. see populating the page: how the browser works for a detailed overview. source order. your html index file's source order can significantly affect performance. the download of additional assets linked to from the index file is generally sequential, based on source o...
The "why" of web performance - Learn web development
y affect the performance of the finished work. good performance is an asset. bad performance is a liability. site speed directly affects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. performant sites have been shown to increase visitor retention and user satisfaction. slow content has been shown to lead to site abandonment, with some visitors leaving to never re
turn. reducing the amount of data that passes between the client and the server lowers the costs to all parties. reducing html/css/javascript and media file sizes reduces both the time to load and a site's power consumption (see performance budgets). tracking performance is important. multiple factors, including network speed and device capabilities affect performance. there is no single performance ...
Website security - Learn web development
. when the attacker has the cookie, they can log into a site as though they were the user and do anything the user can, such as access their credit card details, see contact details, or change passwords. note: xss vulnerabilities have been historically more common than any other type of security threat. the xss vulnerabilities are divided into reflected and persistent, based on how the site re
turns the injected scripts to a browser. a reflected xss vulnerability occurs when user content that is passed to the server is re
turned immediately and unmodified for display in the browser. any scripts in the original user content will be run when the new page is loaded. for example, consider a site search function where the search terms are encoded as url parameters, and these terms are displa...
Ember resources and troubleshooting - Learn web development
mon 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(); re
turn { 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 other form of dom creation, there has yet to be anything as robust as ember's templating system. the intentional m...
Beginning our React todo list - Learn web development
ioned above, you’ll have to start it again using npm start. project starter code as a starting point for this project, we're going to provide two things: an app() function to replace the one you have now, and some css to style your app. ...
Starting our Svelte Todo list app - Learn web development
n, css: css => { css.write('public/build/bundle.css'); }, // warnings are normally passed straight to rollup. you can // optionally handle them here, for example to squelch // warnings with a particular code onwarn: (warning, handler) => { // e.g. i don't care about screen readers -> please don't do this!!! if (warning.code === 'a11y-missing-attribute') re
turn; // let rollup handle all other warnings normally handler(warning); } }), ... ] by design, these warnings are implemented in the compiler itself, and not as a plug-in that you may choose to add to your project. the idea is to check for a11y issues in your markup by default and let you opt-out of specific warnings. note: you should only disable these warnings if you have ...
Deployment and next steps - Learn web development
also consult the svelte api docs and the available examples. to understand the motivations behind svelte, you should read rich harris's rethinking reactivity presentation on youtube. he is the creator of svelte, so he has a couple of things to say about it. you also have the interactive slides available here which are, unsurprisingly, built with svelte. if you liked it, you will also enjoy the re
turn of 'write less, do more' presentation, which rich harris gave at jscamp 2019. related projects there are other projects related to svelte that are worth checking out: sapper: an application framework powered by svelte that provides server-side rendering (ssr), code splitting, file-based routing and offline support, and more. think of it as next.js for svelte. if you are planning to develop a...
Using Vue computed properties - Learn web development
s. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously. adding a summary counter add the following code to your app component object, below the methods property. the list summary method will get the number of finished todoitems, and re
turn a string reporting this. computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length re
turn `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. we'll also add an id and an aria-labelledby attribute to...
Focus management with Vue refs - Learn web development
s. since the focusoneditbutton() method needs to be invoked after the dom has updated, we can wrap the existing function body inside a $nexttick() call. focusoneditbutton() { this.$nexttick(() => { const editbuttonref = this.$refs.editbutton; editbuttonref.focus(); }); } now when you activate the "edit" button and then cancel or save your changes via the keyboard, focus should be re
turned to the "edit" button. success! vue lifecycle methods next, we need to move focus to the edit form’s <input> element when the "edit" button is clicked. however, because our edit form is in a different component to our "edit" button, we can't just set focus inside the "edit" button’s click event handler. instead, we can use the fact that we remove and re-mount our todoitemeditform component...
Vue resources - Learn web development
a specific guide on how to publish your app to many of the common hosting platforms. vue 3 vue 3 is a major release of the framework with a lot of major changes. it went into active beta in april, 2020. the biggest change is a new composition api that works as an alternative to the current property-based api. in this new api, a single setup() function is used on the component. only what you re
turn from this function is available in your <template>s. you are required to be explicit about "reactive" properties when using this api. vue handles this for you using the options api. this makes the new api typically considered a more advanced use case. there are also a handful of other changes, including a change in how apps are initialized in vue. to read more about the changes involved with vue...
Styling Vue components with CSS - Learn web development
template to connect the styles. to the root <div>, add a custom-checkbox class. to the <input>, add a checkbox class. last of all, to the <label> add a checkbox-label class. the updated template is below: the app should now have custom checkboxes. your app should look something like the screenshot below. summary our work is done on the styling of our sample app. in the next article we'll re
turn to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react intera...
Cross browser testing - Learn web development
problems, and more. handling common javascript problems now we'll look at common cross-browser javascript problems and how to fix them. this includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern javascript features working in older browsers, and more. handling common accessibility problems next we
turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues. implementing feature detection feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser ca...
Command line crash course - Learn web development
ion of the page. if you enter it in a new browser tab, you’ll (eventually) get redirected to /docs/web/api/windoworworkerglobalscope/fetch. therefore, if you use curl to request /docs/web/api/fetch, you won’t get an output. try it now: curl /docs/web/api/fetch we need to explicitly tell curl to follow redirects using the -l flag. let's also look at the headers that developer.mozilla.org re
turns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we will ask grep to re
turn all the lines that contain the word "location"). try running the following, and you’ll see that in fact there are three redirects happening before we reach the final page: curl /docs/web/api/fetch -l -i | grep location your output should loo...
Client-side tooling overview - Learn web development
a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently. from a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve: safety net — tools that are useful during your code development. transformation — tools that transform code in some way, e.g.
turning an intermediate language into javascript that a browser can understand. post-development — tools that are useful after you have written your code, such as testing and deployment tools. let's look at each one of these in more detail. safety net these are tools that make the code you write a little better. this part of the tooling should be specific to your own development environment, t...
Accessibility information for UI designers and developers
that do something (like submit a form or open an overlay). links can be styled as buttons and vice versa, but designers are advised to avoid this where possible. motion on pages with transitions and animations, note that some users could experience distraction, dizziness or nausea. pages with a parallax effect can particularly cause troubles. to help these users, you could offer a setting to
turn off animations, or wrap the css in the prefers-reduce-motion media query. see also: understanding success criterion 2.3.3: animation from interactions content on hover or focus if content is revealed on hover or focus, for example in tooltips, there are some things to keep in mind: if the extra content obscures existing content, there should be a way to close it without moving focus if the...
Embedding API for Accessibility
nmode: "normal", "none", "once" moz 0.8 applets setboolpref("browser.accept.applets", acceptapplets); no scripts setboolpref("browser.accept.scripts", acceptscripts); no popup windows //
turn window.open off for particular sites: user_pref("capability.policy.popupsites.sites", "http://www.annoyingsite1.com http://www.popupsite2.com"); user_pref("capability.policy.popupsites.windowinternal.open","noaccess"); // or
turn it off everywhere: user_pref("capability.policy.defa...
Multiprocess on Windows
elibs that are already registered in the system registry will automatically be available for use by the interceptor. this is great for system interfaces, but for interfaces that are specific to gecko, it is better to register them at runtime. the mscom library provides an api for doing this: the registerproxy and registertypelib functions in mozilla/mscom/registration.h. both of these functions re
turn unique pointers and should be treated as opaque by the caller. save them to a location where they will be able to exist for the lifetime of the process. if your typelib is embedded in a proxy's resources, then use registerproxy(). this is the preferred mechanism, as it will register both your oicf and typelib metadata. if you have a standalone .tlb file that you need to register, then use regist...
Theme concepts
: { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#fff', } } }; the theme.theme object is then passed to theme.update() to change the header theme, as in this code snippet from the same example: function settheme(theme) { if (currenttheme === theme) { // no point in changing the theme if it has already been set. re
turn; } currenttheme = theme; browser.theme.update(themes[theme]); } learn more about dynamic themes and see an additional example in the following video: if you have not built a browser extension before, check out your first extension for a step-by-step guide. cross-browser compatibility there is currently limited compatibility between themes in the major browsers. opera takes an entire...
Adding a new CSS property
ou know which struct you're going to use (or that the property is a shorthand), you can add appropriate entry to nscssproplist.h. again, see the documentation at the top of the file and the other entries for examples, and also see the next section for details about parsing. parsing to start implementing the parsing, first read the syntax line in the property's specification (whose syntax is in
turn defined in the css values and units specification) and any prose in the specification that adds additional restrictions to that syntax. every property in nscssproplist.h must have in its flags field exactly one of the four css_property_parse_* flags defined in nscssprops.h. given the syntax for the property, you can determine which one to use. if the property's values can be expressed as a sin...
Browser chrome tests
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 re
turned. call finish() once the test is complete. be aware that the test harness will mark tests that take too long to complete as failed (the current timeout is 30 seconds). function test() { waitforexplicitfinish(); settimeout(completetest, 1000); } function completetest() { ok(true, "timeout ran"); finish(); } if your test is randomly timing out and you think that's just due to i...
Continuous Integration
x for android; these suites are denoted using lower-case letters, e.g., t(c d g1 o s tp). the talos indicators in treeherder appear green if the job successfully completed; to see the performance data generated by the jobs, click on the performance tab of the job details panel that pops up when you click on a job in treeherder. each talos suite contains a set of tests or pages, some of these in
turn have sub-tests. each test is executed multiple times to produce a number of data replicates. the talos harness produces a single number per test (typically the median of all the replicates excluding the first 1-5), which are stored in treeherder's database, and are accessible via the perfherder interface. other performance systems autophone (android) autophone is a test harness which runs a...
Creating a Login Manager storage module
in nsiloginmanagerstorage _xpcom_categories: [ { category: "login-manager-storage", entry: "nsiloginmanagerstorage" } ], // console logging service, used for debugging. __logservice : null, get _logservice() { if (!this.__logservice) this.__logservice = cc["@mozilla.org/consoleservice;1"]. ...
Debugging JavaScript
at a line using the keyword debugger. in debug builds this also dumps a stack trace to the console, even when the debugger is not running. ...
Debugging OpenGL
up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this. if the context isn't current, the call aborts. every time an opengl call completes, glfinish() gets run automatically. this flushes out each call, essentially
turning opengl into a synchronous api. this makes debugging crashes caused by an opengl call much easier, since the stack you see will match where the call was issued, rather than some time in the future when it happens to run and crash. if an opengl error occurred when executing the call, an error message is output. note: you can download debug builds from mozilla taskcluster — click an appropr...
Debugging Safari
to enable the very useful debug menu in safari use the following: defaults write com.apple.safari includeinternaldebugmenu 1 it is often useful to switch into single process mode by
turning off "use multi-process windows" ...
Debugging on Mac OS X
we have to add 1 to correct for # that! :-( dummy_bp_list = lldb.sbbreakpointlist(target) debugger.getdummytarget().findbreakpointsbyname("nsthread::processnextevent", dummy_bp_list) dummy_bp_id = dummy_bp_list.getbreakpointatindex(0).getid() + 1 debugger.getdummytarget().breakpointdelete(dummy_bp_id) # "source" the mozill...
Debugging
failures. detecting defects in firefox with coverity coverity is a static analysis system that can detect defects in firefox. gecko logging using old-school logging to try to track down what's going on. debugging specific parts of the mozilla codebase debugging opengl if you're working on code that involves opengl calls, and need to debug it, you can
turn on a special opengl debugging mode. debugging frame reflow and debugging table reflow notes on debugging issues in gecko's layout engine. miscellaneous debugging safari some tips for debugging safari debugging chrome some tips for debugging chrome debugging internet explorer some tips for debugging internet explorer providin...
Configuring Build Options
disk. parallel compilation note: the build system automatically makes an intelligent guess for how many cpu cores to use when building. the option below is typically not needed. most modern systems have multiple cores or cpus, and they can be optionally used concurrently to make the build faster. the -j flag controls how many parallel builds will run concurrently. you will see (diminishing) re
turns up to a value approximately 1.5× to 2.0× the number of cores on your system. mk_add_options moz_make_flags="-j4" if your machine is overheating, you might want to try a lower value, e.g. -j1. choose an application the --enable-application=application flag is used to select an application to build. firefox is the default. choose one of the following options to add to your mozconfig file: ...
Makefiles - Best practices and suggestions
targets = foo bar tans timestampdir = .ts all: $(timestampdir) $(targets) %: %.c $(cc) -o $@ $< $(timestampdir): $(mkdir) $@ # "clean" target garbage += $(targets) garbage_dirs += $(timestampdir) wrapper check/unit tests with a enable_tests conditional so tests can be disabled on demand. ifdef enable_tests ifeq ($(null),$(filter w...
Eclipse CDT
use the context menu for the 'layout' directory in the project explorer tab to open the directory's properties. you'd select "c/c++ general > prepocessor include paths, macros etc.", and select "gnu c++" and "cdt user settings entries". you'd then click "add", select "preprocessor macro" from the drop-down, and set name to _impl_ns_layout and leave value blank. finally, you'd click ok twice to re
turn to the main eclipse window, and then use the context menu for the 'layout' directory to re-index the 'layout' directory, and then to "run c/c++ code analysis" on it to see if the problem is fixed. this "parse once" strategy can also cause "unresolved inclusion" errors in headers if the first time eclipse sees the header is while indexing a file for which it doesn't have any build output parser d...
Gecko Logging
d. this should not be used directly in code. error 1 an error occurred, generally something you would consider asserting in a debug build. warning 2 a warning often indicates an unexpected state. info 3 an informational message, often indicates the current program state. debug 4 a debug message, useful for debugging but too verbose to be
turned on normally. verbose 5 a message that will be printed a lot, useful for debugging program flow and will probably impact performance. example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int st...
Multiple Firefox profiles
ou have the path to your desired profile handy, enter a space character, followed by -profile followed by another space character, followed by the full path to the profile folder you wish to launch into. this will launch firefox immediately. otherwise, enter a space character followed by --profilemanager. this will present the profile manager window in which you can make your selection. hit re
turn. here is a complete example terminal command from steps 2-3: /applications/firefox.app/contents/macos/firefox -profile /users/suzie/library/application\ support/firefox/profiles/r99d1z7c.default if the profile manager window does not open, firefox may have been running in the background, even though it was not visible. close all instances of firefox, or restart the computer, and then try ag...
Process scripts
achieved by traversing the docshell tree up to the top window and then retrieving its content message manager, as follows: function contentmmfromcontentwindow(window) { let tree = window.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidocshelltreeitem); let top = tree.sametyperoottreeitem; let iface = queryinterface(ci.nsidocshell).queryinterface(ci.nsiinterfacerequestor); re
turn iface.getinterface(ci.nsicontentframemessagemanager); } this is intended for unprivileged pages running in a content process. chrome-privileged pages or things running in the parent process may require special treatment. if the above doesn't work try this: function contentmmfromcontentwindow_method2(acontentwindow) { re
turn acontentwindow.queryinterface(ci.nsiinterfacerequestor) ...
Storage access policy: Block cookies from trackers
d other site storage when they are loaded in a third-party context. this prevents those resources from retrieving tracking identifiers stored in cookies or site storage and using them to identify users across visits to multiple first parties. specifically, firefox does this by imposing the following restrictions: cookies: block cookie request headers and ignore set-cookie response headers. re
turn an empty string for calls to document.cookie and ignore requests to set cookies via document.cookie. dom storage: localstorage: window.localstorage: read and write attempts throw a securityerror exception. prior to firefox 70: window.localstorage is null. thus, attempts to read and write using this object will throw a typeerror exception. sessionstorage: read and write attempts are permitt...
Firefox and the "about" protocol
see firefox reader view for clutter-free web pages about:rights displays rights information about:robots special page showing notes about robots about:serviceworkers displays currently running service workers about:studies lists the shield studies that are installed about:sessionrestore session restoration (displayed after a firefo...
HTMLIFrameElement.addNextPaintListener()
of the htmliframeelement is used to define a handler to listen for the next mozafterpaint event coming from the browser <iframe>. this event provides information about what has been repainted. it is mainly used to investigate performance optimization. note: the handler will receive the event once and then be thrown away. syntax instanceofhtmliframeelement.addnextpaintlistener(listener); re
turns void. parameters listener a function handler to listen for a mozafterpaint event. examples var browser = document.queryselector('iframe'); function onnextpaint() { console.log("paint has occured"); } browser.addnextpaintlistener(onnextpaint); specification not part of any specification. ...
HTMLIFrameElement.clearMatch()
content highlighted by findall() or findnext(). invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.clearmatch(); re
turns void. parameters none. examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. see implementing the search bar for more explanation. searchtoggle.addeventlistener('touchend',function() { if(search.getattribute('class') === 'search') { search.setattribute('c...
HTMLIFrameElement.download()
its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. parameters url the url of the file to be downloaded. ...
HTMLIFrameElement.findAll()
will be highlighted. invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findall(searchstring, casesensitivity); re
turns void. parameters searchstring the string you want to search for in the browser <iframe>'s text. casesensitivity a string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) example the following function is taken from our browser api demo, and executes a search when a search form is submitted. see implementing the search bar ...
HTMLIFrameElement.findNext()
a findall() search has been carried out. invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.findnext(direction); re
turn value void. parameters direction a string indicating the direction in which you want to cycle through the available search results. available values are forward and backward. examples the following functions are taken from our browser api demo, and cycle through the available search results. see implementing the search bar for more explanation. prev.addeventlistener('touchend',function(...
HTMLIFrameElement.getActive()
ack. 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 getactive() method of the htmliframeelement indicates whether the current browser <iframe> is the currently active frame. syntax var amiactive = instanceofhtmliframeelement.getactive(); re
turns a boolean indicating whether the current browser <iframe> is the currently active frame (true) or not (false.) parameters none. example var browser = document.queryselector('iframe'); var amiactive = browser.getactive(); specification not part of any specification. ...
HTMLIFrameElement.getCanGoBack()
will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the getcangoback() method of the htmliframeelement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. syntax instanceofhtmliframeelement.getcangoback() .then(function(result) { ... }); re
turns a promise that resolves with a boolean that equals true if the history can be navigated backward or false if not. parameters none. 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; ...
HTMLIFrameElement.getCanGoForward()
will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the getcangoforward() method of the htmliframeelement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. syntax instanceofhtmliframeelement.getcangoforward() .then(function(result) { ... }); re
turns a promise that resolves with a boolean that equals true if the history can be navigated forward or false if not. parameters none. example function canmovefwd() { browser.getcangoforward().then(function(result) { if (result) { fwd.disabled = false; console.log("it's possible to navigate the history forward."); } else { fwd.disabled = true; ...
HTMLIFrameElement.getManifest()
warning: removed in firefox 65. the getmanifest() method of the htmliframeelement interface retrieves the manifest of an app loaded in the browser <iframe> and re
turns it as json. syntax instanceofhtmliframeelement.getmanifest().then(function(json) { ... }); parameters none. re
turn value a promise that resolves to a json object representation of the loaded app's manifest. examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getmanifest().then(function(json) { console.log(json); }); }); specification not part of any specification. ...
HTMLIFrameElement.getMuted()
tween implementations and the behavior may change in the future. the getmuted() method of the htmliframeelement indicates whether the browser <iframe> is currently muted. syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getmuted(); and a promise version: instanceofhtmliframeelement.getmuted().then(function(muted) { ... }); re
turns callback version: a domrequest that represents the get muted request. it has an onsuccess handler to handle the success case, and an onerror handler to handle the failure case. the muted value is available in the request.result property, and is a boolean value — true means muted, and false means unmuted. promise version: a promise that resolves with the muted value — a boolean where true...
HTMLIFrameElement.getVisible()
ck. 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 getvisible() method of the htmliframeelement is used to request the current visible state of the browser <iframe>. syntax instanceofdomrequest = instanceofhtmliframeelement.getvisible(); re
turns a domrequest object to handle the getvisible() request's success and error cases. if the request is successful, the request's result is a boolean indicating the visible state of the browser <iframe>. parameters none. example var browser = document.queryselector('iframe'); var request = browser.getvisible(); request.onsuccess = function() { console.log('the visible state is: ' + ...
HTMLIFrameElement.getVolume()
ies between implementations and the behavior may change in the future. the getvolume() method of the htmliframeelement gets the current volume of the browser <iframe>. syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getvolume(); and a promise version: instanceofhtmliframeelement.getvolume().then(function(volume) { ... }); re
turns callback version: a domrequest that represents the get volume request. it has an onsuccess handler to handle the success case, and an onerror handler to handle the failure case. the volume value is available in the request.result property, and is a floating point number between 0 and 1. promise version: a promise that resolves with the volume value — a floating point number between 0 and 1...
HTMLIFrameElement.goBack()
the goback() method of the htmliframeelement interface is used to navigate backwards in the browser <iframe>'s history. by calling this method, the browser <iframe> changes its location for the previous location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart, and so on. syntax instanceofhtmliframeelement.goback(); re
turns void. parameters none. examples back.addeventlistener('touchend',function() { browser.goback(); }); specification not part of any specification. ...
HTMLIFrameElement.goForward()
ture. the goforward() method of the htmliframeelement is used to navigate forward in the browser <iframe>'s history. by calling this method, the browser <iframe> changes its location to the next location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart and so on. syntax instanceofhtmliframeelement.goforward(); re
turns void. parameters none. examples fwd.addeventlistener('touchend',function() { browser.goforward(); }); specification not part of any specification. ...
mozbrowserasyncscroll
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: top the scroll top position in css pixels of the document within the browser <iframe>. left the scroll left position in css pixels of the document within the browser <iframe>. width the width in css pixels of the visible part of the document within the browser <iframe>. height the height in css pixels of the visible part of ...
mozbrowsercaretstatechanged
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: rect an object that defines information about the bounding rectangle of the current selection. its properties are width: the width of the bounding rectangle, in css pixels. height: the height of the bounding rectangle, in css pixels. top: the top position of the bounding rectangle, in css pixels. bottom: the bottom posit...
mozbrowsererror
ption 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. detail the detail property re
turns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred. possible values are: fatal(crash) unknownprotocolfound filenotfound dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirectloop unknownsockettype net...
mozbrowsericonchange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon. sizes a domstring listing the sizes the new icon is available in, e.g. "16x16" or "16x16 32x32". 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. example v...
mozbrowserloadend
ption 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. detail the detail property re
turns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value. can be used to make the theme of the surrounding ui complement the theme of the currently loaded content, for example. example in this example the mozbrowserloadstart and mozbrowserloadend events are us...
mozbrowserlocationchange
ption 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. detail the detail property re
turns an anonymous javascript object with the following properties: url a domstring representing the url of the new location. cangoback a boolean that defines whether it's possible to go back in the navigation history (true) or not (false). cangoforward a boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). example this example updates th...
mozbrowsermanifestchange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: href the url of the new app manifest. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermanifestchange", function(event) { console.log("new manifest url: " + event.details.href); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchang...
mozbrowseropensearch
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine. href a domstring representing url of the search engine. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropensearch", function( event ) { console.log("new search engine encountered: " + event.details.title); }); relat...
mozbrowseropentab
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll...
mozbrowseropenwindow
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property. name a domstring representing the name of the new browser window. features a domstring containing features represented by a list of names and values separated by commas. for a complete list of possible features, see window.open(). fr...
mozbrowserresize
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels. height a number representing the new height of the <iframe> viewport, in device pixels. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserresize", function( event ) { console.log("the new window s...
mozbrowserscroll
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport. left a number representing the new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport. example var browser = document.queryselector("ifram...
mozbrowserscrollareachanged
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels. height a number representing the new scroll area height of the <iframe> viewport, in css pixels. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollareachanged", function( event ) { ...
mozbrowserscrollviewchange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollviewchange", function( event ) { console.log("scrolling has " + event.details.state + "."); }); related...
mozbrowsersecuritychange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security. possible values are: broken: indicates an unknown security state. this may mean that the request is being loaded as part of a page in which some content was received over an insecure channel. secure: indicates that the data corresponding to the request was rec...
mozbrowserselectionstatechanged
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: rect an object that represents the bounding rectangle of the selection. its properties are: width: the width of the selection, in css pixels. height: the height of the selection, in css pixels. top: the y coordinate of the top of the bounding box, in css pixels. bottom: the y coordinate of the bottom of the bounding box,...
mozbrowsershowmodalprompt
details property is an anonymous javascript object with the following properties: prompttype a domstring defining the type of the prompt. it can be alert, confirm, or prompt. title a domstring representing the title of the prompt. message a domstring representing the value passed to the window.alert(), window.confirm(), or window.prompt() methods within the browser <iframe>'s content. re
turnvalue a domstring representing the re
turn value for the window.prompt() methods. this should be set by the embedder. unblock() a function to be called when the iframe is unblocked. note that if the embedder calls preventdefault() on this event, the iframe is blocked until unblock() is called. obsolete properties of details msg_name a string representing the type of message. for that event...
mozbrowserusernameandpasswordrequired
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification. realm a domstring representing the value of the realm http header. isproxy a boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false). authenticate() a function that is called to enable the authentic...
mozbrowservisibilitychange
ion 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. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property re
turns an anonymous javascript object with the following properties: visible a boolean that indicates whether the browser iframe is visible (true) or not (false). example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("the browser is visible."); } else { console.log("t...
HTMLIFrameElement.mute()
his 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 mute() method of the htmliframeelement mute any audio playing in the browser <iframe>. syntax instanceofhtmliframeelement.mute(); re
turns void. parameters none. example var browser = document.queryselector('iframe'); browser.mute(); specification not in a specification. ...
HTMLIFrameElement.purgeHistory()
ith the browser <iframe>. it only deletes history, not cookies or other stored information. note: to delete cookies for a firefox os app, you could call clearbrowserdata() on the actual app itself. syntax there is a domrequest version and a promise version: var mydomrequest = instanceofhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ... }); re
turns either a domrequest object that re
turns an onsuccess handler if the history is deleted, or an onerror handler if not. a promise that resolves, with no parameters, if the history is deleted, or rejects if not. parameters none. examples domrequest: var browser = document.queryselector('iframe'); var request = browser.purgehistory(); request.onsuccess = function() { console.log('histo...
HTMLIFrameElement.reload()
dard 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 reload() method of the htmliframeelement interface is used to reload the content of the <iframe>. syntax instanceofhtmliframeelement.reload(hardreload); re
turns void. parameters hardreload optional a boolean that indicates whether all the resources to reload must be revalidated (true) or may be taken directly from the browser cache (false). examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification.
HTMLIFrameElement.sendMouseEvent()
ere may also be large incompatibilities between implementations and the behavior may change in the future. the sendmouseevent() method of the htmliframeelement interface allows you to fake a mouse event and send it to the browser <iframe>'s content. syntax instanceofhtmliframeelement.sendmouseevent(type, x, y, button, clickcount, modifiers); re
turns void. parameters type a string representing the event type. possible values are mousedown, mouseup, mousemove, mouseover, mouseout, or contextmenu. x a number representing the x position of the cursor relative to the browser <iframe>'s visible area in css pixels. y a number representing the y position of the cursor relative to the browser <iframe>'s visible area in css pixels. button ...
HTMLIFrameElement.sendTouchEvent()
sendtouchevent() method of the htmliframeelement allows you to fake a touch event and send it to the browser <iframe>'s content. note: this method is available for touch-enabled devices only. syntax instanceofhtmliframeelement.sendtouchevent(type, x, y, rx, ry, rotationangles, forces, count, modifiers); re
turns void. parameters type a string representing the event type. possible values are touchstart, touchend, touchmove, or touchcancel. x an array of numbers representing the x position of each touch point relative to the browser <iframe>'s visible area in css pixels. y an array of numbers representing the y position of each touch point relative to the browser <iframe>'s visible area in css p...
HTMLIFrameElement.setActive()
ion 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 setactive() method of the htmliframeelement sets the current <iframe> as the active frame, which has an effect on how it is prioritized by the process manager. syntax instanceofhtmliframeelement.setactive(boolean); re
turns void. parameters boolean a boolean that indicates whether the iframe is to be the active frame (true) or not (false). example var browser = document.queryselector('iframe'); browser.setactive(); specification not part of any specification. ...
HTMLIFrameElement.setVisible()
an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to true, window.requestanimationframe will be called as often as necessary. however, if the visible state is set to false, window.requestanimationframe will be called only when there are free resources to do it. syntax instanceofhtmliframeelement.setvisible(visible); re
turns void. parameters visible a boolean that indicates if the browser <iframe> visible state is true or false. examples var browser = document.queryselector('iframe'); browser.setvisible(true); specification not part of any specification. ...
HTMLIFrameElement.setVolume()
n-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 setvolume() method of the htmliframeelement sets the current volume of the browser <iframe>. syntax instanceofhtmliframeelement.setvolume(number); re
turns void. parameters number a floating point number representing the volume you want to set — this can have a value between 0 and 1. example var browser = document.queryselector('iframe'); browser.setvolume(0.5); specification not part of any specification. ...
HTMLIFrameElement.stop()
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 stop() method of the htmliframeelement interface is used to stop loading the content of the <iframe>. syntax instanceofhtmliframeelement.stop(); re
turns void. parameters none. examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification. ...
HTMLIFrameElement.unmute()
ture 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 unmute() method of the htmliframeelement unmutes any audio playing in the browser <iframe>. syntax instanceofhtmliframeelement.unmute(); re
turns void. parameters none. example var browser = document.queryselector('iframe'); browser.unmute(); specification not part of any specification. ...
Embedding the editor
htmlarea>, a floating palette, or a top-level toolbar. current problems the current composer architecture was created while other parts of mozilla were still under development, and as a result it suffers from a number of shortcomings, and anachronisms. this section describes its major faults. editor incorrectly rooted the editor in a composer window is current owned by the nseditorshell, which in
turn is created, owned and destroyed by the nseditorboxobject. the box object is a layout structure that is owned by content nodes, and survives frame destruction/recreation. the box object also has a reference to the docshell for the editor frame. xbl creates an nseditorboxobject for each <editor> tag, and allows javascript to access properties of this box object (such as the nsieditorshell). the <ed...
Gecko SDK
be accessed from xul using javascript. note that in order to develop such components, you do not need the full sources of e.g. firefox, since you do not access parts of the front end from within a component. furthermore, since a component contains basic functionality, it is intended to run with every product of the mozilla platform. therefore it makes no sense to use a particular product to build general functionality. that's the reason why the gecko sdk was devised. ...
How Mozilla determines MIME Types
ension, and is asked for the mime type if no plugin is registered, the ext-to-type-mapping xpcom category is searched for the extension. this allows extensions to register additional mappings. the key of the category entry is the extension without leading dot, the value is the mime type. the extension must be lowercase. if no ext-to-type-mapping category is found, the externalhelperappservice re
turns application/x-extension-ext, where ext is the extension of the file. helper applications a somewhat related issue are the helper applications. when loading an uri with a type that mozilla can not handle, a helper app dialog shows up, and the displayed information comes from these sources: ask the os for a handler of the given <extension, mime type> pair. note that the extension here comes ...
How to get a stacktrace for a bug report
ed reports type "about:crashes" into the firefox address bar and press enter. firefox should open a list of ids for your submitted crash reports. copy two or three of the ids for the appropriate crashes and paste them into your bugzilla report. please check the listed times to avoid copying the id of an unrelated crash report. you can prefix a "bp-" to the beginning of an id to make bugzilla
turn it into a link: bp-a70759c6-1295-4160-aa30-bc4772090918 how to get the crash id if firefox crashes on startup if firefox crashes on startup you can still access your submitted crash reports. crash reports are accessible from all firefox profiles, so if a new profile does not crash you can use it to access them through "about:crashes" as above. accessing crash report ids ...
PBackground
dy is allowed to do long running computation or file i/o on it) to guarantee better latency than going through the main threads (which can run arbitrary js, gc, etc.) can provide. examples indexeddb was rebuilt on top of pbackground last year. this allows the dom code to generally not worry about what thread (main vs. worker) or process (single vs. multiple) it is running in. instead, it simply
turns all of its operations into ipdl calls on a set of pbackground-based actors and the processing, file i/o, etc, can be controlled from the pbackground thread regardless of where the dom calls are being made. the logic is all implemented in actorsparent.cpp and actorschild.cpp in the dom/indexeddb directory. these are not small files (actorsparent.cpp was over 27k lines of code as of this publicat...
Addon
ed in the package. boolean hasresource( in string path ) parameters path a "/" separated path for the resource. getresourceuri() gets an nsiuri to the file resource for this add-on. nsiuri getresourceuri( in string path ) parameters path a "/" separated path for the resource. getdatadirectory() requires gecko 32.0(firefox 32.0 / thunderbird 32.0 / seamonkey 2.29) re
turns the path of the preferred directory, within the current profile, where an add-on should store data files. if the directory does not already exist, it will be created. void getdatadirectory( in datadirectorycallback callback ) ...
AddonUpdateChecker
updateinfo getnewestcompatibleupdate( in updateinfo updates[], in string appversion, in string platformversion ) parameters updates an array of update objects appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current version checkf...
Assert.jsm
l message short explanation of the expected result throws() expected to throw an error. undefined throws( block, expected, message ); parameters block function block to evaluate and catch eventual thrown errors expected test reference to evaluate against the thrown result from block message short explanation of the expected result rejects() expected to reject a promise. re
turns a promise that resolves when the promise either resolves or rejects. promise rejects( promise, expected, message ); parameters promise promise promise to wait for rejection and catch eventual thrown errors expected test reference to evaluate against the thrown result from block message short explanation of the expected result greater() the greater than assertion tests two num...
API-provided widgets
he widget in private browsing mode (optional, default: true) event handlers you can also define several event handlers which will be called at various stages in a widget's lifetime: event handler name description onbuild(adoc) only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget. should re
turn the dom node that has been constructed. nb: the dom node you construct should have the same id as the id property described above, so that customizableui can find the node again later. onbeforecreated(adoc) attached to all non-custom widgets; a function that will be invoked before the widget gets a dom node constructed, passing the document in which that will happen. this is usefu...
DownloadTarget
whenever the download.refresh() method is called. you can use this value from the front-end to reduce file i/o that would be required to check the file directly. methods refresh() updates the state of a finished, failed, or canceled download based on the current state as indicated by the file system. if the download is in progress or has been finalized, this method does nothing and re
turns a resolved promise. calling this method lets the download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents. promise refresh(); parameters none. promise resolves to undefined when the state of the download has been updated. promise can be rejected with never. ...
Downloads.jsm
anymore. the new module works differently from the old component. in general, you should be aware of the following highlights: there is no difference between active downloads and finished downloads. the download object can be used without requiring direct database access. observer notifications (for example, "dl-done") and download listeners are replaced by views on the downloadlist object re
turned by the getlist() method. object identity replaces the use of numeric identifiers. you can use download objects as keys in a set or map to associate your own state to them for the session. there is no separate count of active downloads. if a count is needed, it should be maintained using a view on a downloadlist. the start() method can be used to restart a failed download. handling of downloa...
Http.jsm
as the content type. http.jsm only forces the content type if the post data is an array, and it serializes it automatically. if the provided postdata is a string, the content type isn't touched. in this case, the content type may be set through the headers parameter. additional xhr configuration it is possible to modify things manually on the xhr object after calling httprequest. httprequest re
turns an xhr object, which can be used to set additional parameters for the request. for example, xhr might be configured to use any custom mime-type when processing a response regardless of what the server re
turns. to achieve this, you can obtain an xhr object by calling httprequest and then call its overridemimetype() with a preferred mime-type. another example of how this can be used can be found h...
ISO8601DateUtils.jsm
; to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g. "2010-05-15t13:45:00z", from a javascript date object. string create( adate ); parameters adate a javascript date object to translate into an iso 8601 format string. re
turn value an iso 8601 format date string. parse converts an iso 8601 format date string into a javascript date object. date parse( adatestring ); parameters adatestring an iso 8601 format date string. re
turn value a javascript date object corresponding to the specified date string. ...
OS.File.Error
.. } catch (ex) { if (ex instanceof os.file.error && ex.becausenosuchfile) { // the file does not exist } } global object os.file.error methods overview the following functions are utility functions that may be used to construct instances of os.file.error, setting the platform-specific error number. error closed() error exists() methods os.file.error.closed() re
turn an error representing the fact that a file is closed. os.file.error.exists() re
turn an error representing the fact that a file exists. instances of os.file.error in case of any i/o error, the functions of os.file raise instances of os.file.error. these exceptions hold both a human-readable error message detailing the i/o error and attributes to help determining the cause of the error. cross-platf...
PerfMeasurement.jsm
constructor creates a new perfmeasurement object, configured to record the specified event types. perfmeasurement( eventmask tomeasure ); parameters tomeasure a mask of all of the event types you want to record; see event mask constants for a list of values. or together all the event types you want to record, and pass that value here. pass perfmeasurement.all to record all event types. re
turn value a new perfmeasurement object configured to record the specified event types. methods canmeasuresomething() indicates whether or not the platform on which your code is running supports this code module. static bool canmeasuresomething(); parameters none. re
turn value if even one of the event types can be recorded, this will re
turn true. otherwise, it re
turns false. reset() resets all the en...
Deferred
method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state. methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is exactly same as promise constructor's resolve argument, and can be called with any value of this. ...
PromiseUtils.jsm
odules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise. this method was previously implemented as promise.defer(), which is obsolete since gecko 30. and promiseutils.defer uses dom promise instead of promise.jsm's promise. deferred defer(); parameters none. re
turn value a new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. see the deferred documentation for details. ...
Using JavaScript code modules
vascript code module is simply some javascript code located in a registered location. the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"](). creating a javascript code module a very simple javascript module looks like this: var exported_symbols = ["foo", "bar"]; function foo() { re
turn "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions, objects, constants, and any other javascript type. the module also defines a special array named exported_symbols. any javascript item named in exported_symbols will be exported from the module and injected into the importing scope. for example: component...
JavaScript code modules
easurement tools. pluralform.jsm supplies an easy way to get the correct plural forms for the current locale, as well as ways to localize to a specific plural rule. popupnotifications.jsm gives an easy way to present non-modal notifications to users. promise.jsm implements the promises/a+ proposal as known in april 2013. promiseworker.jsm a version of chromeworker which uses promises to re
turn the worker's result instead 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 ...
L10n testing with xcode
ver the button. to view these strings, you'll need to start the accessibility inspector within the ios simulator by doing the following. in the ios simulator, press the home button from the hardware toolbar menu. navigate to the settings app, open it, and go to general > accessibility. slide the accessibility inspector switch to on. the accessibility inspector remains active until you
turn it off, even if you quit and restart ios simulator. press the home button again, navigate to the pane with your firefox for ios localization on it, and reopen firefox. now, you can navigate through the firefox app in the ios simulator, viewing both ui elements and accessibility strings as you go. congratulations, now your testing your app! see, that wasn't so hard, right? ...
Mozilla Framework Based on Templates (MFBT)
alidation. floatingpoint.h provides various operations for examining and working upon double-precision floating point values, and for producing various special floating point values. core types.h further provides macros to define imported and exported c symbols. attributes.h implements various function and class attribute macros. the function macros control inlining, note whether a function re
turns, and enforce various c++-related restrictions on inheritance and use. the class macros permit controlling the inheritability of a class. likely.h provides moz_likely and moz_unlikely macros to annotate conditions with their expected truthiness. util.h implements various other bits of useful functionality. (this header will likely be further split up so that its functionality is less grab-bag.)...
Basics
, or use color a 2 + b 2 = c 2 in very strange ways p(x) q(x) = a0 + a1x + a2 x2 + ... + an-1 xn-1 b0 + b1x + b2 x2 + ... + bn-1 xn-1 . you can also do other weird and risky things which are not portable, bongo warns, such as mixing mathml with other markups lizard + bongo = ∫ a b d x + mathml and javascript html content <p> and you can
turn to javascript and the dom for dynamic operations. </p> <div style="text-align:center"> fill the gaps in this matrix with resizable input fields. </div> <math class="inputmath" display="block"> <mrow> <mi>a</mi> <mo>=</mo> <mo>[</mo> <mtable> <mtr> <mtd><mn>1</mn></mtd> <mtd> <mtext><input id="input12" value="?" size="1"/></mtext> </mtd> </mtr> <mtr> <mtd> <mtext><input id="input21" value="?" siz...
Mozilla Port Blocking
ser.js or all.js. see bug 85601. per protocol port blocking/enabling preferences. better user interface allow the user to decide if the blocking is really required. some kind of way to manage the ports which are blocked. more information nsioservice.cpp gbadportlist bug 83401 vulnerability note vu#476267 dougt@netscape.com original document information author(s): doug
turner last updated date: august 15, 2007 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Mozilla Web Developer FAQ
nintentional interactions within a complex program. even if you had the source code for browser x, you couldn’t change anything without risking changing one or more of the unknown and unintentional interactions within the program. the usual counter argument is that mozilla doesn’t need to match the behavior of browser x in every possible case but only in the alleged common cases. however, it
turns out mozilla is doing that already. mozilla’s standards mode is, obviously, already compatible with other browsers that implement the same standards reasonably correctly. on the other hand, mozilla’s quirks mode already accommodates common non-standardisms that are due to the behaviors of common legacy browsers. instead of putting time and effort into reverse-engineering and cloning legacy b...
Mozilla Development Strategies
the time for reviews. in your other trees, work on smaller, easier bugs. pick bugs that won't cause conflicts with the work you're doing in your primary tree. pick bugs that should only take you a few hours or a day to fix. in theory, fixes for these bugs will be quick to review. if you have problems finding smaller, easier bugs to work on, start by looking for crashers. maybe the problem can be
turned into an assert, or fixed altogether. you can use talkback queries or bugzilla queries to find crashers. look for problems in existing code. find and fix string usage problems. find and fix bad xpcom macro usage. switch some code over to nscomptrs. look for xxx or todo in the code, verify the code still needs fixing, and fix it. smaller patches get reviewed faster if you find that you spend a...
Mozilla Style System Documentation
ss specification (:before, :after, :first-line, :first-letter), but few of mozilla's custom pseudo-elements, many of which are hacks for further formatting objects that we create. the pres context forwards these calls to its style set object (stylesetimpl, interface nsistyleset), which does the real work (and also maintains the lists of stylesheets and owns the rule tree). these methods may all re
turn an existing style context rather than a new one (see stylesetimpl::getcontext), if there is a current style context with the same parent, that matches the same rules (a check that is easy because of the ruletree), and is for the same pseudo-element (or not for a pseudo-element, or a "non-element"). this is more than just sibling-sharing since if the parent is shared, it could be cousin-sharing. ...
BloatView
1| 308 |pimagebridgechild | 416 416| 1 1| the first line tells you the pid of the leaking process, along with the type of process. here's how you interpret the columns. the first, numerical column is the index of the leaking class. class - the name of the class in question (truncated to 20 characters). bytes per-inst - the number of bytes re
turned if you were to write sizeof(class). note that this number does not reflect any memory held onto by the class, such as internal buffers, etc. (e.g. for nsstring you'll see the size of the header struct, not the size of the string contents!) bytes leaked - the number of bytes per instance times the number of objects leaked: (bytes per-inst) x (objects rem). use this number to look for the worst ...
GC and CC logs
boxing by setting moz_disable_content_sandbox=t when you run firefox. on desktop firefox you can override the default location of the log files by setting the moz_cc_log_directory environment variable. by default, they go to a temporary directory which differs per os - it's /tmp/ on linux/bsd, $localappdata\temp\ on windows, and somewhere in /var/folders/ on mac (whatever the directory service re
turns for tmpd/ns_os_temp_dir). note that just moz_cc_log_directory=. won't work - you need to specify a full path. on firefox for android you can use the cc-dump extension to save the files to /sdcard. by default, the file is created in some temp directory, and the path to the file is printed to the error console. to log every cycle collection, set the moz_cc_log_all environment variable. to log onl...
Leak-hunting strategies and tips
is larger. see bug 106860 and bug 84136 for examples. (is this advice still accurate now that we have a cycle collector? --jesse) dropping a reference on the floor by: forgetting to release (because you weren't using nscomptr when you should have been): see bug 99180 or bug 93087 for an example or bug 28555 for a slightly more interesting one. this is also a frequent problem around early re
turns when not using nscomptr. double-addref: this happens most often when assigning the result of a function that re
turns an addrefed pointer (bad!) into an nscomptr without using dont_addref(). see bug 76091 or bug 49648 for an example. [obscure] double-assignment into the same variable: if you release a member variable and then assign into it by calling another function that does the same thi...
Measuring performance using the PerfMeasurement.jsm code module
code_to_be_benchmarked(); monitor.stop(); clean_up_afterward(); } we call the perfmeasurement object's start() method when we want to start recording, and stop() when we want to stop recording. this lets us record information only for the specific code section we want to measure. since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it re
turns, the code in set_up_some_state() and clean_up_afterward() is not measured. the monitor object automatically accumulates counts over start/stop cycles (that is, it doesn't automatically zero the counters each time you start recording). when you're done benchmarking, you can read out each of the counters you asked for as properties: let report = "cpu cycles: " + monitor.cpu_cycles + "\n" + ...
Profile Manager
ied date. rename - allows you to specify a new name for the profile. version - allows you change the default application version to be used with the profile. future enhancements ability to install/uninstall/enable/disable extensions in profiles. ability to copy certain assets (e.g., bookmarks) between profiles. add 'profile size' to the properties dialog. ability to reset a profile (re
turn it to a default state excluding bookmarks and passwords). add option to specify the location of profiles.ini. ...
Midas
this command will set the hilite color of the selection or at the insertion point. it only works with stylewithcss enabled. increasefontsize this command will add a <big> tag around selection or at insertion point. indent indent the block where the caret is located. if the caret is inside a list, that item becomes a sub-item one level deeper. insertbronre
turn true/false selects whether pressing re
turn inside a paragraph creates another paragraph or just inserts a <br> tag. inserthorizontalrule null/string (when string is the line's id) this command will insert a horizontal rule (line) at the insertion point. does it delete the selection? yes! inserthtml a string. this command will insert the given html into ...
Creating a Cookie Log
fox" and pressing enter mac os x open terminal.app, which is located in the /applications/utilities folder (these instructions are for bash, the default shell in mac os x 10.3 and higher; if you use something else, you probably know how to modify these instructions already). change to the installation directory for firefox, e.g. type "cd /applications/firefox.app/contents/macos" and press re
turn. type "export nspr_log_file=~/desktop/cookie-log.txt" and press re
turn. type "export nspr_log_modules=cookie:4" and press re
turn. run firefox by typing "./firefox-bin" and pressing re
turn (note that firefox will launch behind windows for other applications). creating the log now that you have firefox running with logging enabled, please try to replicate the bug using the steps to reproduce ...
Dynamic Library Linking
ymbols defined in the main executable program pr_loadlibrary cannot open a handle that references the main executable program. (this is admittedly an omission that should be fixed.) however, it is possible to look up symbols defined in the main executable program as follows. prlibrary *lib; void *funcptr; funcptr = pr_findsymbolandlibrary("functionname", &lib); when pr_findsymbolandlibrary re
turns, funcptr is the value of the function pointer you want to look up, and the variable lib references the main executable program. you can then call pr_findsymbol on lib to look up other symbols defined in the main program. remember to call pr_unloadlibrary(lib) to close the library handle when you are done. platform notes to use the dynamic library loading functions on some platforms, certain en...
Monitors
t time the thread successfully enters the same monitor, the thread's entry count is incremented again, and each time the thread exits the monitor, the thread's entry count is decremented. when the entry count for a thread reaches zero, the thread releases the monitor's lock, and other threads that were blocked while trying to enter the monitor will be rescheduled. a call to pr_wait temporarily re
turns the entry count to zero. when the calling thread resumes, it has the same entry count it had before the wait operation. unlike a mutex of type prlock, a mutex of type prmonitor has a single, implicitly associated condition variable that may be used to facilitate synchronization of threads with the change in state of monitored data. for an introduction to nspr thread synchronization, including ...
PLHashComparator
syntax #include <plhash.h> typedef printn (pr_callback *plhashcomparator)( const void *v1, const void *v2); description plhashcomparator is a function type that compares two values of an unspecified type. it re
turns a nonzero value if the two values are equal, and 0 if the two values are not equal. plhashcomparator defines the meaning of equality for the unspecified type. for convenience, two comparator functions are provided. pl_comparestrings compare two character strings using strcmp. pl_comparevalues compares the values of the arguments v1 and v2 numerically. remark the re
turn value of plhashcomparator functions should be of type prbool. see also pl_comparestrings, pl_comparevalues ...
PLHashEnumerator
syntax #include <plhash.h> typedef printn (pr_callback *plhashenumerator)(plhashentry *he, printn index, void *arg); /* re
turn value */ #define ht_enumerate_next 0 /* continue enumerating entries */ #define ht_enumerate_stop 1 /* stop enumerating entries */ #define ht_enumerate_remove 2 /* remove and free the current entry */ #define ht_enumerate_unhash 4 /* just unhash the current entry */ description plhashenumerator is a function type used in the enumerating a hash table. when all the table entries are enumerated, each entry is passed to a user-specified function of type plhashenumerator with the hash table entry, an integer index, and an arbitrary piece of user data as argument. remark the meaning of ht_enumerate_unhash is not clear. in the current implementati...
PLHashNumber
syntax #include <plhash.h> typedef pruint32 plhashnumber; #define pl_hash_bits 32 description plhashnumber is an unsigned 32-bit integer. plhashnumber is the data type of the re
turn value of a hash function. a hash function maps a key to a hash number, which is then used to compute the index of the bucket. the macro pl_hash_bits is the size (in bits) of the plhashnumber data type and has the value of 32. see also plhashfunction ...
PL_CompareStrings
compares two character strings. syntax #include <plhash.h> printn pl_comparestrings( const void *v1, const void *v2); description pl_comparestrings compares v1 and v2 as character strings using strcmp. if the two strings are equal, it re
turns 1. if the two strings are not equal, it re
turns 0. pl_comparestrings can be used as the comparator function for string-valued key or entry value. ...
PL_CompareValues
compares two void * values numerically. syntax #include <plhash.h> printn pl_comparevalues(const void *v1, const void *v2); description pl_comparevalues compares the two void * values v1 and v2 numerically, i.e., it re
turns the value of the expression v1 == v2. pl_comparevalues can be used as the comparator function for integer or pointer-valued key or entry value. ...
PL_HashString
a general-purpose hash function for character strings. syntax #include <plhash.h> plhashnumber pl_hashstring(const void *key); parameter the function has the following parameter: key a pointer to a character string. re
turns the hash number for the specified key. description pl_hashstring can be used as the key hash function for a hash table if the key is a character string. ...
PL_HashTableEnumerateEntries
entries in the hash table, invoking a specified function on each entry. syntax #include <plhash.h> printn pl_hashtableenumerateentries( plhashtable *ht, plhashenumerator f, void *arg); parameters the function has the following parameters: ht a pointer to the hash table whose entries are to be enumerated. f function to be applied to each entry. arg argument for function f. re
turns the number of entries enumerated. description the entries are enumerated in an unspecified order. for each entry, the enumerator function is invoked with the entry, the index (in the sequence of enumeration, starting from 0) of the entry, and arg as arguments. ...
PL_HashTableLookup
looks up the entry with the specified key and re
turn its value. syntax #include <plhash.h> void *pl_hashtablelookup( plhashtable *ht, const void *key); parameters the function has the following parameters: ht a pointer to the hash table in which to look up the entry specified by key. key a pointer to the key for the entry to look up. re
turns the value of the entry with the specified key, or null if there is no such entry. description if there is no entry with the specified key, pl_hashtablelookup re
turns null. this means that one cannot tell whether a null re
turn value means the entry does not exist or the value of the entry is null. keep this ambiguity in mind if you want to store null values in a hash table. ...
PL_HashTableRemove
fied key from the hash table. syntax #include <plhash.h> prbool pl_hashtableremove( plhashtable *ht, const void *key); parameters the function has the following parameters: ht a pointer to the hash table from which to remove the entry. key a pointer to the key for the entry to be removed. description if there is no entry in the table with the specified key, pl_hashtableremove re
turns pr_false. if the entry exists, pl_hashtableremove removes the entry from the table, invokes freeentry with the ht_free_entry flag to frees the entry, and re
turns pr_true. if the table is underloaded, pl_hashtableremove also shrinks the number of buckets by half. remark this function should re
turn prstatus. ...
PL_NewHashTable
function has the following parameters: numbuckets the number of buckets in the hash table. keyhash hash function. keycompare function used to compare keys of entries. valuecompare function used to compare keys of entries. allocops a pointer to a plhashallocops structure that must exist throughout the lifetime of the new hash table. allocpriv passed as the first argument (pool). re
turns the new hash table. description pl_newhashtable creates a new hash table. the table has at least 16 buckets. you can pass a value of 0 as numbuckets to create the default number of buckets in the new table. the arguments keycompare and valuecompare are functions of type plhashcomparator that the hash table library functions use to compare the keys and the values of entries. the argument allo...
PL_strcpy
copies a string, up to and including the trailing '\0', into a destination buffer. syntax char * pl_strcpy(char *dest, const char *src); parameters the function has these parameters: dest pointer to a buffer. on output, the buffer contains a copy of the string passed in src. src pointer to the string to be copied. re
turns the function re
turns a pointer to the buffer specified by the dest parameter. description if the string specified by src is longer than the buffer specified by dest, the buffer will not be null-terminated. ...
PL_strdup
if the memory allocation fails, null. description to accommodate the terminator, the size of the allocated memory is one greater than the length of the string being copied. a null argument, like a zero-length argument, results in a pointer to a one-byte block of memory containing the null value. notes the memory allocated by pl_strdup should be freed with pl_strfree. ...
PL_strlen
re
turns the length of a specified string (not including the trailing '\0') syntax pruint32 pl_strlen(const char *str); parameter the function has these parameter: str size in bytes of item to be allocated. re
turns if successful, the function re
turns length of the specified string. ...
PRCallOnceFN
defines the signature of the function a client must implement. syntax #include <prinit.h> typedef prstatus (pr_callback *prcalloncefn)(void); description the function is called to perform the initialization desired. the function is expected to re
turn a prstatus indicating the outcome of the process. ...
PRDescIdentity
has it own identity. identities are allocated by the runtime and are to be associated (by the layer implementor) with all file descriptors of that layer. it is then possible to scan the chain of layers and find a layer that one recognizes, then predict that it will implement a desired protocol. there are three well-known identities: pr_invalid_io_layer, an invalid layer identity, for error re
turn pr_top_io_layer, the identity of the top of the stack pr_nspr_io_layer, the identity used by nspr proper layers are created by pr_getuniqueidentity. a string may be associated with a layer when the layer is created. the string is copied by the runtime, and pr_getnameforidentity re
turns a reference to that copy. there is no way to delete a layer's identity after the layer is created. ...
PRDir
directory structure used with directory i/o functions. syntax #include <prio.h> typedef struct prdir prdir; description the opaque structure prdir represents an open directory in the file system. the function pr_opendir opens a specified directory and re
turns a pointer to a prdir structure, which can be passed to pr_readdir repeatedly to obtain successive entries (files or subdirectories in the open directory). to close the directory, pass the prdir pointer to pr_closedir. ...
PRExplodedTime
prexplodedtime are: tm_wday: day of week. the range is [0, 6]. 0 is sunday, 1 is monday, and 6 is saturday. tm_yday: day of year. the range is [0, 365]. 0 is the 1st of january. on input to nspr functions, only the essential members of prexplodedtime must be specified. the two nonessential members (day of week and day of year) are ignored by nspr functions as input. when an nspr function re
turns a prexplodedtime object or sets a prexplodedtime object as output, all of the prexplodedtime members are set, including the nonessential members. you can also use pr_normalizetime() to calculate the values of the nonessential members. ...
PRHostEnt
rnal representation of the address in bytes. all of the addresses in the list are of the same type and therefore of the same length. h_addr_list pointer to a pointer to a list of addresses from name server (in network byte order). the list is terminated with a null entry. description this structure is used by many of the network address functions. all addresses are passed in host order and re
turned in network order (suitable for use in system calls). use the network address functions to manipulate the prhostent structure. to make the transition to ip version 6 easier, it's best to treat prhostent as an opaque structure. note winsock.h defines h_addrtype and h_length as a 16-bit field, whereas other platforms treat it as a 32-bit field. the #ifdef in the structure allows direct assignme...
PRIOMethods
e prio.h. the i/o methods table provides procedural access to the functions of the file descriptor. it is the responsibility of a layer implementor to provide suitable functions at every entry point (that is, for every function in the i/o methods table). if a layer provides no functionality, it should call the next lower (higher) function of the same name (for example, the "close" method would re
turn fd->lower->method->close(fd->lower)). not all functions in the methods table are implemented for all types of files. for example, the seek method is implemented for normal files but not for sockets. in cases where this partial implementation occurs, the function re
turns an error indication with an error code of pr_invalid_method_error. ...
PRIntervalTime
gardless of host processing requirements and are very cheap to acquire. the constants pr_interval_min and pr_interval_max define a range in ticks per second. these constants bound both the period and the resolution of a printervaltime object. the reserved constants pr_interval_no_wait and pr_interval_no_timeout have special meaning for nspr. they indicate that the process should wait no time (re
turn immediately) or wait forever (never time out), respectively. important note the counters used for interval times are allowed to overflow. since the sampling of the counter used to define an arbitrary epoch may have any 32-bit value, some care must be taken in the use of interval times. the proper coding style to test the expiration of an interval is as follows: if ((printervaltime)(now - epoc...
PRLibrary
an opaque structure identifying a library. syntax #include <prlink.h> typedef struct prlibrary prlibrary; description a prlibrary is an opaque structure. a reference to such a structure can be re
turned by some of the functions in the runtime and serve to identify a particular instance of a library. ...
PRProtoEnt
syntax #include <prnetdb.h> typedef struct prprotoent { char *p_name; char **p_aliases; #if defined(_win32) print16 p_num; #else print32 p_num; #endif } prprotoent; fields the structure has the following fields: p_name pointer to official protocol name. p_aliases pointer to a pointer to a list of aliases. the list is terminated with a null entry. p_num protocol number. ...
PRStatus
type for status code re
turned by some functions. syntax #include <prtypes.h> typedef enum { pr_failure = -1, pr_success = 0 } prstatus; ...
PRThread
an nspr thread. syntax #include <prthread.h> typedef struct prthread prthread; description in nspr, a thread is represented by a pointer to an opaque structure of type prthread. this pointer is a required parameter for most of the functions that operate on threads. a prthread* is the successful result of creating a new thread. the identifier remains valid until it re
turns from its root function and, if the thread was created joinable, is joined. ...
PRThreadScope
syntax #include <prthread.h> typedef enum prthreadscope { pr_local_thread, pr_global_thread pr_global_bound_thread } prthreadscope; enumerators pr_local_thread a local thread, scheduled locally by nspr within the process. pr_global_thread a global thread, scheduled by the host os. pr_global_bound_thread a global bound (kernel) thread, scheduled by the host os description an enumerator of type prthreadscope specifies how a thread is scheduled: either locally by nspr within the process (a local thread) or globally by the host (a global thread). ...
PRThreadType
n nspr thread, specified as a parameter to pr_createthread. syntax #include <prthread.h> typedef enum prthreadtype { pr_user_thread, pr_system_thread } prthreadtype; enumerators pr_user_thread pr_cleanup blocks until the last thread of type pr_user_thread terminates. pr_system_thread nspr ignores threads of type pr_system_thread when determining when a call to pr_cleanup should re
turn. description threads can be either user threads or system threads. nspr allows the client to synchronize the termination of all user threads and ignores those created as system threads. this arrangement implies that a system thread should not have volatile data that needs to be safely stored away. the applicability of system threads is somewhat dubious; therefore, they should be used with caut...
PRTimeParamFn
this type defines a callback function to calculate and re
turn the time parameter offsets from a calendar time object in gmt. syntax #include <prtime.h> typedef prtimeparameters (pr_callback_decl *prtimeparamfn) (const prexplodedtime *gmt); description the type prtimeparamfn represents a callback function that, when given a time instant in gmt, re
turns the time zone information (offset from gmt and dst offset) at that time instant. ...
PRTimeParameters
st is not in effect, the tp_dst_offset component is 0. for example, the us pacific time zone has both a standard time zone (pacific standard time, or pst) and a daylight time zone (pacific daylight time, or pdt). in pst, the local time is 8 hours behind gmt, so tp_gmt_offset is -28800 seconds. tp_dst_offset is 0, indicating that daylight saving time is not in effect. in pdt, the clock is
turned forward by one hour, so the local time is 7 hours behind gmt. this is broken down as -8 + 1 hours, so tp_gmt_offset is -28800 seconds, and tp_dst_offset is 3600 seconds. a second example is japan, which is 9 hours ahead of gmt. japan does not use daylight saving time, so the only time zone is japan standard time (jst). in jst tp_gmt_offset is 32400 seconds, and tp_dst_offset is 0. ...
PR_ASSERT
when the result is zero (false) the application terminates; otherwise the application continues. ...
PR_Access
ar *name, praccesshow how); parameters the function has the following parameters: name the pathname of the file whose accessibility is to be determined. how specifies which access permission to check for. use one of the following values: pr_access_read_ok. test for read permission. pr_access_write_ok. test for write permission. pr_access_exists. check existence of file. re
turns one of the following values: if the requested access is permitted, pr_success. if the requested access is not permitted, pr_failure. ...
PR_Assert
normally an application would not call this function directly; use pr_assert instead. ...
PR_AtomicDecrement
atomically decrements a 32-bit value. syntax #include <pratom.h> print32 pr_atomicdecrement(print32 *val); parameter the function has the following parameter: val a pointer to the value to decrement. re
turns the function re
turns the decremented value (i.e., the result). description pr_atomicdecrement first decrements the referenced variable by one. the value re
turned is the referenced variable's final value. the modification to memory is unconditional. ...
PR_AtomicIncrement
atomically increments a 32-bit value. syntax #include <pratom.h> print32 pr_atomicincrement(print32 *val); parameter the function has the following parameter: val a pointer to the value to increment. re
turns the function re
turns the incremented value (i.e., the result). description the referenced variable is incremented by one. the result of the function is the value of the memory after the operation. the writing of the memory is unconditional. ...
PR_AtomicSet
atomically sets a 32-bit value and re
turn its previous contents. syntax #include <pratom.h> print32 pr_atomicset( print32 *val, print32 newval); parameters the function has the following parameter: val a pointer to the value to be set. newval the new value to assign to the val parameter. re
turns the function re
turns the prior value of the referenced variable. description pr_atomicset first reads the value of var, then updates it with the supplied value. the re
turned value is the value that was readbefore memory was updated. the memory modification is unconditional--that is, it isn't a test and set operation. ...
PR_AttachSharedMemory
attaches a memory segment previously opened with pr_opensharedmemory and maps it into the process memory space. syntax #include <prshm.h> nspr_api( void * ) pr_attachsharedmemory( prsharedmemory *shm, printn flags ); /* define values for pr_attachsharedmemory(...,flags) */ #define pr_shm_readonly 0x01 parameters the function has these parameters: shm the handle re
turned from pr_opensharedmemory. flags options for mapping the shared memory. pr_shm_readonly causes the memory to be attached read-only. re
turns address where shared memory is mapped, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. ...
PR_AttachThread
> prthread* pr_attachthread( prthreadtype type, prthreadpriority priority, prthreadstack *stack); parameters pr_attachthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). priority the priority to assign to the thread being attached. stack the stack for the thread being attached. re
turns the function re
turns one of these values: if successful, a pointer to a prthread object. if unsuccessful, for example if system resources are not available, null. description you use pr_attachthread when you want to use nss functions on the native thread that was not created with nspr. pr_attachthread informs nspr about the new thread by associating a prthread object with the native thre...
PR_Available
determines the number of bytes (expressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. syntax #include <prio.h> print32 pr_available(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. re
turns the function re
turns one of the following values: if the function completes successfully, it re
turns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it re
turns the value -1. the error code can then be retrieved via pr_geterror. description pr_available works on normal files and sockets. pr_available does not work with pipes on win3...
PR_Available64
determines the number of bytes (expressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket. syntax #include <prio.h> print64 pr_available64(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. re
turns the function re
turns one of the following values: if the function completes successfully, it re
turns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it re
turns the value -1. the error code can then be retrieved via pr_geterror. description pr_available64 works on normal files and sockets. pr_available does not work with pipes on ...
PR_Bind
binds an address to a specified socket. syntax #include <prio.h> prstatus pr_bind( prfiledesc *fd, const prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr a pointer to a prnetaddr object representing the address to which the socket will be bound. re
turns the function re
turns one of the following values: upon successful binding of an address to a socket, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description when a new socket is created, it has no address bound to it. pr_bind assigns the specified address (also known as name) to the socket. if you do not care about the exact ip address assigned to the socket, set the inet.ip f...
PR_Calloc
allocates zeroed memory from the heap for a number of objects of a given size. syntax #include <prmem.h> void *pr_calloc ( pruint32 nelem, pruint32 elsize); parameters nelem the number of elements of size elsize to be allocated. elsize the size of an individual element. re
turns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error re
turned by the libc function malloc(). description this function allocates memory on the heap for the specified number of objects of the specified size. all bytes in the allocated memory are cleared. ...
PR_CLIST_IS_EMPTY
checks for an empty circular list. syntax #include <prclist.h> printn pr_clist_is_empty (prclist *listp); parameter listp a pointer to the linked list. description pr_clist_is_empty re
turns a non-zero value if the specified list is an empty list, otherwise re
turns zero. ...
PR_CNotify
notify a thread waiting on a change in the state of monitored data. syntax #include <prcmon.h> prstatus pr_cnotify(void *address); parameter the function has the following parameter: address the address of the monitored object. the calling thread must be in the monitor defined by the value of the address. re
turns pr_success indicates that the calling thread is the holder of the mutex for the monitor referred to by the address parameter. pr_failure indicates that the monitor has not been entered by the calling thread. description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cnotify notifies single a thread waiting for the monitor's state to change. if a thread is waiting on the monitor (having called pr_cwait), then that threa...
PR_CNotifyAll
notifies all the threads waiting for a change in the state of monitored data. syntax #include <prcmon.h> prstatus pr_cnotifyall(void *address); parameter the function has the following parameter: address the address of the monitored object. the calling thread must be in the monitor at the time pr_cnotifyall is called. re
turns pr_success indicates that the referenced monitor was located and the calling thread was in the monitor. pr_failure indicates that the referenced monitor could not be located or that the calling thread was not in the monitor description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cnotifyall notifies all threads waiting for the monitor's state to change. all of the threads waiting on the state change are ...
PR_CWait
*address, printervaltime timeout); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor. timeout the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. if you specify pr_interval_no_timeout, the function re
turns if and only if the object is notified. re
turns the function re
turns one of the following values: pr_success indicates either that the monitored object has been notified or that the interval specified in the timeout parameter has been exceeded. pr_failure indicates either that the monitor could not be located in the cache or that the monitor was located and the calling thread was not the t...
PR_CallOnce
exist), the object must be initialized to all zeros. from that time on, the client should consider the object read-only (or even opaque) and allow the runtime to manipulate its content appropriately. func a pointer to the function the calling client has designed to perform the subsystem initialization. the function will be called once, at most, for each subsystem to be initialized. it should re
turn a prstatus indicating the result of the initialization process. while the first thread executes this function, other threads attempting the same initialization will be blocked until it has been completed. ...
PR_Cleanup
coordinates a graceful shutdown of nspr. syntax #include <prinit.h> prstatus pr_cleanup(void); re
turns the function re
turns one of the following values: if nspr has been shut down successfully, pr_success. if the calling thread of this function is not the primordial thread, pr_failure. description pr_cleanup must be called by the primordial thread near the end of the main function. pr_cleanup attempts to synchronize the natural termination of the process. it does so by blocking the caller, if and only if it is the primordial thread, until all user threads have terminated. when the primordial thread re
turns from main, the process immediately and silently exits. that is, the process (if necessary) forcibly terminates any existing threads and exits without significant blocking and ...
PR_Close
closes a file descriptor. syntax #include <prio.h> prstatus pr_close(prfiledesc *fd); parameters the function has the following parameters: fd a pointer to a prfiledesc object. re
turns one of the following values: if file descriptor is closed successfully, pr_success. if the file descriptor is not closed successfully, pr_failure. description the file descriptor may represent a normal file, a socket, or an end point of a pipe. on successful re
turn, pr_close frees the dynamic memory and other resources identified by the fd parameter. ...
PR_CloseDir
closes the specified directory. syntax #include <prio.h> prstatus pr_closedir(prdir *dir); parameter the function has the following parameter: dir a pointer to a prdir structure representing the directory to be closed. re
turns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. description when a prdir object is no longer needed, it must be closed and freed with a call to pr_closedir call. note that after a pr_closedir call, any prdirentry object re
turned by a previous pr_readdir call on the same prdir object becomes invalid. see also pr_opendir ...
PR_CloseSharedMemory
closes a shared memory segment identified by name. syntax #include <prshm.h> nspr_api( prstatus ) pr_closesharedmemory( prsharedmemory *shm ); parameter the function has these parameter: shm the handle re
turned from pr_opensharedmemory. re
turns prstatus. ...
PR_Connect
s pr_connect( prfiledesc *fd, const prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr a pointer to the address of the peer to which the socket is to be connected. timeout a value of type printervaltime specifying the time limit for completion of the connect operation. re
turns the function re
turns one of the following values: upon successful completion of connection setup, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description pr_connect is usually invoked on a tcp socket, but it may also be invoked on a udp socket. both cases are discussed here. if the socket is a tcp socket, pr_connect establishes a ...
PR ConvertIPv4AddrToIPv6
pv4-mapped) ipv6 address. syntax #include <prnetdb.h> void pr_convertipv4addrtoipv6( pruint32 v4addr, pripv6addr *v6addr ); parameters the function has the following parameters: v4addr the ipv4 address to convert into an ipv4-mapped ipv6 address. this must be specified in network byte order. v6addr a pointer to a buffer, allocated by the caller, that is filled in with the ipv6 address on re
turn. ...
PR_CreateIOLayerStub
creates a new layer. syntax #include <prio.h> prfiledesc* pr_createiolayerstub( prdescidentity ident priomethods const *methods); parameters the function has the following parameters: ident the identity to be associated with the new layer. methods a pointer to the priomethods structure specifying the functions for the new layer. re
turns a new file descriptor for the specified layer. description a new layer may be allocated by calling pr_createiolayerstub. the file descriptor re
turned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor re
turned before pushing it onto the protocol stack. ...
PR_CreatePipe
creates an anonymous pipe and retrieves file descriptors for the read and write ends of the pipe. syntax #include <prio.h> prstatus pr_createpipe( prfiledesc **readpipe, prfiledesc **writepipe); parameters the function has the following parameters: readpipe a pointer to a prfiledesc pointer. on re
turn, this parameter contains the file descriptor for the read end of the pipe. writepipe a pointer to a prfiledesc pointer. on re
turn, this parameter contains the file descriptor for the write end of the pipe. re
turns the function re
turns one of these values: if the pipe is successfully created, pr_success. if the pipe is not successfully created, pr_failure. the error code can be retrieved via pr_geterror. description pr_createpipe creates an anonymous pipe. data written i...
PR_DELETE
allocates memory of a specified size from the heap. syntax #include <prmem.h> void pr_delete(_ptr); parameter _ptr the address of memory to be re
turned to the heap. must be an lvalue (an expression that can appear on the left side of an assignment statement). re
turns nothing. description this macro re
turns allocated memory to the heap from the specified location and sets _ptr to null. ...
PR_Delete
if the file is not deleted, pr_failure. ...
PR_DeleteSemaphore
removes a semaphore specified by name from the system. syntax #include <pripcsem.h> nspr_api(prstatus) pr_deletesemaphore(const char *name); parameter the function has the following parameter: name the name of a semaphore that was previously created via a call to pr_opensemaphore. re
turns prstatus ...
PR_DeleteSharedMemory
deletes a shared memory segment identified by name. syntax #include <prshm.h> nspr_api( prstatus ) pr_deletesharedmemory( const char *name ); parameter the function has these parameter: shm the handle re
turned from pr_opensharedmemory. re
turns prstatus. ...
PR_DestroyPollableEvent
close the file descriptor associated with a pollable event and release related resources. syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_DetachSharedMemory
unmaps a shared memory segment identified by name. syntax #include <prshm.h> nspr_api( prstatus ) pr_detachsharedmemory( prsharedmemory *shm, void *addr ); parameters the function has these parameters: shm the handle re
turned from pr_opensharedmemory. addr the address to which the shared memory segment is mapped. re
turns prstatus. ...
PR_EnterMonitor
enters the lock associated with a specified monitor. syntax #include <prmon.h> void pr_entermonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. description when the calling thread re
turns, it will have acquired the monitor's lock. attempts to acquire the lock for a monitor that is held by some other thread will result in the caller blocking. the operation is neither timed nor interruptible. if the monitor's entry count is greater than zero and the calling thread is recognized as the holder of the lock, pr_entermonitor increments the entry count by one and re
turns. if the entry count is greater than zero and the calling thread is not recognized as the holder of the lock, the thread is blocked unt...
PR_ExitMonitor
count associated with a specified monitor and, if the entry count reaches zero, releases the monitor's lock. syntax #include <prmon.h> prstatus pr_exitmonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful (the calling thread has not entered the monitor), pr_failure. description if the decremented entry count is zero, pr_exitmonitor releases the monitor's lock. threads that were blocked trying to enter the monitor will be rescheduled. ...
PR_ExplodeTime
ime. syntax #include <prtime.h> void pr_explodetime( prtime usecs, prtimeparamfn params, prexplodedtime *exploded); parameters the function has these parameters: usecs an absolute time in the prtime format. params a time parameter callback function. exploded a pointer to a location where the converted time can be stored. this location must be preallocated by the caller. re
turns nothing; the buffer pointed to by exploded is filled with the exploded time. description this function converts the specified absolute time to a clock/calendar time in the specified time zone. upon re
turn, the location pointed to by the exploded parameter contains the converted time value. ...
PR_ExportFileMapAsString
ifying a prfilemap. syntax #include <prshma.h> nspr_api( prstatus ) pr_exportfilemapasstring( prfilemap *fm, prsize bufsize, char *buf ); define pr_filemap_string_bufsize 128 parameters the function has the following parameters: fm a pointer to the prfilemap to be represented as a string. bufsize sizeof(buf) buf a pointer to abuffer of length pr_filemap_string_bufsize. re
turns prstatus description creates an identifier, as a string, from a prfilemap object previously created with pr_openanonfilemap. ...
PR_FREEIF
conditionally frees allocated memory. syntax #include <prmem.h> void pr_freeif(_ptr); parameter _ptr the address of memory to be re
turned to the heap. re
turns nothing. description this macro re
turns memory to the heap when _ptr is not null. if _ptr is null, the macro has no effect. ...
PR_FamilyInet
gets the value of the address family for internet protocol. syntax #include <prnetdb.h> pruint16 pr_familyinet(void); re
turns the value of the address family for internet protocol. this is usually pr_af_inet, but can also be pr_af_inet6 if ipv6 is enabled. the re
turned value can be assigned to the inet.family field of a prnetaddr object. ...
PR_Free
frees allocated memory in the heap. syntax #include <prmem.h> void pr_free(void *ptr); parameter ptr a pointer to the memory to be freed. re
turns nothing. description this function frees the memory addressed by ptr in the heap. ...
PR FreeAddrInfo
destroys the praddrinfo structure re
turned by pr_getaddrinfobyname. syntax #include <prnetdb.h> void pr_enumerateaddrinfo(praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure re
turned by a successful call to pr_getaddrinfobyname. re
turns the function doesn't re
turn anything. ...
PR_FreeLibraryName
frees memory allocated by nspr for library names and path names. syntax #include <prlink.h> void pr_freelibraryname(char *mem); parameters the function has this parameter: mem a reference to a character array that was previously allocated by the dynamic library runtime. re
turns nothing. description this function deletes the storage allocated by the runtime in the functions described previously. it is important to use this function to rather than calling directly into malloc in order to isolate the runtime's semantics regarding storage management. ...
PR GetAddrInfoByName
t16 af, printn flags); parameters the function has the following parameters: hostname the character string defining the host name of interest. af the address family. may be pr_af_unspec or pr_af_inet. flags may be either pr_ai_addrconfig or pr_ai_addrconfig | pr_ai_nocanonname. include pr_ai_nocanonname to suppress the determination of the canonical name corresponding to hostname re
turns the function re
turns one of the following values: if successful, a pointer to the opaque praddrinfo structure containing the results of the host lookup. use pr_enumerateaddrinfo to inspect the prnetaddr values stored in this structure. when no longer needed, this pointer must be destroyed with a call to pr_freeaddrinfo. if unsuccessful, null. you can retrieve the reason for the failure by c...
PR GetCanonNameFromAddrInfo
extracts the canonical name of the hostname passed to pr_getaddrinfobyname. syntax #include <prnetdb.h> const char *pr_getcanonnamefromaddrinfo(const praddrinfo *addrinfo); parameters the function has the following parameters: addrinfo a pointer to a praddrinfo structure re
turned by a successful call to pr_getaddrinfobyname. re
turns the function re
turns a const pointer to the canonical hostname stored in the given praddrinfo structure. this pointer is invalidated once the praddrinfo structure is destroyed by a call to pr_freeaddrinfo. ...
PR_GetCurrentThread
description the currently running thread may discover its own identity by calling pr_getcurrentthread. note: this is the only safe way to establish the identity of a thread. creation and enumeration are both subject to race conditions. ...
PR_GetDefaultIOMethods
description after using pr_getdefaultiomethods to identify the default i/o methods table, you can select elements from that table with which to build your own layer's methods table. ...
PR_GetDescType
describes what type of file is referenced by a specified file descriptor. syntax #include <prio.h> prdesctype pr_getdesctype(prfiledesc *file); parameter the function has the following parameter: file a pointer to a prfiledesc object whose descriptor type is to be re
turned. re
turns the function re
turns a prdesctype enumeration constant that describes the type of file. description the prdesctype enumeration is defined as follows: typedef enum prdesctype { pr_desc_file = 1, pr_desc_socket_tcp = 2, pr_desc_socket_udp = 3, pr_desc_layered = 4 } prdesctype; the enumeration has the following enumerators: pr_desc_file the prfiledesc object represents a normal file. pr_desc_socket_tcp the prfiledesc object represents a tcp socket. pr_desc_socket_udp the prfi...
PR_GetErrorTextLength
gets the length of the error text. syntax #include <prerror.h> print32 pr_geterrortextlength(void) re
turns if a zero is re
turned, no error text is currently set. otherwise, the value re
turned is sufficient to contain the error text currently available. ...
PR_GetFileInfo
essed as a 32-bit integer. syntax #include <prio.h> prstatus pr_getfileinfo( const char *fn, prfileinfo *info); parameters the function has the following parameters: fn the pathname of the file to get information about. info a pointer to a file information object (see prfileinfo). on output, pr_getfileinfo writes information about the given file to the file information object. re
turns one of the following values: if the file information is successfully obtained, pr_success. if the file information is not successfully obtained, pr_failure. description pr_getfileinfo stores information about the file with the specified pathname in the prfileinfo structure pointed to by info. the file size is re
turned as an unsigned 32-bit integer. see also for the 64-bit version of th...
PR_GetFileInfo64
it integer. syntax #include <prio.h> prstatus pr_getfileinfo64( const char *fn, prfileinfo64 *info); parameters the function has the following parameters: fn the pathname of the file to get information about. info a pointer to a 64-bit file information object (see prfileinfo64). on output, pr_getfileinfo64 writes information about the given file to the file information object. re
turns one of the following values: if the file information is successfully obtained, pr_success. if the file information is not successfully obtained, pr_failure. description pr_getfileinfo64 stores information about the file with the specified pathname in the prfileinfo64 structure pointed to by info. the file size is re
turned as an unsigned 64-bit integer. see also for the 32-bit version o...
PR_GetHostByAddr
n output. all of the pointers in the hostentry structure point to data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function re
turns pr_success. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description pr_gethostbyaddr is used to perform reverse lookups of network addresses. that is, given a valid network address (of type prnetaddr), pr_gethostbyaddr discovers the address' primary ...
PR_GetHostByName
n output. all of the pointers in the hostentry structure point to data saved in this buffer. this buffer is referenced by the runtime during a call to pr_enumeratehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function re
turns pr_success. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_GetIdentitiesLayer
finds the layer with the specified identity in the specified stack of layers. syntax #include <prio.h> prfiledesc* pr_getidentitieslayer( prfiledesc* stack, prdescidentity id); parameters the function has the following parameters: stack a pointer to a prfiledesc object that is a layer in a stack of layers. id the identity of the specified layer. re
turns the function re
turns one of the following values: if successful, a pointer to a file descriptor of the layer with the specified identity in the given stack of layers. if not successful, null. description the stack of layers to be searched is specified by the fd parameter, which is a layer in the stack. both the layers underneath fd and the layers above fd are searched to find the layer with the specified identity. ...
PR_GetInheritedFileMap
imports a prfilemap previously exported by my parent process via pr_createprocess. syntax #include <prshma.h> nspr_api( prfilemap *) pr_getinheritedfilemap( const char *shmname ); parameter the function has the following parameter: shmname the name provided to pr_processattrsetinheritablefilemap. re
turns pointer to prfilemap or null on error. description pr_getinheritedfilemap retrieves a prfilemap object exported from its parent process via pr_createprocess. note: this function is not implemented. ...
PR_GetLayersIdentity
gets the unique identity for the layer of the specified file descriptor. syntax #include <prio.h> prdescidentity pr_getlayersidentity(prfiledesc* fd); parameter the function has the following parameter: fd a pointer to a file descriptor. re
turns if successful, the function re
turns the prdescidentity for the layer of the specified file descriptor. ...
PR_GetLibraryPath
retrieves the current default library path. syntax #include <prlink.h> char* pr_getlibrarypath(void); parameters the function has no parameters. re
turns a copy of the default library pathname string. in case of error, re
turns null. description this function retrieves the current default library pathname, copies it, and re
turns the copy. if sufficient storage cannot be allocated to contain the copy, the function re
turns null. storage for the result is allocated by the runtime and becomes the responsibility of the caller. when it is no longer used, free it using pr_freelibraryname. ...
PR_GetNameForIdentity
gets the string associated with a layer's unique identity. syntax #include <prio.h> const char* pr_getnameforidentity(prdescidentity ident); parameter the function has the following parameter: ident a layer's identity. re
turns the function re
turns one of the following values: if successful, the function re
turns a pointer to the string associated with the specified layer. if unsuccessful, the function re
turns null. description a string may be associated with a layer when the layer is created. the string is copied by the runtime, and pr_getnameforidentity re
turns a pointer to that copy. ...
PR_GetOSError
its interpretation is left to the caller. description used for platform-specific code that requires the underlying os error. for portability, clients should not create dependencies on the values of os-specific error codes. however, this information is preserved, along with a platform neutral error code, on a per thread basis. it is most useful during development. ...
PR_GetOpenFileInfo
formation. file size is expressed as a 32-bit integer. syntax #include <prio.h> prstatus pr_getopenfileinfo( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file. info a pointer to a prfileinfo object. on output, information about the given file is written into the file information object. re
turns the function re
turns one of the following values: if file information is successfully obtained, pr_success. if file information is not successfully obtained, pr_failure. description pr_getopenfileinfo obtains the file type (normal file, directory, or other), file size (as a 32-bit integer), and the file creation and modification times of the open file represented by the file descriptor. ...
PR_GetOpenFileInfo64
ation. file size is expressed as a 64-bit integer. syntax #include <prio.h> prstatus pr_getopenfileinfo64( prfiledesc *fd, prfileinfo *info); parameters the function has the following parameters: fd a pointer to a prfiledesc object for an open file. info a pointer to a prfileinfo64 object. on output, information about the given file is written into the file information object. re
turns the function re
turns one of the following values: if file information is successfully obtained, pr_success. if file information is not successfully obtained, pr_failure. description pr_getopenfileinfo64 is the 64-bit version of pr_getopenfileinfo. it obtains the file type (normal file, directory, or other), file size (as a 64-bit integer), and the creation and modification times of the o...
PR_GetPeerName
gets the network address of the connected peer. syntax #include <prio.h> prstatus pr_getpeername( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr on re
turn, the address of the peer connected to the socket. re
turns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetProtoByName
looks up a protocol entry based on the protocol's name. syntax #include <prnetdb.h> prstatus pr_getprotobyname( const char* protocolname, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolname a pointer to the character string of the protocol's name. buffer a pointer to a scratch buffer for the runtime to re
turn result. this buffer is allocated by the caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prprotoent structure. on output, this structure is filled in by the runtime if the function re
turns pr_success. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful...
PR_GetProtoByNumber
looks up a protocol entry based on protocol's number. syntax #include <prnetdb.h> prstatus pr_getprotobynumber( print32 protocolnumber, char* buffer, print32 bufsize, prprotoent* result); parameters the function has the following parameters: protocolnumber the number assigned to the protocol. buffer a pointer to a scratch buffer for the runtime to re
turn result. this buffer is allocated by the caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the function re
turns pr_success. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can ...
PR_GetRandomNoise
ed value for another random number generator. syntax #include <prrng.h> nspr_api(prsize) pr_getrandomnoise( void *buf, prsize size ); parameters the function has these parameters: buf a pointer to a caller-supplied buffer to contain the generated random number. buf must be at least as large as specified in size. size the size, in bytes, of the requested random number. re
turns prsize value equal to the size of the random number actually generated, or zero. the generated size may be less than the size requested. a re
turn value of zero means that pr_getrandomnoise is not implemented on this platform, or there is no available noise to be re
turned at the time of the call. description pr_getrandomnoise provides a random value, depending on platform. the length of the ra...
PR_GetSockName
gets network address for a specified socket. syntax #include <prio.h> prstatus pr_getsockname( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket. addr on re
turn, the address of the socket. re
turns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetSocketOption
lowing parameters: fd a pointer to a prfiledesc object representing the socket whose options are to be retrieved. data a pointer to a structure of type prsocketoptiondata. on input, the option field of this structure must be set to indicate which socket option to retrieve for the socket represented by the fd parameter. on output, this structure contains the requested socket option data. re
turns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetThreadPriority
syntax #include <prthread.h> prthreadpriority pr_getthreadpriority(prthread *thread); parameter pr_getthreadpriority has the following parameter: thread a valid identifier for the thread whose priority you want to know. ...
PR_GetThreadPrivate
recovers the per-thread private data for the current thread. syntax #include <prthread.h> void* pr_getthreadprivate(pruintn index); parameter pr_getthreadprivate has the following parameters: index the index into the per-thread private data table. re
turns null if the data has not been set. description pr_getthreadprivate may be called at any time during a thread's execution. a thread can get access only to its own per-thread private data. do not delete the object that the private data refers to without first clearing the thread's value. ...
PR_GetThreadScope
gets the scoping of the current thread. syntax #include <prthread.h> prthreadscope pr_getthreadscope(void); re
turns a value of type prthreadscope indicating whether the thread is local or global. ...
PR_GetUniqueIdentity
asks the runtime to allocate a unique identity for a layer identified by the layer's name. syntax #include <prio.h> prdescidentity pr_getuniqueidentity(const char *layer_name); parameter the function has the following parameter: layer_name the string associated with the creation of a layer's identity. re
turns the function re
turns one of the following values: if successful, the prdescidentity for the layer associated with the string specified in the layer named layer_name. if the function cannot allocate enough dynamic memory, it fails and re
turns the value pr_invalid_io_layer with the error code pr_out_of_memory_error. description a string may be associated with a layer when the layer is created. pr_getuniqueidentity allocates a unique layer identity and associates it with...
PR_ImplodeTime
converts a clock/calendar time to an absolute time. syntax #include <prtime.h> prtime pr_implodetime(const prexplodedtime *exploded); parameters the function has these parameters: exploded a pointer to the clock/calendar time to be converted. re
turns an absolute time value. description this function converts the specified clock/calendar time to an absolute time and re
turns the converted time value. ...
PR_ImportFileMapFromString
creates a prfilemap from an identifying string. syntax #include <prshma.h> nspr_api( prfilemap * ) pr_importfilemapfromstring( const char *fmstring ); parameter the function has the following parameter: fmstring a pointer to string created by pr_exportfilemapasstring. re
turns prfilemap pointer or null on error. description pr_importfilemapfromstring creates a prfilemap object from a string previously created by pr_exportfilemapasstring. ...
PR ImportTCPSocket
imports a native tcp socket into nspr. syntax #include "private/pprio.h" prfiledesc* pr_importtcpsocket(prosfd osfd); parameters the function has the following parameters: osfd the native file descriptor for the tcp socket to import. on posix systems, this is an int. on windows, this is a socket. re
turns the function re
turns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly imported native tcp socket. if the import of the native tcp socket failed, null. description a native tcp socket osfd can be imported into nspr with pr_importtcpsocket. the caller gives up control of the native tcp socket osfd and should use the prfiledesc* re
turned by pr_importtcpsocket instead. although pr_importtcpsocket is a supported ...
PR_InitializeNetAddr
taddr *addr); parameters the function has the following parameters: val the value to be assigned to the ip address portion of the network address. this must be pr_ipaddrnull, pr_ipaddrany, or pr_ipaddrloopback. port the port number to be assigned in the network address structure. the value is specified in host byte order. addr a pointer to the prnetaddr structure to be manipulated. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occur, for example, if the value of val is not within the ranges defined by prnetaddrvalue. you can retrieve the reason for the failure by calling pr_geterror. description pr_initializenetaddr allows the assignment of special network address values and the port number, while...
PR_Initialized
checks whether the runtime has been initialized. syntax #include <prinit.h> prbool pr_initialized(void); re
turns the function re
turns one of the following values: if pr_init has already been called, pr_true. if pr_init has not already been called, pr_false. ...
PR_IntervalNow
pr_intervalnow() is both very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex. the most common use for pr_intervalnow() is to establish an epoch and test for the expiration of intervals. in this case, you typically call pr_intervalnow() in a sequence that looks like this: pruint32 interval = ... ; // milliseconds // ... ...
PR_IntervalToMicroseconds
converts platform-dependent intervals to standard clock microseconds. syntax #include <prinrval.h> pruint32 pr_intervaltomicroseconds(printervaltime ticks); parameter ticks the number of platform-dependent intervals to convert. re
turns equivalent in microseconds of the value passed in the ticks parameter. description conversion may cause overflow, which is not reported. ...
PR_IntervalToMilliseconds
converts platform-dependent intervals to standard clock milliseconds. syntax #include <prinrval.h> pruint32 pr_intervaltomilliseconds(printervaltime ticks); parameter ticks the number of platform-dependent intervals to convert. re
turns equivalent in milliseconds of the value passed in the ticks parameter. description conversion may cause overflow, which is not reported. ...
PR_IntervalToSeconds
converts platform-dependent intervals to standard clock seconds. syntax #include <prinrval.h> pruint32 pr_intervaltoseconds(printervaltime ticks); parameter ticks the number of platform-dependent intervals to convert. re
turns equivalent in seconds of the value passed in the ticks parameter. description conversion may cause overflow, which is not reported. ...
PR_JoinThreadPool
waits for all threads in a thread pool to complete, then releases resources allocated to the thread pool. syntax #include <prtpool.h> nspr_api(prstatus) pr_jointhreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. re
turns prstatus ...
PR_LIST_HEAD
re
turns the head of a circular list. syntax #include <prclist.h> prclist *pr_list_head (prclist *listp); parameter listp a pointer to the linked list. re
turns a pointer to a list element. description pr_list_head re
turns the head of the specified circular list. ...
PR_LIST_TAIL
re
turns the tail of a circular list. syntax #include <prclist.h> prclist *pr_list_tail (prclist *listp); parameter listp a pointer to the linked list. re
turns a pointer to a list element. description pr_list_tail re
turns the tail of the specified circular list. ...
PR_LOG
o a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug _args a variable length argument list, as if to printf. re
turns nothing description this macro formats the specified arguments and writes the output to the log file, if logging is enabled for the specified module and level. for a description of formatting and format strings, see "formatted printing". for an example of using conditional logging, see use example. this macro compiles to nothing if compile-time options are not ...
PR_LOG_TEST
macro has these parameters: _module a pointer to a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug re
turns pr_true when logging is enabled for the given module and level, otherwise pr_false. description this macro tests whether logging is enabled for the specified module and level. use it as an expression in a conditional execution statement to control logging. see also pr_log. ...
PR_Listen
listens for connections on a specified socket. syntax #include <prio.h> prstatus pr_listen( prfiledesc *fd, printn backlog); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket that will be used to listen for new connections. backlog the maximum length of the queue of pending connections. re
turns the function re
turns one of the following values: upon successful completion of listen request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description pr_listen
turns the specified socket into a rendezvous socket. it creates a queue for pending connections and starts to listen for connection requests on the socket. the maximum size of the queue for pending co...
PR_Lock
locks a specified lock object. syntax #include <prlock.h> void pr_lock(prlock *lock); parameter pr_lock has one parameter: lock a pointer to a lock object to be locked. description when pr_lock re
turns, the calling thread is "in the monitor," also called "holding the monitor's lock." any thread that attempts to acquire the same lock blocks until the holder of the lock exits the monitor. acquiring the lock is not an interruptible operation, nor is there any timeout mechanism. pr_lock is not reentrant. calling it twice on the same thread results in undefined behavior. see also pr_unlock ...
PR_LogFlush
flushes the log buffer to external media. syntax #include <prlog.h> void pr_logflush(void); parameters the function has no parameters. re
turns nothing description this function flushes the log buffer to external media. ...
PR_LogPrint
writes an entry to the log. syntax #include <prlog.h> void pr_logprint(const char *fmt, ...); parameters the function has this parameter: fmt the string that is used as the formatting specification. re
turns nothing description this function unconditionally writes a message to the log using the specified format string. for a description of formatting and format strings, see "formatted printing". ...
PR_MALLOC
allocates memory of a specified size from the heap. syntax #include <prmem.h> void * pr_malloc(_bytes); parameter _bytes size of the requested memory block. re
turns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error re
turned by the libc function malloc(). description this macro allocates memory of the requested size from the heap. ...
PR_MemMap
clude <prio.h> void* pr_memmap( prfilemap *fmap, print64 offset, pruint32 len); parameters the function has the following parameters: fmap a pointer to the file-mapping object representing the file to be memory-mapped. offset the starting offset of the section of file to be mapped. the offset must be aligned to whole pages. len length of the section of the file to be mapped. re
turns the starting address of the memory region to which the section of file is mapped. re
turns null on error. description pr_memmap maps a section of the file represented by the file mapping fmap to memory. the section of the file starts at offset and has the length len. when the file-mapping memory region is no longer needed, it should be unmapped with a call to pr_memunmap. ...
PR_MicrosecondsToInterval
converts standard clock microseconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_microsecondstointerval(pruint32 milli); parameter the function has the following parameter: micro the number of microseconds to convert to interval form. re
turns platform-dependent equivalent of the value passed in the micro parameter. ...
PR_MillisecondsToInterval
converts standard clock milliseconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_millisecondstointerval(pruint32 milli); parameter the function has the following parameter: milli the number of milliseconds to convert to interval form. re
turns platform-dependent equivalent of the value passed in the milli parameter. ...
PR_MkDir
caveat: the mode parameter is currently applicable only on unix platforms. it may be applicable to other platforms in the future. possible values include the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by others. 00002. write by others. 00001. search by others. re
turns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_mkdir creates a new directory with the pathname name. all the path components up to but not including the leaf component must already exist. for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist. see also pr_r...
PR_NEW
allocates memory of a specified size from the heap. syntax #include <prmem.h> _type * pr_new(_struct); parameter _struct the name of a type. re
turns an pointer to a buffer sized to contain the type _struct, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error re
turned by the libc function. description this macro allocates memory whose size is sizeof(_struct) and re
turns a pointer to that memory. ...
PR_NEWZAP
allocates and clears memory from the heap for an instance of a given type. syntax #include <prmem.h> _type * pr_newzap(_struct); parameter _struct the name of a type. re
turns an pointer to a buffer sized to contain the type _struct, or if the allocation attempt fails, null. the bytes in the buffer are all initialized to 0. call pr_geterror() to retrieve the error re
turned by the libc function. description this macro allocates an instance of the specified type from the heap and sets the content of that memory to zero. ...
PR_NOT_REACHED
terminates the calling application with a message to the log. syntax #include <prlog.h> void pr_not_reached(const char *_reasonstr); parameters the macro has this parameter: reasonstr a string that describes why you should not have reached this statement. re
turns nothing description this macro writes the specified reason string to the log and terminates the application. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_NetAddrToString
onverts a character string to a network address. syntax #include <prnetdb.h> prstatus pr_netaddrtostring( const prnetaddr *addr, char *string, pruint32 size); parameters the function has the following parameters: addr a pointer to the network address to be converted. string a buffer that will hold the converted string on output. size the size of the result buffer (string). re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description the network address to be converted (addr) may be either an ipv4 or ipv6 address structure, assuming that the nspr library and the host system are both configured to utilize ipv6 addressing. if addr is an...
PR_NewCondVar
creates a new condition variable. syntax #include <prcvar.h> prcondvar* pr_newcondvar(prlock *lock); parameter pr_newcondvar has one parameter: lock the identity of the mutex that protects the monitored data, including this condition variable. re
turns the function re
turns one of the following values: if successful, a pointer to the new condition variable object. if unsuccessful (for example, if system resources are unavailable), null. ...
PR_NewLock
creates a new lock. syntax #include <prlock.h> prlock* pr_newlock(void); re
turns the function re
turns one of the following values: if successful, a pointer to the new lock object. if unsuccessful (for example, the lock cannot be created because of resource constraints), null. description pr_newlock creates a new opaque lock. ...
PR_NewLogModule
creates a new log module. syntax #include <prlog.h> prlogmoduleinfo* pr_newlogmodule(const char *name); parameters the function has this parameter: name the name to be assigned to the prlogmoduleinfo structure. re
turns a pointer to a prlogmoduleinfo structure. description this function allocates and initializes a new prlogmoduleinfo structure with the specified name. if the environment variable nspr_log_modules contains the specified name, then the associated level value from the variable is associated with the new prlogmoduleinfo structure. ...
PR_NewMonitor
creates a new monitor object. the caller is responsible for the object and is expected to destroy it when appropriate. syntax #include <prmon.h> prmonitor* pr_newmonitor(void); re
turns the function re
turns one of the following values: if successful, a pointer to a prmonitor object. if unsuccessful (for example, if some operating system resource is unavailable), null. description a newly created monitor has an entry count of zero. ...
PR_NewPollableEvent
create a pollable event file descriptor. syntax nspr_api(prfiledesc *) pr_newpollableevent( void); parameter none. re
turns pointer to prfiledesc or null, on error. ...
PR NewProcessAttr
creates a process attributes structure. syntax #include <prlink.h> prprocessattr *pr_newprocessattr(void); parameters the function has no parameters. re
turns a pointer to the new process attributes structure. description this function creates a new prprocessattr structure that specifies the attributes of a new process, then re
turns a pointer to the structure. the new prprocessattr structure is initialized with these default attributes: the standard i/o streams (standard input, standard output, and standard error) are not redirected. no file descriptors are inherited by the new process. ...
PR_NewTCPSocket
if the creation of a new tcp socket failed, null. description tcp (transmission control protocol) is a connection-oriented, reliable byte-stream protocol of the tcp/ip protocol suite. pr_newtcpsocket creates a new ipv4 tcp socket. a tcp connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). ...
PR_NewUDPSocket
if the creation of a new udp socket failed, null. description udp (user datagram protocol) is a connectionless, unreliable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_newudpsocket creates a new udp socket. the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. ...
PR_Notify
notifies a monitor that a change in state of the monitored data has occurred. syntax #include <prmon.h> prstatus pr_notify(prmonitor *mon); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. description notification of a monitor signals the change of state of some monitored data. the changing of that data and the notification must all be performed while in the monitor. when the notification occurs, the runtime promotes a thread that is waiting on the monitor to a ready state. if more than one thread is wa...
PR_NotifyAll
promotes all threads waiting on a specified monitor to a ready state. syntax #include <prmon.h> prstatus pr_notifyall(prmonitor *mon); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. description a call to pr_notifyall causes all of the threads waiting on the monitor to be scheduled to be promoted to a ready state. if no threads are waiting, the operation is no-op. pr_notifyall should be used with some care. the expense of scheduling multiple threads increases dramatically as the number of threads incr...
PR_NotifyAllCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure. description the calling thread must hold the lock that protects the condition, as well as the invariants that are tightly bound to the condition. ...
PR_OpenAnonFileMap
a named semaphore with the specified name syntax #include <prshma.h> nspr_api( prfilemap *) pr_openanonfilemap( const char *dirname, prsize size, prfilemapprotect prot ); parameters the function has the following parameters: dirname a pointer to a directory name that will contain the anonymous file. size the size of the shared memory. prot how the shared memory is mapped. re
turns pointer to prfilemap or null on error. description if the shared memory already exists, a handle is re
turned to that shared memory object. on unix platforms, pr_openanonfilemap uses dirname as a directory name, without the trailing '/', to contain the anonymous file. a filename is generated for the name. on windows platforms, dirname is ignored. ...
PR_OpenDir
opens the directory with the specified pathname. syntax #include <prio.h> prdir* pr_opendir(const char *name); parameter the function has the following parameter: name the pathname of the directory to be opened. re
turns if the directory is successfully opened, a prdir object is dynamically allocated and the function re
turns a pointer to it. if the directory cannot be opened, the function re
turns null. description pr_opendir opens the directory specified by the pathname name and re
turns a pointer to a directory stream (a prdir object) that can be passed to subsequent pr_readdir calls to get the directory entries (files and subdirectories) in the directory. the prdir pointer should eventually be closed by a call to pr_closedir. ...
PR_OpenSemaphore
if already exists */ nspr_api(prsem *) pr_opensemaphore( const char *name, printn flags, printn mode, pruintn value ); parameters the function has the following parameters: name the name to be given the semaphore. flags how to create or open the semaphore. mode unix style file mode to be used when creating the semaphore. value the initial value assigned to the semaphore. re
turns a pointer to a prsem structure or null/code> on error. description if the named semaphore doesn't exist and the pr_sem_create flag is specified, the named semaphore is created. the created semaphore needs to be removed from the system with a pr_deletesemaphore call. if pr_sem_create is specified, the third argument is the access permission bits of the new semaphore (same interpretation as t...
PR_OpenTCPSocket
creates a new tcp socket of the specified address family. syntax #include <prio.h> prfiledesc* pr_opentcpsocket(printn af); parameters the function has the following parameters: af the address family of the new tcp socket. can be pr_af_inet (ipv4), pr_af_inet6 (ipv6), or pr_af_local (unix domain, supported on posix systems only). re
turns the function re
turns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened tcp socket. if the creation of a new tcp socket failed, null. description tcp (transmission control protocol) is a connection-oriented, reliable byte-stream protocol of the tcp/ip protocol suite. pr_opentcpsocket creates a new tcp socket of the address family af. a tcp connection is established by a ...
PR OpenUDPSocket
creates a new udp socket of the specified address family. syntax #include <prio.h> prfiledesc* pr_openudpsocket(printn af); parameters the function has the following parameters: af the address family of the new udp socket. can be pr_af_inet (ipv4), pr_af_inet6 (ipv6), or pr_af_local (unix domain, supported on posix systems only). re
turns the function re
turns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket. if the creation of a new udp socket failed, null. description udp (user datagram protocol) is a connectionless, unreliable datagram protocol of the tcp/ip protocol suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_openudpsocket creates a new udp socket of...
PR_ProcessAttrSetInheritableFileMap
) pr_processattrsetinheritablefilemap( prprocessattr *attr, prfilemap *fm, const char *shmname ); parameters the function has the following parameters: attr pointer to a prprocessattr structure used to pass data to pr_createprocess. fm pointer to a prfilemap structure to be passed to the child process. shmname pointer to the name for the prfilemap; used by child. re
turns prstatus description pr_processattrsetinheritablefilemap connects the prfilemap to prprocessattr with shmname. a subsequent call to pr_createprocess makes the prfilemap importable by the child process. note: this function is not implemented. ...
PR_QueueJob_Timer
pool structure previously created by a call to pr_createthreadpool. iod a pointer to a prjobiodesc structure. timeout a value, expressed as a printervaltime, to wait before queuing the job. fn the function to be executed when the job is executed. arg a pointer to an argument passed to fn. joinable if pr_true, the job is joinable. if pr_false, the job is not joinable. see pr_joinjob. re
turns pointer to a prjob structure or null on error. ...
PR_Realloc
resizes allocated memory on the heap. syntax #include <prmem.h> void *pr_realloc ( void *ptr, pruint32 size); parameters ptr a pointer to the existing memory block being resized. size the size of the new memory block. re
turns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error re
turned by the libc function realloc(). description this function attempts to enlarge or shrink the memory block addressed by ptr to a new size. the contents of the specified memory remains the same up to the smaller of its old size and new size, although the new memory block's address can be different from the original address. ...
PR_Read
s from a file or socket. syntax #include <prio.h> print32 pr_read(prfiledesc *fd, void *buf, print32 amount); parameters the function has the following parameters: fd a pointer to a prfiledesc object for the file or socket. buf a pointer to a buffer to hold the data read in. on output, the buffer contains the data. amount the size of buf (in bytes). re
turns one of the following values: a positive number indicates the number of bytes actually read in. the value 0 means end of file is reached or the network connection is closed. the value -1 indicates a failure. to get the reason for the failure, call pr_geterror. description the thread invoking pr_read blocks until it encounters an end-of-stream indication, some positive number of bytes (bu...
PR_Recv
intn flags, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer to hold the data received. amount the size of buf (in bytes). flags must be zero or pr_msg_peek. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. re
turns the function re
turns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_recv blocks until some positive number of bytes are transferred, a timeout occurs, or an error occurs. n...
PR_RecvFrom
printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data received. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. addr a pointer to the prnetaddr object that will be filled in with the address of the sending peer on re
turn. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. re
turns the function re
turns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. de...
PR_Rename
if file is not successfully renamed, pr_failure. ...
PR_RmDir
removes a directory with a specified name. syntax #include <prio.h> prstatus pr_rmdir(const char *name); parameter the function has the following parameter: name the name of the directory to be removed. re
turns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_rmdir removes the directory specified by the pathname name. the directory must be empty. if the directory is not empty, pr_rmdir fails and pr_geterror re
turns the error code pr_directory_not_empty_error. see also pr_mkdir ...
PR_STATIC_ASSERT
s code from compiling when an expression has the value false at compile time. syntax #include <prlog.h> pr_static_assert ( expression ); parameters the macro has this parameter: expression any valid expression which evaluates at compile-time to true or false. an expression which cannot be evaluated at compile time will cause a compiler error; see pr_assert for a runtime alternative. re
turns nothing description this macro evaluates the specified expression. when the result is zero (false) program compilation will fail with a compiler error; otherwise compilation completes successfully. the compiler error will include the number of the line for which the compile-time assertion failed. this macro may only be used in locations where an extern function declaration may be used. ...
PR_SecondsToInterval
converts standard clock seconds to platform-dependent intervals. syntax #include <prinrval.h> printervaltime pr_secondstointerval(pruint32 seconds); parameter the function has the following parameter: seconds the number of seconds to convert to interval form. re
turns platform-dependent equivalent of the value passed in the seconds parameter. ...
PR_Seek
e file pointer associated with the fd parameter. the value for the whence parameter can be one of the following: pr_seek_set. sets the file pointer to the value of the offset parameter. pr_seek_cur. sets the file pointer to its current location plus the value of the offset parameter. pr_seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. re
turns the function re
turns one of the following values: if the function completes successfully, it re
turns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function re
turns -1. the error code can then be retrieved with pr_geterror. description here's an idiom for obtaining the current locati...
PR_Seek64
e file pointer associated with the fd parameter. the value for the whence parameter can be one of the following: pr_seek_set. sets the file pointer to the value of the offset parameter. pr_seek_cur. sets the file pointer to its current location plus the value of the offset parameter. pr_seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. re
turns the function re
turns one of the following values: if the function completes successfully, it re
turns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function re
turns -1. the error code can then be retrieved with pr_geterror. description this is the idiom for obtaining the current loca...
PR_Send
valtime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data to be sent. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. re
turns the function re
turns one of the following values: a positive number indicates the number of bytes successfully sent. if the parameter fd is a blocking socket, this number must always equal amount. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_send blocks until all bytes are sent, a timeout occurs, or an error occurs. ...
PR_SendTo
following parameters: fd a pointer to a prfiledesc object representing a socket. buf a pointer to a buffer containing the data to be sent. amount the size of buf (in bytes). flags this obsolete parameter must always be zero. addr a pointer to the address of the destination. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. re
turns the function re
turns one of the following values: a positive number indicates the number of bytes successfully sent. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_sendto sends a specified number of bytes from a socket to the specified destination address. the calling thread blocks until all bytes are sent, a timeout ha...
PR_SetLibraryPath
registers a default library pathname with a runtime. syntax #include <prlink.h> prstatus pr_setlibrarypath(const char *path); parameters the function has this parameter: path a pointer to a character array that contains the directory path that the application should use as a default. the syntax of the pathname is not defined, nor whether that pathname should be absolute or relative. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may indicate that the function cannot allocate sufficient storage to make a copy of the path string description this function registers a default library pathname with the runtime. this allows an environment to express policy decisions globally and lazily, rather than hardcoding...
PR_SetLogBuffering
sets the level of buffering for the log file. syntax #include <prlog.h> void pr_setlogbuffering(printn buffer_size); parameters the function has this parameter: buffer_size the size of the buffer to be used for logging. re
turns nothing description this function sets the size of the buffer used in nspr logging. ordinarily, a user application need not use this function, as nspr initializes logging at nspr startup. the application can use the model provided in use example to effect application logging. ...
PR_SetLogFile
otherwise, pr_false. description creates a log file with the specified file name. ...
PR_SetPollableEvent
set a pollable event. syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_SetSocketOption
eves the socket options set for a specified socket. syntax #include <prio.h> prstatus pr_setsocketoption( prfiledesc *fd, prsocketoptiondata *data); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket whose options are to be set. data a pointer to a structure of type prsocketoptiondata specifying the options to set. re
turns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. description on input, the caller must set both the option and value fields of the prsocketoptiondata object pointed to by the data parameter. ...
PR_Shutdown
s the function has the following parameters: fd a pointer to a prfiledesc object representing a connected socket. how the kind of disallowed operations on the socket. possible values include the following: pr_shutdown_rcv. further receives will be disallowed. pr_shutdown_send. further sends will be disallowed. pr_shutdown_both. further sends and receives will be disallowed. re
turns the function re
turns one of the following values: upon successful completion of shutdown request, pr_success. if unsuccessful, pr_failure. further information can be obtained by calling pr_geterror. description the prshutdownhow enumeration is defined as follows: typedef enum prshutdownhow{ pr_shutdown_rcv = 0, pr_shutdown_send = 1, pr_shutdown_both = 2 } prshutdownhow; ...
PR_ShutdownThreadPool
notifies all threads in a thread pool to terminate. syntax #include <prtpool.h> nspr_api(prstatus) pr_shutdownthreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. re
turns prstatus ...
PR_Sleep
description pr_sleep simply waits on a condition for the amount of time specified. ...
PR_Sync
synchronizes any buffered data for a file descriptor to its backing device (disk). syntax #include <prio.h> prstatus pr_sync(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file. re
turns the function re
turns one of the following values: on successful completion, pr_success. if the function fails, pr_failure. description pr_sync writes all the in-memory buffered data of the specified file to the disk. ...
PR_TransmitFile
before sending data. hlen length of the headers buffer in bytes. flags one of the following flags: pr_transmitfile_keep_open indicates that the socket will be kept open after the data is sent. pr_transmitfile_close_socket indicates that the connection should be closed immediately after successful transfer of the file. timeout time limit for completion of the transmit operation. re
turns a positive number indicates the number of bytes successfully written, including both the headers and the file. the value -1 indicates a failure. if an error occurs while sending the file, the pr_transmitfile_close_socket flag is ignored. the reason for the failure can be obtained by calling pr_geterror. description the pr_transmitfile function sends a complete file (sourcefile) across a c...
PR_UnloadLibrary
unloads a library loaded with pr_loadlibrary. syntax #include <prlink.h> prstatus pr_unloadlibrary(prlibrary *lib); parameters the function has this parameter: lib a reference previously re
turned from pr_loadlibrary. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. use pr_geterror to find the reason for the failure. description this function undoes the effect of a pr_loadlibrary. after calling this function, future references to the library using its identity as re
turned by pr_loadlibrary will be invalid. ...
PR_Unlock
releases a specified lock object. releasing an unlocked lock results in an error. attempting to release a lock that was locked by a different thread causes undefined behavior. syntax #include <prlock.h> prstatus pr_unlock(prlock *lock); parameter pr_unlock has one parameter: lock a pointer to a lock object to be released. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller does not own the lock), pr_failure. see also pr_lock ...
PR_Unmap
unmap a memory region that is backed by a memory-mapped file. syntax #include <prio.h> prstatus pr_memunmap( void *addr, pruint32 len); parameters the function has the following parameters: addr the starting address of the memory region to be unmapped. len the length, in bytes, of the memory region. re
turns the function re
turns one of the following values: if the memory region is successfully unmapped, pr_success. if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. description pr_memunmap removes the file mapping for the memory region (addr, addr + len). the parameter addr is the re
turn value of an earlier call to pr_memmap. ...
PR_VersionCheck
compares the version of nspr assumed by the caller (the imported version) with the version being offered by the runtime (the exported version). syntax #include <prinit.h> prbool pr_versioncheck(const char *importedversion); parameter pr_versioncheck has one parameter: importedversion the version of the shared library being imported. re
turns the function re
turns one of the following values: if the version of the shared library is compatible with that expected by the caller, pr_true. if the versions are not compatible, pr_false. description pr_versioncheck tests whether the version of the library being imported (importedversion) is compatible with the running version of the shared library. this is a string comparison of sorts, though the details of the comparison will vary o...
PR_Wait
itor *mon, printervaltime ticks); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. ticks the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. re
turns the function re
turns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired. pr_failure means pr_wait encountered a system error (such as an invalid monitor reference) or the thread was interrupted by another thread. description a call to pr_...
PR_WaitCondVar
llowing parameters: cvar the condition variable on which to wait. timeout the value pr_interval_no_timeout requires that a condition be notified (or the thread interrupted) before it will resume from the wait. the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure. the details can be determined with pr_geterror. description before the call to pr_waitcondvar, the lock associated with the condition variable m...
PR_WaitForPollableEvent
blocks the calling thread until the pollable event is set, and then atomically unsetting the event before re
turning. syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. re
turns the function re
turns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_cnvtf
to store the result. bufsz the size of the buffer provided to hold the result. prcsn the number of digits of precision to which to generate the floating point value. fval the double-precision floating point number to be converted. description pr_cnvtf is a simpler interface to convert a floating point number to a string. it conforms to the ecma standard of javascript (ecmascript). on re
turn, the result is written to the buffer pointed to by buf of size bufsz. ...
PR_htonl
performs 32-bit conversion from host byte order to network byte order. syntax #include <prnetdb.h> pruint32 pr_htonl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in host byte order, to be converted. re
turns the value of the conversion parameter in network byte order. ...
PR_htons
performs 16-bit conversion from host byte order to network byte order. syntax #include <prnetdb.h> pruint16 pr_htons(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in host byte order, to be converted. re
turns the value of the conversion parameter in network byte order. ...
PR_ntohl
performs 32-bit conversion from network byte order to host byte order. syntax #include <prnetdb.h> pruint32 pr_ntohl(pruint32 conversion); parameter the function has the following parameter: conversion the 32-bit unsigned integer, in network byte order, to be converted. re
turns the value of the conversion parameter in host byte order. ...
PR_ntohs
performs 16-bit conversion from network byte order to host byte order. syntax #include <prnetdb.h> pruint16 pr_ntohs(pruint16 conversion); parameter the function has the following parameter: conversion the 16-bit unsigned integer, in network byte order, to be converted. re
turns the value of the conversion parameter in host byte order. ...
NSPR API Reference
onitors condition variables nspr sample code nspr types calling convention types algebraic types 8-, 16-, and 32-bit integer types signed integers unsigned integers 64-bit integer types floating-point integer type native os integer types miscellaneous types size type pointer difference types boolean types status type for re
turn values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities controlling per-thread private data interrupting and yielding setting global thread concurrency getting a thread's scope process initialization identity and versioning name and version constants initializat...
NSS CERTVerify Log
log parameter, nss will continue chain validation after each error . the log tells you what the problem was with the chain and what certificate in the chain failed. to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function. on re
turn: log->count is the number of entries. log->head is the first entry; log->tail is the last entry. each entry is a certverifylognode. defined in certt.h: /* * this structure is used to keep a log of errors when verifying * a cert chain. this allows multiple errors to be reported all at * once. */ struct certverifylognodestr { certcertificate *cert; /* what cert had the error */ long...
CERT_FindCertByDERCert
ointer to an secitem whose type must be sidercertbuffer and whose data contains a der-encoded certificate description this function looks in the ?nsscryptocontext? and the ?nsstrustdomain? to find the certificate that matches the der-encoded certificate. a match is found when the issuer and serial number of the der-encoded certificate are found on a certificate in the certificate database. re
turns a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. see also occurrences of cert_findcertbydercert in the current nss source code (generated by lxr). ...
CERT_FindCertByIssuerAndSN
; parameters handle in pointer to a certcertdbhandle representing the certificate database to look in issuerandsn in pointer to a certissuerandsn that must be properly formed to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database. re
turns a pointer to a certcertificate representing the certificate in the database that matched the issuer and serial number, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. example certissuerandsn issuersn; issuersn.derissuer.data = caname->data; issuersn.derissuer.len = caname->len; issuersn.se...
Cryptography functions
mxr 3.2 and later pk11_hasrootcerts mxr 3.4 and later pk11_importcert mxr 3.5 and later pk11_importcertforkeytoslot mxr 3.2 and later pk11_importcrl mxr 3.6 and later pk11_importdercert mxr 3.6 and later pk11_importderprivatekeyinfoandre
turnkey mxr 3.4 and later pk11_importencryptedprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfoandre
turnkey mxr 3.4 and later pk11_importpublickey mxr 3.4 and later pk11_importsymkeywithflags mxr 3.4...
HTTP delegation
for function sec_registerdefaulthttpclient and all functions having names that start with sec_http. to find an example 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 re
turns 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.
HTTP delegation
for function sec_registerdefaulthttpclient and all functions having names that start with sec_http. to find an example 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 re
turns 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.
NSS 3.46.1 release notes
lls: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_46_1_rtm/src/ other releases are available in nss releases. new in nss 3.46.1 no new functionality is introduced in this release. bugs fixed in nss 3.46.1 bug 1582343 - soft token mac verification not constant time bug 1577953 - remove arbitrary hkdf output limit by allocating space as needed this bugzilla query re
turns all the bugs fixed in nss 3.46.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.46.1 compatibility nss 3.46.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.46.1 shared libraries without recompil...
NSS 3.47.1 release notes
eases are available in nss releases. new in nss 3.47.1 no new functionality is introduced in this release. bugs fixed in nss 3.47.1 cve-2019-11745 - encryptupdate should use maxout, not block size bug 1590495 - fix a crash that could be caused by client certificates during startup bug 1589810 - fix compile-time warnings from uninitialized variables in a perl script this bugzilla query re
turns all the bugs fixed in nss 3.47: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.47 compatibility nss 3.47.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.47.1 shared libraries without recompiling ...
NSS 3.48.1 release notes
ttps://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_48_1_rtm/src/ other releases are available in nss releases. new in nss 3.48.1 no new functionality is introduced in this release. bugs fixed in nss 3.48.1 bug 1606992 - cache the most recent pbkdf2 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. this bugzilla query re
turns all the bugs fixed in nss 3.48: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.48 compatibility nss 3.48.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.48.1 shared libraries without recompiling ...
NSS 3.48 release notes
a program linked with older nss 3.x shared libraries will work with nss 3.48 shared libraries without recompiling or r...
NSS 3.49.1 release notes
ttps://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_49_1_rtm/src/ other releases are available in nss releases. new in nss 3.49.1 no new functionality is introduced in this release. bugs fixed in nss 3.49.1 bug 1606992 - cache the most recent pbkdf2 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. this bugzilla query re
turns all the bugs fixed in nss 3.49: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.49 compatibility nss 3.49.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.49.1 shared libraries without recompiling ...
NSS 3.49.2 release notes
cache the most recent pbkdf1 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. nss 3.49.1 sped up pbkdf2 operations, though pbkdf1 operations are also relevant for older nss databases. bug 1608327 - fix compilation problems with neon-specific code in freebl bug 1608895 - fix a taskcluster issue with python 2 / python 3 this bugzilla query re
turns all the bugs fixed in nss 3.49: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.49 compatibility nss 3.49.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.49.2 shared libraries without recompiling ...
NSS 3.49 release notes
a program linked with older nss 3.x shared libraries will work with nss 3.49 shared libraries without recompiling or r...
NSS 3.50 release notes
tation, such as macos. bug 1547639 - update zlib in nss to 1.2.11 bug 1609181 - detect arm (32-bit) cpu features on freebsd bug 1602386 - fix build on freebsd/powerpc* bug 1608151 - introduce nss_disable_altivec bug 1612623 - depend on nspr 4.25 bug 1609673 - fix a crash when nss is compiled without libnssdbm support, but the nssdbm shared object is available anyway. this bugzilla query re
turns all the bugs fixed in nss 3.50: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.50 compatibility nss 3.50 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.50 shared libraries without recompiling or r...
NSS 3.51 release notes
a program linked with older nss 3.x shared libraries will work with nss 3.51 shared libraries without recompiling or r...
NSS 3.52 release notes
onid or using external cache. bug 1465613 - fix issue where testlib makefile build produced extraneous object files. bug 1619959 - properly handle multi-block seed ecb inputs. bug 1630925 - guard all instances of nsscmssigneddata.signerinfo to avoid a cms crash bug 1571677 - name constraints validation: cn treated as dns name even when syntactically invalid as dns name this bugzilla query re
turns all the bugs fixed in nss 3.52: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.52 compatibility nss 3.52 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.52 shared libraries without recompiling or r...
NSS 3.53 release notes
a program linked with older nss 3.x shared libraries will work with nss 3.53 shared libraries without recompiling or r...
NSS 3.54 release notes
enable ssl_sendsessionticket after resumption. bug 1643123 - support ssl_exportearlykeyingmaterial with external psks. bug 1643557 - fix numerous compile warnings in nss. bug 1644774 - ssl gtests to use clearservercache when resetting self-encrypt keys. bug 1645479 - don't use secitem_makeitem in secutil.c. bug 1646520 - stricter enforcement of asn.1 integer encoding. this bugzilla query re
turns all the bugs fixed in nss 3.54: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.54 compatibility nss 3.54 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.54 shared libraries without recompiling or r...
NSS 3.55 release notes
g 1637222 - consistently enforce iv requirements for des and 3des. bug 1067214 - enforce minimum pkcs#1 v1.5 padding length in rsa_checksignrecover. bug 1643528 - fix compilation error with -werror=strict-prototypes. bug 1646324 - advertise pkcs#1 schemes for certificates in the signature_algorithms extension. bug 1652331 - update nss 3.55 nspr version to 4.27. this bugzilla query re
turns all the bugs fixed in nss 3.55: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.55 compatibility nss 3.55 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.55 shared libraries without recompiling or r...
NSS 3.56 release notes
makefile cross-compilation. bug 1625791 - fix deadlock issue in nssslot_istokenpresent. bug 1653975 - fix 3.53 regression by setting "all" as the default makefile target. bug 1659792 - fix broken libpkix tests with unexpired paypal cert. bug 1659814 - fix interop.sh failures with newer tls-interop commit and dependencies. bug 1656519 - update nspr dependency to 4.28. this bugzilla query re
turns all the bugs fixed in nss 3.56: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.56 compatibility nss 3.56 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.56 shared libraries without recompiling or r...
NSS Developer Tutorial
ine2 */ or /* line1 * line2 */ naming public functions are named foo_dooneaction. global, but unexported functions, are usually named foo_dooneaction. variable, and function parameter names, always start with a lowercase letter. the most common style is foobarbaz, although foobarbaz and foo_bar_baz are also used. miscellaneous goto can be used, to simplify resource deallocation, before re
turning from a function. a data buffer is usually represented as: unsigned char *data; unsigned int len; the buffer pointer is unsigned char *, as opposed to void *, so we can perform pointer arithmetic without casting. use char * only if the data is interpreted as text characters. for historical reasons, the buffer length is unsigned int, as opposed to size_t. unfortunately, this can be a...
NSS functions
mxr 3.2 and later pk11_hasrootcerts mxr 3.4 and later pk11_importcert mxr 3.5 and later pk11_importcertforkeytoslot mxr 3.2 and later pk11_importcrl mxr 3.6 and later pk11_importdercert mxr 3.6 and later pk11_importderprivatekeyinfoandre
turnkey mxr 3.4 and later pk11_importencryptedprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfo mxr 3.2 and later pk11_importprivatekeyinfoandre
turnkey mxr 3.4 and later pk11_importpublickey mxr 3.4 and later pk11_importsymkeywithflags mxr 3.4...
gtstd.html
cs #11 module that supports pkcs #11 can be used with the nss libraries. netscape software uses a file called secmod.db to keep track of the modules available. a pkcs #11 module always has one or more slots, which may be implemented as physical hardware slots in some form of physical reader (for example, for smart cards) or as conceptual slots in software. each slot for a pkcs #11 module can in
turn contain a token, which is the hardware or software device that actually provides cryptographic services and optionally stores certificates and keys. netscape provides three built-in modules with nss and with server and client products: the default netscape internal pkcs #11 module comes with two built-in tokens: the generic crypto services token performs all cryptographic operat...
sslintro.html
plication typically begins by opening a new socket and then importing the new socket into the ssl environment: pr_newtcpsocket. opens a new socket. a legal nspr socket is required to be passed to ssl_importfd, whether it is created with this function or by another method. ssl_importfd. makes an nspr socket into an ssl socket. required. brings an ordinary nspr socket into the ssl library, re
turning a new nspr socket that can be used to make ssl calls. you can pass this function a model file descriptor to create the new ssl socket with the same configuration state as the model. it is also possible for an application to import a socket into ssl after the tcp connection on that socket has already been established. in this case, initial configuration takes place in the same way: pass the e...
NSS Tools modutil
st <null>value ---> key_value_pair stringkey_value_pair --> key { valuelist }key --> stringstring --> simple_string "complex_string"simple_string --> [^ \t\n\""{""}"]+ (no whitespace, quotes, or braces.)complex_string --> ([^\"\\\r\n]|(\\\")|(\\\\))+ (quotes andbackslashes must be escaped with a backslash. a complex string must notinclude newlines or carriage re
turns.) outside of complex strings, all white space (for example, spaces, tabs, and carriage re
turns) is considered equal and is used only to delimit tokens. keys keys are case-insensitive. this section discusses the following keys: global keysper-platform keysper-file keys global keys forwardcompatible gives a list of platforms that are forward compatible. if the current platform ca...
NSS Tools pk12util
ay be the softtoken module or an external hardware module. it may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. if no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the error message. ...
NSS Tools sslstrength
restricts the available ciphers to the same set used by communicator. in addition to this, the ciphers command can be used to further restrict the ciphers available. the argument to the ciphers command is a string of characters, where each single character represents a cipher. you can obtain this list of character->cipher mappings by doing 'sslstrength ciphers'. for example, ciphers=bfi will
turn on these cipher preferences and
turn off all others. policy=export or policy=domestic will set your policies appropriately. policy will default to domestic if not specified. step-up step up is a mode where the connection starts out with 40-bit encryption, but due to a 'change-cipher-spec' handshake, changes to 128-bit encryption. this is only done in 'export mode', with servers with a...
Proxies in Necko
he type of the proxy info, it either asks the http protocol handler or the protocol handler for the requested uri for a new channel with the nsiproxyinfo - if the channel supports nsiproxiedprotocolhandler. otherwise, the proxy info is discarded. nsiprotocolproxyservice the most important function on nsiprotocolproxyservice is resolve. it checks whether the passed-in uri should use a proxy, and re
turns an nsiproxyinfo if so. this works by examining the protocolflags of the protocol handler for the given uri. if this protocol handler does not support proxies, resolve re
turns null. alternatively, if proxies are disabled, or this host is in the list of hosts for which no proxy should be used, null is also re
turned. if pac (proxy autoconfiguration) is enabled, it is asked for the proxy string for ...
The JavaScript Runtime
mode is supported. when scripts are compiled in interpretive mode, an internal representation of the compiled form is created and stored rather than generating a java class. execution proceeds by evaluating this compiled form using support routines in rhino. compilation to java bytecodes for improved performance, rhino may compile javascript scripts to java bytecodes. the generated bytecodes in
turn depend upon runtime support routines. each javascript script or function is compiled to a separate class. compilation of javascript source to class files is supported. it is possible to specify the class files as well as the packages to generate into. types and values there are six fundamental types in javascript. these types are implemented with the following java types and values: ...
Rhino scopes and contexts
ne context associated with each thread that will be executing javascript. to associate the current thread with a context, simply call the enter method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be re
turned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. scopes a scope is a set of javascript objects. execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like f...
GCIntegration - SpiderMonkey Redirect 1
s, that some code has read the weak pointer to c and then created a regular (strong) reference from b to c. now c is reachable, but it won't be marked because b was already fully marked. no write barrier is invoked when creating the pointer from b to c because no pointer is being destroyed. as a concrete example of this, imagine that we call getwrapper() on an nswrappercache instance. this will re
turn a jsobject *. then this pointer is installed as a property on another jsobject that was already marked. the solution to this problem is to require a read barrier on every weak reference. whenever the weak pointer is read during incremental marking, we mark the object that it points to. in the example above, c would be marked when reading it out of a. a very simple way to identify weak pointers ...
Bytecodes
the local variables used by the current code. expression slots: holds the temporary space that you need to calculate expressions on a stack. for example, in (a + b) + c you would push a, then push b, then add, then push c, then add, which requires a maximum depth of two expression slots. there are also some slots reserved for dedicated functionality, holding values like this and the callee / re
turn value. there is always a "top of stack" (tos) that corresponds to the latest value pushed onto the expression stack. all bytecodes implicitly operate in terms of this location. bytecode listing all opcodes are annotated with a [-popcount, +pushcount] to represent the overall stack-effects their execution. bytecode listing was moved to spidermonkey internals: bytecode descriptions page. ...
Garbage collection
essentially a cell** that the gc knows about.) root a starting point to the gc graph traversal, a root is known to be alive for some external reason (one other than being reachable by some other part of the gc heap.) weak pointer in common cs terminology, a weak pointer is one that doesn't keep the pointed-to value live for gc purposes. typically, a weak pointer value has a get() method that re
turns a null pointer if the object has been gc'd. in gecko/spidermonkey, a weak pointer is a pointer to an object that can be gc'd that is not marked through. thus, there is no get() method and no protection against the pointed-to value getting gc'd--the programmer must ensure that the lifetime of the pointed-to object contains the lifetime of the weak pointer. todo make sure this is correct. white ...
SpiderMonkey Internals: Thread Safety
ion handling, for example, is per-jscontext. each jscontext must be used by only one thread at a time. a single jscontext can run work with code and objects in multiple compartments as long as no other thread is accessing those compartments. objects may be shared among jscontexts within a jscompartment. there's no fixed association between an object and a context. thread-safety in spidermonkey is
turned on by compiling with -djs_threadsafe. in a js_threadsafe build, these operations are handled specially: access to jsruntime data structures garbage collection accesses to jsruntime data structures are serialized with a few mutexes. the treatment of gc requires more explanation. making gc thread-safe with js_threadsafe, the api changes slightly. the program must group jsapi calls into "reque...
INT_FITS_IN_JSVAL
removed at any time. try to avoid using it. determines if a specified c integer is safe to pass to int_to_jsval. syntax #define int_fits_in_jsval(i) /* ... */ name type description i jsint the c integer value to check. description determines if a specified c integer value, i, lies within the range allowed for integer jsvals. if so, int_fits_in_jsval re
turns true, and i can be cast to jsval by calling int_to_jsval(i). otherwise, int_fits_in_jsval re
turns false. in this case, the application can still convert i to a jsval using js_newnumbervalue. warning: the type of the argument i must be jsint, but the c/c++ compiler does not enforce type safety here. if i is an unsigned or 64-bit value, int_fits_in_jsval can silently give the wrong answer. start...
JS::Add*Root
e is a static string constant, identifying the source location of the call to js::addnamed*root for debugging purposes. needs the example for typical usage of the name parameter. all the js::add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js::remove*root is required to unroot the location. on success, these functions re
turn true. otherwise they report an out of memory error and re
turn false. see also mxr id search for js::addvalueroot mxr id search for js::addstringroot mxr id search for js::addobjectroot mxr id search for js::addnamedvalueroot mxr id search for js::addnamedvaluerootrt mxr id search for js::addnamedstringroot mxr id search for js::addnamedobjectroot mxr id search for js::addnamedscriptroo...
JS::AutoSaveExceptionState
aller must be in a request on this jscontext. description js::autosaveexceptionstate saves and later restores the current exception state of a given jscontext. ...
JS::Call
nobj js::handlefunction / js::handlevalue / js::handleobject pointer to the function to call. should be a native function or jsapi-compiled function. name const char * pointer to the function name to call. args js::handlevaluearray & arguments to pass to the function. rval js::mutablehandlevalue out parameter. on success, *rval receives the re
turn value from the function call. description js::call calls a specified function, fun, on an object, thisobj. in terms of function execution, the object is treated as this. for more detail, see js_callfunction, js_callfunctionname, and js_callfunctionvalue. see also mxr id search for js::call js_callfunction js_callfunctionname js_callfunctionvalue bug 601168 ...
JS::CloneFunctionObject
global object. the new object's prototype is function.prototype; js_newobject : choosing a default prototype explains exactly how this is computed. js::clonefunctionobject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer to a javascript function object (see js_objectisfunction). on success, js::clonefunctionobject re
turns a pointer to the newly created object. if the class of funobj is not function, then js::clonefunctionobject re
turns funobj itself. on failure, it re
turns null. see also mxr id search for js::clonefunctionobject bug 1088228 bug 1089026 ...
JS::Compile
the script. length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or url) containing the script. this information is included in error messages if an error occurs during compilation.. on success, js::compile stores an object representing the newly compiled script into script, and re
turns true. otherwise, it re
turns false and the value left in script is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compile js::evaluate js::compileoffthread js::compilefunction js_decompilescript bug 771705 bug 1143793 -- removed obj parameter ...
JS::CompileFunction
irst element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcbuf is a string containing the source code of the function. length is the length of the source code in characters. on success, js::compilefunction stores an function object representing the newly compiled function into fun and and re
turns true. otherwise, it re
turns false and the value left in fun is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compilefunction js::evaluate js::compile js::compileoffthread js_executescript js_decompilescript bug 771705 ...
JS::CompileOffThread
le of a script, the callback will eventually be invoked with the specified data and a token for the compilation. the callback will be invoked while off the main thread, so its operations must be thread safe. afterwards, js::finishoffthreadscript must be invoked on the main thread to get the result script or nullptr. if maybecx is not specified, the resources will be freed, but no script will be re
turned. the characters passed in to js::compileoffthread must remain live until the callback is invoked, and the resulting script will be rooted until the call to finishoffthreadscript. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compileoffthread js::evaluate js::compile js::compilefunction js_decompilescript bug 897655 ...
JS::CreateError
ort jserrorreport * a pointer to jserrorreport instance. message js::handlestring the value of error.prototype.message. rval js::mutablehandlevalue out parameter. receives the created error object. description js::createerror creates an error object with specified properties. if successful, js::createerror stores the created error object to *rval and re
turns true, otherwise re
turns false and the value of *rval is undefined. see also mxr id search for js::createerror jsexntype jserrorreport bug 984048 bug 1038238 -- change stack parameter from js::handlestring to js::handleobject ...
JS::CurrentGlobalOrNull
this article covers features introduced in spidermonkey 31 re
turn the global object for the active function on the context. syntax jsobject * js::currentglobalornull(jscontext *cx); name type description cx jscontext * the context for which to re
turn the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js::currentglobalornull() re
turns the global object for whatever function is currently running on the context. in other words, it re
turns the global object on the current scope chain. if there is no javascript running on the context, this re
turns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming ob...
JS::DoubleNaNValue
this article covers features introduced in spidermonkey 24 create a not-a-number (nan) floating-point number as a value of type js::value. syntax js::value js::doublenanvalue() description js::doublenanvalue re
turns a value of type js::value that represents an ieee floating-point quiet not-a-number (nan). the result is an floating-point js::value. see also mxr id search for js::doublenanvalue js::value js_getnanvalue ...
JS::Evaluate
he same way as for the standard eval function. in the common case where the script is just an expression, the result value is simply the value of that expression. more generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. if a script compiles and executes successfully, js::evaluate stores the result in *rval, if non-null, and re
turns true. otherwise it re
turns false and the value left in *rval is undefined. see also mxr id search for js::evaluate js::compile js_executescript bug 771705 bug 1097987 -- remove obj parameter ...
JS::GetDeflatedUTF8StringLength
this article covers features introduced in spidermonkey 38 re
turns the length of the char buffer required to encode given string as utf8. syntax size_t getdeflatedutf8stringlength(jsflatstring* s); name type description s jsflatstring * the pointer to the string to calculate the length. description js::getdeflatedutf8stringlength re
turns the length of the char buffer required to encode s as utf8. the re
turned length does not include the null-terminator. see also js::deflatestringtoutf8buffer bug 1034627 ...
JS::GetFirstArgumentAsTypeHint
fs callargs the arguments of the function call. behavior jstype * receives the result of conversion. see below. description js::getfirstargumentastypehint converts first argument of @@toprimitive method to jstype. if args.get(0) is one of the strings "string", "number", or "default", set *result to jstype_string, jstype_number, or jstype_void accordingly and re
turn true. otherwise, re
turn false with a typeerror pending. see also mxr id search for js::getfirstargumentastypehint bug 1054756 - added ...
JS::GetSelfHostedFunction
me const char* function name in the self-hosted javascript. id js::handle<jsid> a pointer to jsid of the name to assign to the new function. nargs unsigned number of arguments the function expects. description js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript. on success, js::getselfhostedfunction re
turns a pointer to the newly created function. otherwise, it reports an out-of-memory error and re
turns null. see also mxr id search for js::getselfhostedfunction bug 1140573 ...
JS::Handle
ntroduced in spidermonkey 17 reference to a t that has been rooted elsewhere. this is most useful as a parameter type, which guarantees that the t value is properly rooted. syntax bool somefunction(jscontext *cx, js::handle<t> var) { ... } methods here, ptr represents the private member of js::handle<t>, typed with t. method description const t *address() const re
turns a pointer to ptr. const t &get() const re
turns ptr. operator const t&() const t operator->() const bool operator!=(const t &other) const compares ptr and other. bool operator==(const t &other) const description js::handle<t> is a const reference to a js::rooted<t>. functions which take gc things or values as arguments and need to r...
JS::HandleValueArray
f values. elements js::value * (frommarkedlocation only) a pointer to the first element of an array of js::value. values js::handlevaluearray (subarray only) an array to get sub array. startindex size_t (subarray only) an index of the first element of subarray of values. methods method description size_t length() const re
turns the length of the array. const value *begin() const re
turns the pointer to the first element of the array. js::handlevalue operator[](size_t i) const re
turns i-th element of the array. description js::handlevaluearray is a handle to an array of rooted values. this is useful as a parameter type, or a temporal local variable for it. see also mxr id search for js...
JS::IsCallable
this article covers features introduced in spidermonkey 38 re
turn whether the given function object is callable/a valid constructor. syntax bool js::iscallable(jsobject *obj); bool js::isconstructor(jsobject *obj); name type description obj jsobject * pointer to the function. description js::iscallable re
turns whether the given function object is callable. js::isconstructor re
turns whether the given function object is a valid constructor. see also mxr id search for js::iscallable mxr id search for js::isconstructor js_isconstructor js_isnativefunction bug 1065811 ...
JS::MutableHandle
eatures introduced in spidermonkey 17 reference to a t that has been rooted elsewhere. the underlying storage can be changed. this is useful for outparams. syntax bool somefunction(jscontext *cx, js::mutablehandle<t> outparam) { ... } methods here, ptr represents the private member of js::mutablehandle<t>, typed with t *. method description const t &get() const re
turns *ptr. operator const t&() const t operator->() const t *address() re
turns ptr. void set(t v) sets the value of *ptr to v. description js::mutablehandle<t> is a non-const reference to js::rooted<t>. it is used in the same way as js::handle<t> and includes a |set(const t &v)| method to allow updating the value of the referenced js::root...
JS::NewFunctionFromSpec
a successful call to propertyspecnametopermanentid(cx, fs->name, &id). description js::newfunctionfromspec creates a new function based on the given jsfunctionspec, *fs. id is the result of a successful call to propertyspecnametopermanentid(cx, fs->name, &id). unlike js_definefunctions, this does not treat fs as an array. *fs must not be js_fs_end. on success, js::newfunctionfromspec re
turns a pointer to newly created function. on error, it re
turns nullptr. see also mxr id search for js::newfunctionfromspec js_definefunctions bug 1054756 - added ...
JS::ObjectOrNullValue
this article covers features introduced in spidermonkey 24 convert a jsobject or null pointer to a js::value. syntax js::value js::objectornullvalue(jsobject* obj) name type description str jsobject* a pointer to a jsobject or null to convert. description js::objectvalue converts a given jsobject to js::value. if the pointer is null, it re
turns javascript null. the conversion always succeeds. see also mxr id search for js::objectornullvalue js::value js::objectvalue ...
JS::OrdinaryToPrimitive
specified in es6 draft rev 28 (2014 oct 14) 7.1.1, second algorithm. most users should not call this -- use js::tonumber, js::toboolean, or js::tostring instead. this should only be called from custom convert hooks. it implements the default conversion behavior shared by most objects in js, so it's useful as a fallback. on success, js::ordinarytoprimitive stores the converted value in *vp and re
turns true. on error or exception, it re
turns false, and the value left in *vp is undefined. see also mxr id search for js::ordinarytoprimitive js::tonumber js::toboolean js::tostring bug 1103152 ...
JS::PropertySpecNameEqualsId
ax bool js::propertyspecnameequalsid(const char *name, js::handleid id); name type description name const char * jspropertyspec::name or jsfunctionspec::name. id js::handleid a jsid to compare with. description js::propertyspecnameequalsid determines if the given jspropertyspec::name or jsfunctionspec::name value equals the given jsid, and re
turns true if so. see also mxr id search for js::propertyspecnameequalsid js::propertyspecnameissymbol js::propertyspecnametopermanentid jspropertyspec jsfunctionspec bug 1082672 ...
JS::PropertySpecNameIsSymbol
ng. syntax bool js::propertyspecnameissymbol(const char *name); name type description name const char * the pointer of the name, actually the uintptr_t type, and not a pointer to any string. description js::propertyspecnameissymbol determines if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string, and re
turns true if so. see also mxr id search for js::propertyspecnameissymbol js::propertyspecnameequalsid js::propertyspecnametopermanentid jspropertyspec jsfunctionspec bug 1082672 ...
JS::Rooted
in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. rt jsruntime * the runtime in which to add the root. initial t an initial value for the rooted variable. methods here, ptr represents the private member of js::rooted<t>, typed with t. method description t &get() re
turns ptr. const t &get() const operator const t&() const t operator->() const t *address() re
turns a pointer to ptr. const t *address() const t &operator=(t value) sets the value of ptr to value. t &operator=(const rooted &value) void set(t value) bool operator!=(const t &other) const compares ptr and other. ...
JS::SetOutOfMemoryCallback
w the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out-of-memory callback is only called if the allocation still fails after the large-allocation-failure callback has re
turned. js::setoutofmemorycallback sets a callback function for it. see also mxr id search for js::setoutofmemorycallback mxr id search for js::outofmemorycallback bug 969415 bug 987995 - added data parameter ...
JS::ToBoolean
introduced in spidermonkey 17 convert any javascript value to a boolean. syntax bool js::toboolean(js::handlevalue v) name type description v js::handlevalue the value to convert. description js::toboolean converts a javascript value to a boolean. it implements the toboolean operation described in ecma 262 §7.1.2.this function can not fail and the re
turn value is always the boolean conversion of the argument. mxr id search for js::toboolean bug 749536 ...
JS::ToInt32
on this jscontext. v js::handlevalue the value to convert. out int32_t * out parameter. on success, *out receives the converted floating-point value. description js::toint32 converts a javascript value to a signed 32bit integer. it implements the toint32 operator described in ecma 262-3 §9.5. on success, js::toint32 stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::toint32 bug 739541 ...
JS::ToInt64
request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. out int64_t * out parameter. on success, *out receives the converted floating-point value. description js::toint64 converts a javascript value to a signed 64bit integer. on success, js::toint64 stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::toint64 bug 742188 ...
JS::ToNumber
in a request on this jscontext. v js::handlevalue the value to convert. out double * out parameter. on success, *out receives the converted floating-point value. description js::tonumber converts a javascript value to a number. it implements the tonumber operator described in ecma 262-3 §9.3. on success, js::tonumber stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::tonumber bug 739541 ...
JS::ToPrimitive
r to pass the corresponding type as a hint, or jstype_void to pass no hint. do not pass any other type. vp js::mutablehandleobject out parameter. on success, *vp receives the converted value. description js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive. on success, js::toprimitive stores the converted value in *vp and re
turns true. on error or exception, it re
turns false, and the value left in *vp is undefined. see also mxr id search for js::toprimitive js::getfirstargumentastypehint js_defaultvalue -- old name of this function bug 1054756 - added ...
JS::ToString
spidermonkey 38; previously in jsapi.h jsstring* js::tostring(jscontext *cx, js::handlevalue v) name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. description js::tostring re
turns a string representation of a javascript value. if v.isstring() is true, it calls v.tostring(). otherwise, it converts the value to string. on success, js::tostring re
turns a jsstring instance. on error or exception, it re
turns nullptr. see also mxr id search for js::tostring bug 933834 ...
JS::ToUint16
this jscontext. v js::handlevalue the value to convert. out uint16_t * out parameter. on success, *out receives the converted floating-point value. description js::toint16 converts a javascript value to an unsigned 16bit integer. it implements the toint16 operator described in ecma 262-3 §9.7. on success, js::toint16 stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::touint16 bug 779601 ...
JS::ToUint32
is jscontext. v js::handlevalue the value to convert. out int32_t * out parameter. on success, *out receives the converted floating-point value. description js::touint32 converts a javascript value to an unsigned 32bit integer. it implements the touint32 operator described in ecma 262-3 §9.5. on success, js::touint32 stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::touint32 bug 739541 ...
JS::ToUint64
est. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handlevalue the value to convert. out uint64_t * out parameter. on success, *out receives the converted floating-point value. description js::toint64 converts a javascript value to an unsigned 64bit integer. on success, js::toint64 stores the converted value in *out and re
turns true. on error or exception, it re
turns false, and the value left in *out is undefined. see also mxr id search for js::touint64 bug 742188 ...
JSBool
obsolete since jsapi 26this 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. every instance of jsbool has been replaced by bool. js_true has been replaced by just true and in the same way js_false by false. jsbool is the re
turn type of many jsapi functions and callbacks. js_true indicates success; js_false indicates an error or exception occurred. jsbool is an integer type. js_true is (jsbool) 1 and js_false is (jsbool) 0. these values must not be used as jsvals. instead, use jsval_true and jsval_false, and use boolean_to_jsval and jsval_to_boolean to convert. ...
JSCheckAccessOp
obj jsobject * the object whose properties are being accessed. id jsval the name or index of the property being accessed. mode jsaccessmode the type of access being checked. vp jsval * out parameter. on success, the callback must set *vp to the stored value of the property. description check whether obj[id] may be accessed per mode, re
turning js_false on error/exception, js_true on success with obj[id]'s stored value in *vp. as for jspropertyop, id is either a string or an int jsval. jscheckaccessop implementations generally work by using jsdbgapi functions such as js_frameiterator and js_stackframeprincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them w...
JSClass
b, printer_finalize, * jsclass_no_optional_members * }; */ bool printer_construct(jscontext *cx, unsigned argc, jsval *vp) { js::callargs args = js::callargsfromvp(argc, vp); jsobject *obj = js_newobjectforconstructor(cx, &printer_class, args); /* spidermonkey 31 or older * jsobject *obj = js_newobjectforconstructor(cx, &printer_class, vp); */ if (!obj) re
turn false; myprinter *p = new myprinter; if (p == null) { js_reportoutofmemory(cx); re
turn false; } js_setprivate(cx, obj, p); args.rval().setobject(*obj); /* spidermonkey 31 or older * js_set_rval(cx, vp, object_to_jsval(obj)); */ re
turn true; } { js_initclass(cx, global, js::null(), &printer_class, printer_construct, 1, null,...
JSConvertOp
s a hint, or jstype_void to pass no hint. other types may be passed as hints, but such behavior is deprecated. vp js::mutablehandlevalue out parameter. on success, *vp receives the converted value. description jsconvertop callback specifies conversion behavior for objects having this class, implementing the ecmascript [[defaultvalue]] behavior for them. on success it must re
turn a primitive value in *vp. implementations of this hook have historically been required to accept any type. however, the engine itself only requires support for jstype_string, jstype_number, and jstype_void, if js_convertvalue is not used. if you do not use the js_convertvalue method, you may omit support for other types. (support for the other types may eventually be removed.) the callback retu...
JSErrorFormatString
nt16_t exntype; } jserrorformatstring; name type description format const char * the error format string in ascii. argcount uint16_t the number of arguments to expand in the formatted error message. exntype int16_t one of the jsexntype constants. description jserrorformatstring is a struct to represent error message and type, re
turned by js_reporterrornumber function. see also mxr id search for jserrorformatstring jsexntype js_reporterrornumber bug 684526 ...
JSErrorReport
to hold the text that generated the error condition. set linebuf to point at the buffer before your application executes a script. for unicode scripts, define a second buffer that holds the unicode version of the text the generated the error. for application that do not use unicode, set uclinebuf and uctokenptr to null. macros name description jsreport_is_warning(flags) re
turns true if flags has jsreport_warning. jsreport_is_exception(flags) re
turns true if flags has jsreport_exception. jsreport_is_strict(flags) re
turns true if flags has jsreport_strict. jsreport_is_strict_mode_error(flags) re
turns true if flags has jsreport_strict_mode_error. see also mxr id search for jserrorreport js_reporterror js_reportwarning js_repo...
JSExceptionState
the fields of this structure are private/opaque. this is used to save and restore exception states. syntax struct jsexceptionstate; description a jsexceptionstate object is re
turned by the js_saveexceptionstate function, and is passed to functions js_restoreexceptionstate and js_dropexceptionstate. see also mxr id search for jsexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexceptionstate ...
JSExtendedClass
p wrappedobject; // added in spidermonkey 1.8 ...and additional reserved fields. }; name type description base jsclass the basic class information and callbacks for this class. this contains some required fields. equality jsequalityop optional. overrides the javascript == and != operators. outerobject jsobjectop optional. re
turn the current outer object. this is used to implement split objects. innerobject jsobjectop optional. re
turn the current inner object. this is used to implement split objects. iteratorobject jsiteratorop added in spidermonkey 1.8 optional. creates and re
turns a new iterator. wrappedobject jsobjectop added in spidermonkey 1.8 optional. if non-null, an obj...
JSFreeOp
this article covers features introduced in spidermonkey 17 structure used during finalization instead of jscontext. syntax jsfreeop(jsruntime *rt); name type description rt jsruntime * a runtime to store in this structure. methods method description jsruntime *runtime() const re
turns a pointer to jsruntime passed to constructor. description various finalization api takes not jscontext * but rather either jsfreeop structure or its library-private counterpart freeop. these structures wrap parameters that are passed to the finalizers removing most of explicit dependencies on jscontext in the finalization code. see also mxr id search for jsfreeop js_freeop js_getdefaultfreeop jsfinalizecallback jsdestroycom...
JSGetObjectOps
>getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_newobject, etc. most host objects do not need to implement the larger jsobjectops, and can share the common jsscope code and data used by the native (js_objectops, see jsobj.c) ops. further extension to preserve api compatibility: if this function re
turns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x. jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created. it re
turns a pointer to a jsobjectops which is then used as a virtual table for operations on the new object. see also mxr id search for jshasinstanceop jsclass ...
JSHasInstanceOp
the js context in which the type check is occurring. obj js::handleobject the "type" in the type check. v js::mutablehandlevalue the value whose type is being checked. bp bool * out parameter. on success, the callback stores the result of the type check in *bp. description jshasinstanceop is called to check whether v is an instance of obj. re
turn false on error or exception, true on success with true in *bp if v is an instance of obj, false in *bp otherwise. jsclass hooks jsclass offers the following hook: the jsclass.hasinstance callback implements js_hasinstance and the javascript instanceof keyword. see also mxr id search for jshasinstanceop jsclass js_hasinstance ...
JSID_IS_GCTHING
testing and conversion functions between a js id and a gc thing. syntax bool jsid_is_gcthing(jsid id); js::gccellptr jsid_to_gcthing(jsid id); name type description id jsid the property identifier to test or convert. description jsid_is_gcthing tests whether a specified js id, id, is a gc thing, and re
turns true if it's a gc thing. jsid_to_gcthing converts a specified js id, id to a gc thing. see also mxr id search for jsid_is_gcthing mxr id search for jsid_to_gcthing ...
JSID_IS_INT
nd an integer. syntax bool jsid_is_int(jsid id); int32_t jsid_to_int(jsid id); bool int_fits_in_jsid(int32_t i); jsid int_to_jsid(int32_t i); name type description id jsid the property identifier to test or convert. i int32_t an integer to test or convert. description jsid_is_int tests whether a specified js id, id, is an integer, and re
turns true if it's an integer. jsid_to_int converts a specified js id, id to an integer. int_fits_in_jsid tests whether a specified integer fits in jsid, it means the integer value is not negative. int_to_jsid converts a specified integer, i to a jsid. see also mxr id search for jsid_is_int mxr id search for jsid_to_int mxr id search for int_fits_in_jsid mxr id search for int_to_jsid ...
JSID_IS_STRING
ntext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. id jsid the property identifier to test or convert. str jsstring * an interned string to convert to an id. description jsid_is_string tests whether a specified js id, id, is a string, and re
turns true if it's a string. jsid_to_string converts a specified js id, id to a jsstring *. interned_string_to_jsid converts a specified interned string, str to a jsid. jsid_to_flat_string converts a specified js id, id to a jsflatstring *. see also mxr id search for jsid_is_string mxr id search for jsid_to_string mxr id search for interned_string_to_jsid mxr id search for jsid_to_flat_strin...
JSID_IS_SYMBOL
id and a js symbol. syntax bool jsid_is_symbol(jsid id); js::symbol * jsid_to_symbol(jsid id); jsid symbol_to_jsid(js::symbol *sym); name type description id jsid the property identifier to test or convert. sym js::symbol a js symbol to test or convert. description jsid_is_symbol tests whether a specified js id, id, is a js symbol, and re
turns true if it's a js symbol. jsid_to_symbol converts a specified js id, id to a js symbol. symbol_to_jsid converts a specified js symbol, i to a jsid. see also mxr id search for jsid_is_symbol mxr id search for jsid_to_symbol mxr id search for symbol_to_jsid bug 645416 ...
JSID_VOID
an additional jsid which is used to indicate the absence of a valid jsid. syntax const jsid jsid_void; const js::handleid jsid_voidhandle; // added in spidermonkey 31 description jsid_void does not occur in js scripts but may be used to indicate the absence of a valid jsid. a void jsid is not a valid id and only arises as an exceptional api re
turn value, such as in js_nextproperty. embeddings must not pass jsid_void into jsapi entry points expecting a jsid and do not need to handle jsid_void in hooks receiving a jsid except when explicitly noted in the api contract. jsid_voidhandle is the handle to the jsid which value is jsid_void. see also mxr id search for jsid_void mxr id search for jsid_voidhandle bug 912411 ...
JSIteratorOp
o the js context in which the iterator creation should take place. obj jsobject * pointer to the object to iterate over. keysonly jsbool if true, the iterator should yield keys only, not [key, value] pairs. description the javascript engine calls the jsextendedclass.iteratorobject callback to create an iterator object for a given object. the callback should re
turn an iterator object or null if an error or exception occurred on cx. see also bug 909178 ...
JSNewResolveOp
ccess, the resolve hook must set *objp to the object in which the property has been defined, or null if it was not defined. description like jsresolveop, but flags provide contextual information about the property access. on success, the callback must set the *objp out parameter to null if id was not resolved; or non-null, referring to obj or one of its prototypes, if id was resolved; and re
turn js_true. on failure, it must re
turn js_false. this hook instead of jsresolveop is called via the jsclass.resolve member if jsclass_new_resolve is set in jsclass.flags. setting jsclass_new_resolve and jsclass_new_resolve_gets_start further extends this hook by passing in the starting object on the prototype chain via *objp. thus a resolve hook implementation may define the property id being resolv...
JSObjectOps.defaultValue
volve implicit conversion of the operands using [[defaultvalue]]. the default [[defaultvalue]] behavior for ordinary objects is as described in es5 §8.12.8. it calls the javascript methods obj.valueof() and/or obj.tostring(). provide a custom jsobjectops.defaultvalue callback to implement customized [[defaultvalue]] behavior. the jsclass.convert callback should convert obj to the given type, re
turning js_true with the resulting value in *vp on success, and re
turning js_false on error or exception. on success, *vp must be a primitive value: per es5 §8.12.8, every object "must ensure that its [[defaultvalue]] internal method can re
turn only primitive values." debug builds of spidermonkey will assert if a convert callback is successful but leaves *vp holding a primitive value. js_convertstub...
JSObjectOps.dropProperty
is an own property. that is, the value that the jsobjectops.lookupproperty hook stored in the *objp out parameter. prop jsproperty * the property to release. that is, the value that jsobjectops.lookupproperty hook stored in the *propp out parameter. description the following contract governs jsobjectops callers and implementations: whenever jsobjectops.lookupproperty re
turns a jsproperty pointer, the property is locked. while the property is locked, the caller may access it using other jsobjectops callbacks. it may not otherwise call into the jsapi in ways that might trigger other property accesses. (in a js_threadsafe build, that would risk deadlock.) when finished with a locked property, the caller must release it by calling the dropproperty callback. the lifet...
JSObjectOps.getAttributes
whose property attributes are being accessed. id jsid the name or index of the property whose attributes are being accessed. prop jsproperty * the property whose attributes are being accessed. this may be null. attrsp unsigned int * in/out parameter. see the description section below. description get or set attributes of the property obj[id]. re
turns js_false on error or exception, else js_true with current attributes in *attrsp. if prop is non-null, it must come from the *propp out parameter of a prior jsobjectops.defineproperty or jsobjectops.lookupproperty call. for more information on property attributes, see js_getpropertyattributes. ...
JSObjectOps.getProperty
*vp); name type description cx jscontext * pointer to the js context in which the property access is happening. obj jsobject * the object to be accessed. id jsid the name or index of the property to access. vp jsval * in/out parameter. see the description section below. description get, set, or delete obj[id], re
turning js_false on error or exception, js_true on success. if getting or setting, the new value is re
turned in *vp on success. if deleting without error, *vp will be jsval_false if obj[id] is permanent, and jsval_true if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype...
JSObjectOps.newObjectMap
newobjectmap by including the non-public header jsobj.h, or obtain the default newobjectmapop by calling the jsclass.getobjectops callback of a standard jsclass. create a new instance of (a concrete subclass of) jsobjectmap (see jsobj.h), with the nrefs and ops members initialized from the same-named parameters, and with the nslots and freeslot members initialized according to ops and clasp. re
turn null on error, non-null on success. jsobjectmaps are reference-counted by generic code in the engine. usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref re
turned to the caller on success. after a successful construction, some number of js_holdobjectmap and js_dropobjectmap calls ensue. when nrefs reaches 0 due to a js_dropobjectmap call, jsobjectops.destroyobjec...
JSObjectPrincipalsFinder
callback to obtain principals for the local scope object, to check that the caller has access to that object. the two debugger functions js_stackframeprincipals and js_evalframeprincipals also use this callback. since it is very common for jsobjectops.checkaccess or jsclass.checkaccess hooks to call these functions, the object principals finder callback is a key security feature. the callback re
turns a pointer to the principals associated with obj, possibly via the immutable parent chain leading from obj to a top-level container (such as a window object in the dom). if there are no principals associated with obj, re
turn null. therefore null does not mean an error was reported; in no event should an error be reported or an exception be thrown by this callback's implementation. the callback s...
JSPrincipals
nformation for an object or script. properties name type description refcount mozilla::atomic<int32_t> reference count. use js_holdprincipals and js_dropprincipals. codebase char * pointer to the codebase for the principal. obsolete since jsapi 13 getprincipalarray void * (*)(jscontext *, jsprincipals *) pointer to the function that re
turns an array of principal definitions. obsolete since jsapi 12 globalprivilegesenabled jsbool (*)(jscontext *, jsprincipals *) flag indicating whether principals are enabled globally. obsolete since jsapi 12 destroy void (*)(jscontext *, jsprincipals *) pointer to the function that decrements the reference count and possibly frees the principals if they are no longer in...
JSPrincipalsTranscoder
incipals, which poses a problem for xdr. the application provides the jsprincipals objects, so it must also provide a jsprincipalstranscoder if it intends to serialize or deserialize principals. the callback xdr-encodes or -decodes a principals instance, based on whether xdr->mode is jsxdr_encode, in which case *principalsp should be encoded; or jsxdr_decode, in which case implementations must re
turn a held (via jsprincipals_hold), non-null *principalsp out parameter. re
turn js_true on success, js_false on any error, which the implementation must have reported. mxr id search for jsprincipalstranscoder ...
JSResolveOp
solve operation. description jsresolveop callback is a hook which is called when a property is not found on an object. it resolves a lazy property named by id in obj by defining it directly in obj. lazy properties are those reflected from some peer native property space (e.g., the dom attributes for a given node reflected as obj) on demand. the callback must set *resolvedp to true and re
turn true if the property is resolved, or set *resolvedp to false and re
turn true if the object has no lazy property with the given id; or re
turn false to indicate any other error. obsolete since jsapi 36 the callback must re
turn true if the property is resolved, or if the object has no lazy property with the given id; or false to indicate any other error. note: jsnewresolveop provides a cheaper w...
JSVAL_IS_OBJECT
obsolete since jsapi 32this 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. determine whether a given jsval is an object or null. syntax jsbool jsval_is_object(jsval v); description jsval_is_object(v) re
turns true if v is either an object or jsval_null. this indicates that it is safe to call jsval_to_object(v) to convert v to type jsobject *. if v is a string, number, boolean, or undefined, the result is false. this function is obsolete and has been removed. instead use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null. see also bug 952650 ...
JSVAL_TO_STRING
o type jsstring *. as a precondition, jsval_is_string(v) must be true. this function is not type-safe: if v is not a string, the behavior is undefined. to coerce any value to a string, use the js_valuetostring function instead. (the difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) to convert the re
turn type of this macro (jsstring *) to a char pointer, use js_getstringbytes. see also bug 952650 ...
JS_ASSERT_STRING_IS_FLAT
this article covers features introduced in spidermonkey 1.8.5 assert a string is flattened. syntax static moz_always_inline jsflatstring * js_assert_string_is_flat(jsstring *str) { moz_assert(js_stringisflat(str)); re
turn (jsflatstring *)str; } name type description str jsstring * string to examine. description js_assert_string_is_flat asserts the string is flattened, and re
turns a pointer to jsflatstring. see also mxr id search for js_assert_string_is_flat js_stringisflat bug 609440 ...
JS_AddExternalStringFinalizer
ing() when creating the string. it is the callback's responsibility to free the memory. after this callback, the js engine will not use that memory anymore and will not keep a pointer to it. the callback may not keep a reference to this jsstring, as its memory is about to be freed. description add a finalizer for external strings created by js_newexternalstring using a type-code re
turned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str). re
turns a nonnegative type index if there is room for finalizer in the global gc finalizers table, else re
turns -1. in a js_threadsafe build, this function must be invoked on the primordial thread only, at startup—or else the entire program must single-thread itself while loading ...
JS_Add*Root
tic string constant, identifying the source location of the call to js_addnamedroot for debugging purposes. js_dumpnamedroots can be used to access this information from a debugger. all the js_add*root methods are idempotent: multiple calls for the same address will add only one root. correspondingly, only a single js_removeroot is required to unroot the location. on success, these functions re
turn js_true. otherwise they report an out of memory error and re
turn js_false. see also mxr id search for js_addvalueroot mxr id search for js_addstringroot mxr id search for js_addobjectroot mxr id search for js_addnamedvalueroot mxr id search for js_addnamedstringroot mxr id search for js_addnamedobjectroot bug 912581 ...
JS_AliasElement
is deprecated, meaning that it is currently supported only for backward compatibility with existing applications. future versions of the engine may no longer support this function. an alias does not replace an element's current index number; it supplements it, providing a second way to reference the element. if the alias is successfully created and associated with the property, js_aliaselement re
turns js_true. adding an alias element does not change the element array length. if the property name you specify does not exist, js_aliaselement reports an error, and re
turns js_false. if the element is currently out of scope, already exists, or the alias itself cannot be assigned to the element, js_aliaselement does not report an error, but re
turns js_false. once you create an alias, you can reassig...
JS_AliasProperty
. obj is the object to which the property belongs. name is the property's current name in the object, and alias is the alternate name to assign to the property. notes this feature has been removed. an alias does not replace a property's name; it supplements it, providing a second way to reference a property. if the alias is successfully created and associated with the property, js_aliasproperty re
turns js_true. creating an alias does not change the length of the property array. if the property name you specify does not exist, js_aliasproperty reports an error, and re
turns js_false. if the property is currently out of scope, already exists, or the alias itself cannot be assigned to the property, js_aliasproperty does not report an error, but re
turns js_false. once you create an alias, you can r...
JS_AlreadyHasOwnProperty
this is the only api that breaks the abstraction.) for non-native objects, this falls back on a complete search. this calls the jsobjectops.lookupproperty hook. *foundp is set to true only if lookupproperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any). if the property is found on obj, this sets *foundp to true and re
turns true. if the property is not found on obj, this sets *foundp to false and re
turns true (to indicate that no error occurred). if the search fails with an error or exception, this re
turns false. see also mxr id search for js_alreadyhasownproperty mxr id search for js_alreadyhasownucproperty mxr id search for js_alreadyhasownpropertybyid mxr id search for js_alreadyhasownelement bug 400793 bug 461...
JS_BindCallable
safe build, the caller must be in a request on this jscontext. callable js::handle<jsobject*> pointer to the function object to bind new this. newthis js::handle<jsobject*> pointer to the new this value for callable. description js_bindcallable binds the given callable to use the given object as this. if callable is not callable, will throw and re
turn nullptr. see also mxr id search for js_bindcallable bug 738356 ...
JS_BufferIsCompilableUnit
pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the global object, or null. utf8 const char * string containing the script to compile. length size_t the length of utf8 in characters. description given a buffer, re
turn false if the buffer might become a valid javascript statement with the addition of more lines. otherwise re
turn true. the intent is to support interactive compilation - accumulate lines in a buffer until js_bufferiscompilableunit is true, then pass it to the compiler. see also mxr id search for js_bufferiscompilableunit js::evaluate js::compile js::compileoffthread js::compilefunction js_d...
JS_CStringsAreUTF8
rmonkey can optionally interpret these strings as utf-8. there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_newruntime. enabling this option also causes js_getstringbytes and js_encodecharacters to produce utf-8 strings instead of latin-1. js_cstringsareutf8 re
turns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8. see also bug 805080 ...
JS_CheckAccess
ccess check is delegated to the jsobjectops.checkaccess callback. otherwise, if obj's class has a non-null jsclass.checkaccess callback, then it is called to perform the check. otherwise, if a runtime-wide check-object-access callback has been installed by calling js_setcheckobjectaccesscallback, then that is called to perform the check. otherwise, access is granted. on success, js_checkaccess re
turns js_true, *vp is set to the current value of the specified property, and *attrsp is set to the property's attributes. on error or exception, including if access is denied, js_checkaccess re
turns js_false, and the values left in *vp and *attrsp are undefined. mxr id search for js_checkaccess ...
JS_CheckForInterrupt
this article covers features introduced in spidermonkey 45 check for and handle interrupt. syntax bool js_checkforinterrupt(jscontext* cx); name type description cx </code>jscontext *<code> the context. description js_checkforinterrupt checks for the interrupt, and handle it if it's pending. js_checkforinterrupt re
turns false if interrupt callback re
turns false. see also mxr id search for js_checkforinterrupt js_setinterruptcallback js_getinterruptcallback js_requestinterruptcallback bug 1058695 ...
JS_ClearContextThread
text *cx) { js_setcontextthread(cx); /* note: outside the request */ js_beginrequest(cx); ... js_endrequest(cx); js_clearcontextthread(cx); /* note: outside the request */ } js_setcontextthread ties cx to the current thread for exclusive use. no other thread may use cx until the current thread removes this association by calling js_clearcontextthread. js_setcontextthread re
turns the thread id of the thread previously associated with this context. when the function is used properly, the re
turn value is always zero, indicating that no thread was previously associated with the context. js_clearcontextthread relinquishes the calling thread's right to use cx. it re
turns the thread id of the last thread to be associated with this context. (this is always the current thread i...
JS_ClearPendingException
adsafe build, the caller must be in a request on this jscontext. description js_clearpendingexception cancels the currently pending exception in cx, if any. (there is a pending exception if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi call fails with an exception, the caller must either use js_clearpendingexception to catch the exception; or re
turn false to allow the exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an exception is pending. many jsapi functions can simply report an error and re
turn false without building and throwing an exception object. use js_isexceptionpending or js_getpendingexception to check for a pending exception. see examples in the jsapi phrasebook. see also mxr ...
JS_ClearRegExpStatics
name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject a pointer to a global object. description js_clearregexpstatics clears the pending input string and flags of the built-in regexp object. on successful, js_clearregexpstatics re
turns true, otherwise re
turns false. see also mxr id search for js_clearregexpstatics js_newregexpobject js_newucregexpobject js_setregexpinput regexp ...
JS_CloneFunctionObject
reated global object. the new object's prototype is function.prototype; js_newobject: choosing a default prototype explains exactly how this is computed. js_clonefunctionobject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer to a javascript function object (see js_objectisfunction). on success, js_clonefunctionobject re
turns a pointer to the newly created object. if the class of funobj is not function, then js_clonefunctionobject re
turns funobj itself. on failure, it re
turns null. see also mxr id search for js_clonefunctionobject js::clonefunctionobject bug 1089026 renamed to js::clonefunctionobject ...
JS_CompareStrings
compare. result int32_t * the out parameter. see description for value of *result. description js_comparestrings compares two js strings, str1 and str2. if the strings are identical in content and length, js_comparestrings stores 0 in *result. if str1 is less than str2, *result is less than 0. if str1 is greater than str2, *result is greater than 0. on success the function re
turns js_true. on error, it re
turns js_false and the value in result is unchanged. this function imposes a total order on all javascript strings, the same order imposed by the javascript string comparison operators (<, <=, >, >=), as described in ecma 262-3 § 11.8.5. as the standard says: the comparison of strings uses a simple lexicographic ordering on sequences of code point value values. there i...
JS_CompileFunction
tion is used in error messages if an error occurs during compilation. similarly, lineno is used to report the line number where an error occurred during compilation. if both obj and name are non-null, the new function becomes a method of obj. (a new property is defined on obj with the given name and the new function object as its value.) on success, js_compilefunction and js_compileucfunction re
turn a pointer to the newly compiled function. on error or exception, they re
turn null. see also mxr id search for js_compilefunction mxr id search for js_compileucfunction jsfun_bound_method jsfun_global_parent js_callfunction js_callfunctionname js_callfunctionvalue js_decompilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfunctionobject js_newfunction ...
JS_CompileFunctionForPrincipals
ength is the length of the string in characters. filename is the name of the file (or url) containing the function. this information is passed in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the function or file where an error occurred during compilation. on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals re
turn a pointer to the newly compiled function. on error or exception, they re
turn null. see also mxr id search for js_compilefunctionforprincipals mxr id search for js_compileucfunctionforprincipals jsfun_bound_method jsfun_global_parent js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunction js_decompilefunctionbody js_definefunction js_definefu...
JS_CompileScript
pilescript compiles a script, source, for execution. js_compileucscript is the unicode version of the function. the script is associated with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and re
turns true. otherwise, they report an error, stores null to *script, and re
turn false. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilescript mxr id search for js_compileucscript js::evaluate js::compileoffthread js::compilefunction js_executescript js_decompilescript bug 1143793 -- removed obj parameter ...
JS_CompileScriptForPrincipals
dicates the length of the script, in characters. filename is the name of the file (or url) containing the script. this information is included in error messages if an error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. on success, js_compilescriptforprincipals and js_compileucscriptforprincipals re
turn a pointer to the compiled script. on error or exception, they re
turn null. the application is responsible for ensuring that the new compiled script is cleaned up later—either by calling js_destroyscript() directly or by calling js_newscriptobject(), in which case the garbage collector cleans up the script. warning: this api is subject to bug 438633, which can cause crashes in almost any prog...
JS_CompileUTF8File
s jscontext. obj jsobject * object with which the script is associated. filename const char * name of file containing the script to compile. description js_compileutf8file compiles the text of script in an external file location for execution by the js engine. filename is the name of the file containing the script to compile. on success, js_compileutf8file re
turns an object that represents the newly compiled script. otherwise it re
turns null. js_compileutf8file is deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilefile js::compile js_decompilescript js::evaluate js_executescript bug 805080 ...
JS_CompileUTF8FileHandle
function for use with spidermonkey's security features. filename is the name of the file containing the script to compile. file is the file handle. js_compileutf8filehandle does not close the file handle. if principals is non-null, it points to a jsprincipals object that is associated with the new script and any functions it creates. on success, js_compileutf8filehandle reads file to eof and re
turns an object representing the newly compiled script. if an error occurs during compilation, js_compileutf8filehandle stops reading from the file and re
turns null. js_compileutf8filehandle and js_compileutf8filehandleforprincipals are deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compileutf8fileha...
JS_ConcatStrings
xt *cx, js::handlestring left, js::handlestring right); name type description cx jscontext * the context in which both the strings have been created. left js::handlestring first string to concatenate. right js::handlestring second string to concatenate. description js_concatstrings concatenates two js strings, str1 and str2, and re
turns the result. the result could be the same as one of the input strings, if the other string is zero length. when the string concatenation fails null is re
turned. see also mxr id search for js_concatstrings ...
JS_ConstructObject
ike the javascript new keyword. for details on how we find the appropriate constructor and default prototype, see js_newobject: choosing a default prototype. roughly speaking, we use parent or cx to find a global object, and then find clasp's constructor in that global object. if parent is null, the engine chooses an object to serve as the new object's parent. on success, js_constructobject re
turns a pointer to the newly instantiated object. otherwise it re
turns null. the new object created by these functions is subject to garbage collection. the object should be made gc-reachable immediately. see the jsapi user guide. see also js_defineobject js_newobject bug 757551 ...
JS_ContextIterator
rt jsruntime * the runtime to walk. iterp jscontext * in-out parameter. on input, *iterp must be null or point to a context in rt. on success, the value of *iterp is modified so that repeated calls cycle through all the contexts in rt. description js_contextiterator steps through the set of contexts associated with the runtime rt. each call to js_contextiterator re
turns the next context in the cycle. iterp must point to a variable of type jscontext *. if *iterp is null, js_contextiterator modifies it to point to the first jscontext in the list. otherwise *iterp must point to an existing context in rt, and js_contextiterator modifies it to point to the next context in the list, if any, and null otherwise. js_contextiterator re
turns the new value of *iterp. ex...
JS_ConvertArguments
for example, if format is "biob", then js_convertarguments converts the first js value in argv into a bool, the second value into a double, the third value into a jsobject *, and the last value into a bool. to skip a given argument, pass an asterisk in the corresponding position in format. if argc is less than the number of arguments required by format, js_convertargument reports an error and re
turns false. if argc is greater than the number of arguments described in format, the extraneous arguments are ignored. on success, js_convertargument re
turns true. if any argument conversion fails or there are not enough arguments, it re
turns false. to perform the opposite conversion, converting values of various c types to an array of jsvals, use js_pusharguments. see also mxr id search for js...
JS_ConvertArgumentsVA
which to store the converted types. there should be one pointer for each converted value. the type va_list is a standard feature of the c programming language. it is defined in <stdarg.h>. description js_convertargumentsva is to js_convertarguments as vprintf is to printf. see js_convertarguments for further information. if js_convertargumentsva successfully converts all arguments, it re
turns true. otherwise it re
turns false. see also mxr id search for js_convertargumentsva js_convertarguments bug 969798 - added args bug 1125784 ...
JS_ConvertValue
er: the result is a function object that has not been stripped of its lexical scope. it is safe to call the result (e.g. using js_callfunctionvalue). converting to jstype_string works like js::tostring. converting to jstype_number works exactly like js::tonumber. converting to jstype_boolean works exactly like js::toboolean. on success, js_convertvalue stores the converted value in *vp and re
turns true. on error or exception, it re
turns false, and the value left in *vp is undefined. see also mxr id search for js_convertvalue js_convertarguments js_gettypename js_typeofvalue bug 1125784 ...
JS_DecompileFunction
js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle<jsfunction*> function to decompile. description js_decompilefunction generates the complete source code of a function declaration from a function's compiled form, fun. if successful, js_decompilefunction re
turns a string containing the text of the function. otherwise, it re
turns null. if you decompile a function that does not make a native c call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing. if you decompile a function that makes a native c call, the body of the function contains the text "native code'" and cannot be re-parsed. see also m...
JS_DecompileFunctionBody
> fun, unsigned indent); name type description cx jscontext * the context in which to decompile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle<jsfunction*> the function to decompile. indent unsigned if it's not js_dont_pretty_print, js_decompilefunction re
turns pretty printed source code of the function. description js_decompilefunctionbody generates the source code of a function's body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. if successful, js_decompilefunctionbody re
turns a string containing the source code of the function body. otherwise, it re
turns null. the source code generated by this...
JS_DefaultValue
ecial case for date objects). objects with a custom jsclass specified by the embedder will invoke that class's convert hook, which must convert the object to a primitive value, to determine the primitive result of conversion. behavior when the convert hook is js_convertstub is identical to that for objects defined by ecmascript. on success, js_defaultvalue stores the converted value in *vp and re
turns true. on error or exception, it re
turns false, and the value left in *vp is undefined. see also mxr id search for js_defaultvalue js::toprimitive bug 1054756 - renamed to js::toprimitive ...
JS_DefineConstDoubles
of an array of jsconstdoublespec/jsconstintegerspec structures. each array element defines a single property name and property value to create. the name field of the last element of the array must contain 0. js_defineconstdoubles/js_defineconstintegers create one property for each element in the array what contains a non-zero name field. on success, js_defineconstdoubles/js_defineconstintegers re
turns true, indicating it has created all properties listed in the array. otherwise it re
turns false. see also mxr id search for js_defineconstdoubles mxr id search for js_defineconstintegers jsconstdoublespec jsconstintegerspec js_defineelement js_defineproperties js_defineproperty js_definepropertywithtinyid bug 1066020 - added js_defineconstintegers ...
JS_DefineElement
that defines the property's initial value. getter and setter identify the getproperty and setproperty methods for the property, respectively. if you pass null values for these entries, js_defineelement assigns the default getproperty and setproperty methods to this element. obsolete since jsapi 32 flags contains the property attributes to set for the new property. on success, js_defineelement re
turns true. otherwise it re
turns false. obsolete since jsapi 32. while you can assign a setproperty method to a property and set flags to jsprop_readonly, the setter method will not be called on this property. see also mxr id search for js_defineelement js_defineconstdoubles js_definefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_definepropertywithtinyid js...
JS_DefineFunction
ll is a pointer to the c/c++ function that is to be exposed to javascript. nargs indicates the number of arguments the function expects to receive. this becomes the new function object's length property and can be accessed using js_getfunctionarity. flags is the logical or of zero or more property attributes, which apply to the new property. on success, js_definefunction and js_defineucfunction re
turn a pointer to the new function. on error or exception, they re
turn null. see also mxr id search for js_definefunction mxr id search for js_defineucfunction mxr id search for js_definefunctionbyid js_callfunctionname js_callfunctionvalue js_compilefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_getfunctionobject js_newfunction bug 607695 - added js...
JS_DefineFunctions
t of the array must contain 0 values. (the macro js_fs_end can be used for the last element.) js_definefunctions creates one function for each non-zero element in the array. propertydefinitionbehavior is used to select if properties with jsprop_define_late flag should be defined on the object. normal jsapi consumers probably always want defineallproperties here. on success, js_definefunctions re
turns true. on error or exception, it stops defining functions and re
turns false. see also mxr id search for js_definefunctions js_callfunctionname js_defineobject js_defineproperties js_newfunction bug 959787 - make fs type to const bug 825199 - added propertydefinitionbehavior ...
JS_DefineObject
t of the class clasp and assigns it to a new property of an existing object, obj. name is the property name to assign to obj to hold the new object, and flags contains the property attributes to set for the newly created property. the new object's parent is obj. js_defineobject does not call clasp->constructor. initialization of the new object is up to the caller. on success, js_defineobject re
turns a pointer to the new object. on error or exception (if the object cannot be created, the property already exists, or the property cannot be created), js_defineobject re
turns null. this function combines two operations: creating an object and storing it in a property of another object. use js_constructobject, js_constructobjectwitharguments, or js_newobject to create a new object without storing...
JS_DefineProperties
ines a single property: its name, attributes, getter, and setter. the name field of the last array element must be null. js_defineproperties creates one property for each element in the array before the element with a null name field. each property is defined as though by calling js_defineproperties. the initial stored value of each property created is undefined. on success, js_defineproperties re
turns true, indicating it has created all properties listed in the array. otherwise it re
turns false. see also mxr id search for js_defineproperties js_defineconstdoubles js_defineelement js_definefunction js_definefunctions js_defineobject js_defineproperty js_initclass bug 855582 ...
JS_DefineProperty
ss.setproperty) callback from obj's class. if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (or setter) must point to a javascript function, not a c/c++ function. that is, it must be a jsobject * that points to a javascript function, cast to type jspropertyop. for more about javascript getters and setters, see defining getters and setters. on success, js_defineproperty re
turns true. on error or exception, it re
turns false. see also mxr id search for js_defineproperty mxr id search for js_defineucproperty mxr id search for js_definepropertybyid js_defineelement bug 461163 bug 1113369 -- added desc and result parameters ...
JS_DeleteElement
js::objectopresult & (out parameter) receives the result of the operation. description js_deleteelement removes a specified element or numeric property, index, from an object, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement re
turns true. otherwise it re
turns false. for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the error before re
turning false. for javascript 1.3 and later, the attempt is silently ignored. to truncate an array, use js_setarraylength. to remove all elements and properties from an object, call js_clearscope. see al...
JS_DeleteElement2
deleted because it is permanent and true otherwise. description js_deleteelement2 removes a specified element or numeric property, index, from an object, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement2 stores true to *succeeded and re
turns true. otherwise it re
turns false and the value of *succeeded is undefined. notes per the ecma standard, js_deleteelement2 removes read-only properties from objects as long as they are not also permanent. for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the error and re
turns false. for javascript 1.3, the attempt is silently ignor...
JS_DeleteProperty
ified property from its prototype, then obj's jsclass.delproperty hook is called. no property is deleted, but this is not an error. if obj has the specified property but it is permanent, nothing happens. no property is deleted, but this is not an error. otherwise obj has a non-permanent own property with the given name or id. in this case, obj's jsclass.delproperty hook is called. if the hook re
turns false, the error is propagated. otherwise, if obj is not configurable, an error is raised. otherwise, the property is removed. these functions re
turn true on success, regardless of whether a property was actually deleted, and false on error or exception. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.)...
JS_DeleteProperty2
eded). no property is deleted, but this is not an error. if obj has the specified property but it is permanent, then *succeeded receives false. no property is deleted, but this is not an error. otherwise obj has a non-permanent own property with the given name or id. in this case, *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded). if the hook re
turns false, the error is propagated. otherwise, if obj is not configurable, an error is raised. otherwise, *succeeded receives true and the property is removed. these functions re
turn true on success, regardless of whether a property was actually deleted. on error or exception, the re
turn value is false, and the value left in *succeeded is unspecified. jsobjectops.deleteproperty implements this be...
JS_DoubleIsInt32
(comment from mozilla::numberequalsint32) casting a floating-point value that doesn't truncate to int32_t, to int32_t, induces undefined behavior. we should definitely fix this (bug 744965), but as apparently it "works" in practice, it's not a pressing concern now. see also mxr i...
JS_EncodeStringToBuffer
on this jscontext. str jsstring * a string to encode. buffer char * a character buffer to receive encoded string. length size_t the size of buffer in bytes. description js_encodestringtobuffer converts the specified javascript str to a c string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string. it re
turns the length of the whole string encoding or (size_t)-1 if the string can't be encoded as bytes. if the re
turned value is greater than the length you specified, the string was truncated. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. see also mxr id search for js_encodestringtobuffer js_encodestring js_encodestringtoutf8 js_getstringencodi...
JS_EnterCompartment
rtment call is needed. target jsobject * the object in a different compartment to be accessed. this implicitly identifies the compartment to be entered. description every jscontext has a current compartment. any access to an object in a different compartment must be bracketed by calling js_entercompartment and js_leavecompartment. on success, js_entercompartment re
turns a pointer to the previously entered compartment. to re
turn to that compartment, pass it to js_leavecompartment. js_entercompartment is infallible, so a null re
turn value doesn't indicate failure. see also mxr id search for js_entercompartment js_leavecompartment jsautocompartment bug 786068 ...
JS_EnterCrossCompartmentCall
target jsobject * the object in a different compartment to be accessed. this implicitly identifies the compartment to be entered. description every jscontext has a current compartment. any access to an object in a different compartment must be bracketed by calling js_entercrosscompartmentcall and js_leavecrosscompartmentcall. on success, js_entercrosscompartmentcall re
turns a pointer to a jscrosscompartmentcall object that must be passed to js_leavecrosscompartmentcall. otherwise it re
turns null. see also js_leavecrosscompartmentcall js_entercompartment js_leavecompartment bug 786068 bug 563099 ...
JS_Enumerate
properties of the specified object, obj, that have the jsprop_enumerate attribute. (the term own property refers to a property that is not inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in loop, which converts all property ids to strings and also enumerates inherited properties. this calls obj's jsclass.enumerate hook. on success, js_enumerate re
turns a pointer to the first element of an array of property ids. the application must free this array using js_destroyidarray. on error or exception, js_enumerate re
turns null. the property ids in the re
turned jsidarray are subject to garbage collection. as long as obj is reachable, its current property ids are reachable. but, for example, if an application calls back into javascript while it is ...
JS_EnumerateResolvedStandardClasses
g it. enumerate any already-resolved standard class ids. syntax jsidarray * js_enumerateresolvedstandardclasses(jscontext *cx, jsobject *obj, jsidarray *ida); name type description description js_enumerateresolvedstandardclasses enumerates any already-resolved standard class ids into ida, or into a new jsidarray if ida is null. re
turn the augmented array on success, null on failure with ida (if it was non-null on entry) destroyed. see also js_enumerateresolvedstandardclasses bug 884410 ...
JS_ErrorFromException
cx jscontext * pointer to a js context whose errors should be reported via your function. other contexts in the same runtime can have their own error reporting functions. obj js::handleobject an exception object. description if obj is an exception object, the exception will have (or be able to lazily create) an error report struct, and js_errorfromexception will re
turn the address of that struct. otherwise, it re
turns nullptr. the lifetime of the error report struct that might be re
turned is the same as the lifetime of the exception object. see also mxr id search for js_errorfromexception jserrorreport ...
JS_EvaluateScript
ard eval function. in the common case where the script is just an expression, the result value is simply the value of that expression. more generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. if a script compiles and executes successfully, js_evaluatescript or js_evaluateucscript stores the result in *rval, if non-null, and re
turns js_true. otherwise it re
turns js_false and the value left in *rval is undefined. see also mxr id search for js_evaluatescript mxr id search for js_evaluateucscript js_compilefile js_compilescript js_decompilescript js_destroyscript js_evaluatescriptforprincipals bug 1100579 ...
JS_EvaluateScriptForPrincipals
tion is used in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. if the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and js_evaluatescriptforprincipals or js_evaluateucscriptforprincipals re
turns js_true. otherwise it re
turns js_false, and the value left in *rval is undefined. see also js::evaluate js_compilefile js_compilescriptforprincipals js_evaluatescript bug 980180 ...
JS_ExecuteScript
t. description js_executescript executes a previously-compiled script, script. js::cloneandexecutescript handles a cross-compartment script. if the script is cross-compartment, it is cloned into the current compartment before executing. if the script executes successfully, rval receives the value from the last executed expression statement processed in the script, and js_executescript re
turns true. otherwise it re
turns false, and the value left in rval is unspecified. the jsapi user guide contains example code using compiled scripts. to execute a script that has not been compiled, use js::evaluate instead. see also mxr id search for js_executescript mxr id search for js::cloneandexecutescript js::compile js::evaluate bug 993438 bug 1145294 -- removed obj from js::cloneand...
JS_ExecuteScriptPart
statement in the script. description js_executescriptpart executes part of a previously compiled script, script. the part parameter must be either jsexec_prolog to execute the script prolog or jsexec_main to execute the main section of the script. if the script executes successfully, js_executescriptpart stores the value of the last-executed expression statement in the script in *rval and re
turns js_true. otherwise it re
turns js_false, and the value left in *rval is undefined. to execute both parts of a script, use js_executescript instead. see also mxr id search for js_executescriptpart js_executescript bug 555104 ...
JS_ExecuteScriptVersion
success, *rval receives the value from the last executed expression statement processed in the script. version jsversion version for the script. description js_executescript executes a previously-compiled script, script. if the script executes successfully, *rval receives the value from the last executed expression statement processed in the script, and js_executescript re
turns true. otherwise it re
turns false, and the value left in *rval is unspecified. to execute a script that has not been compiled, use js::evaluate instead. see also js::compile js_executescript js::evaluate bug 1095660 ...
JS_FORGET_STRING_FLATNESS
this article covers features introduced in spidermonkey 1.8.5 convert jsflatstring to jsstring. syntax static moz_always_inline jsstring * js_forget_string_flatness(jsflatstring *fstr) { re
turn (jsstring *)fstr; } name type description fstr jsflatstring * a string to convert description js_forget_string_flatness converts jsflatstring * to jsstring *. see also mxr id search for js_forget_string_flatness jsflatstring jsstring bug 609440 ...
JS_FileEscapedString
inter to write into. str jsstring * a string to write into the file. quote char one of 0, single quote, and double quote. description js_fileescapedstring writes str into file fp escaping any non-printable or non-ascii character. if quote is not 0, it must be a single or double quote character that will quote the output. if successful, js_fileescapedstring re
turns true, otherwise false. see also mxr id search for js_fileescapedstring bug 609440 ...
JS_ForwardGetPropertyTo
und. description js_forwardgetpropertyto is the base implementation of js_getproperty, js_getucproperty, js_getpropertybyid etc, where onbehalfof is same to obj. onbehalfof is receiver in [[get]] internal method of proxy, defined in es2015 draft spec (rev 29, 9.5.8). on success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and re
turn true. on an error or exception, these functions re
turn false, and the value left in *vp is undefined. see also mxr id search for js_forwardgetpropertyto js_getproperty bug 698551 ...
JS_GET_CLASS
prior to spidermonkey 1.8.8, js_getclass took both a jscontext* and a jsobject* as arguments in thread-safe builds, and in non-thread-safe builds it took only a jsobject*. the js_get_class(cx, obj) macro abstracted away this detail. newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe. description js_get_class re
turns a pointer to the jsclass associated with a specified js object, obj. the application must treat the jsclass as read-only. to check the type of an object, use js_hasinstance instead. for a stricter, exact-match-only check, use js_instanceof or js_getinstanceprivate. the js_get_class abstracted away signature differences in the js_getclass method in threadsafe and non-threadsafe builds. as of spi...
JS_GetArrayLength
of the array. description js_getarraylength gets the .length property of obj as though by calling js_getproperty and converts it to a 32-bit unsigned integer. if obj is an array (see js_isarrayobject), this is guaranteed to succeed, because the .length property of an array is always a number and can't be deleted or redefined. on success, js_getarraylength stores the length in *lengthp and re
turns true. on failure, it reports an error and re
turns false, and the value left in *lengthp is undefined. see also mxr id search for js_getarraylength js_getelement js_setarraylength ...
JS_GetArrayPrototype
a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose array.prototype is being retrieved. description js_getarrayprototype() retrieves the original array.prototype of a specified object, obj. if an error occurs, it re
turns null. note: this expression might have different values over time if the global array property is modified, but this method re
turns only the original value. see also mxr id search for js_getarrayprototype bug 872043 ...
JS_GetClass
s prior to spidermonkey 1.8.8, js_getclass took both a jscontext* and a jsobject* as arguments in thread-safe builds, and in non-thread-safe builds it took only a jsobject*. the js_get_class(cx, obj) macro abstracted away this detail. newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe. description js_getclass re
turns a pointer to the jsclass associated with a specified js object, obj. the application must treat the jsclass as read-only. if obj has no jsclass, this re
turns null. to check the type of an object, use js_hasinstance instead. for a stricter, exact-match-only check, use js_instanceof or js_getinstanceprivate. see also mxr id search for js_getclass bug 723517 ...
JS_GetClassObject
ller must be in a request on this jscontext. key jsprotokey the key of the prototype. objp js::mutablehandle<jsobject*> out parameter. if successful, receive the class constructor. description js_getclassobject gets the builtin class costructor for the specified prototype key. if successful, js_getclassobject stores the class constructor to *objp and re
turns true, otherwise re
turns false and the value of *objp is undefined. see also mxr id search for js_getclassobject js_getclassprototype jsprotokey ...
JS_GetClassPrototype
a request on this jscontext. key jsprotokey the key of the prototype. objp js::mutablehandle<jsobject*> out parameter. if successful, receive the class prototype object. description js_getclassprototype gets the builtin class costructor for the specified prototype key. if successful, js_getclassprototype stores the class prototype object to *objp and re
turns true, otherwise re
turns false and the value of *objp is undefined. see also mxr id search for js_getclassprototype js_getclassobject jsprotokey ...
JS_GetConstructor
retrieves the constructor for an object. syntax jsobject * js_getconstructor(jscontext *cx, js::handle<jsobject*> proto); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle<jsobject*> the object whose constructor is to be re
turned. description js_getconstructor retrieves the constructor property of a given object, obj. if the result is a function object, js_getconstructor re
turns a pointer to that object. otherwise, it reports an error and re
turns null. to get an object's prototype, use js_getprototype. to get an object's parent, use js_getparent. see also mxr id search for js_getconstructor ...
JS_GetContextThread
obsolete since jsapi 8this 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. re
turns the id of the associated thread for a context. syntax int js_getcontextthread(jscontext *cx); name type description cx jscontext * the context to examine. description js_getcontextthread re
turns the id of the thread currently associated with this context. if the context is not currently associated with any thread, the re
turn value is 0. see js_setcontextthread. js_getcontextthread is available only if the engine is built with js_threadsafe. mxr id search for js_getcontextthread ...
JS_GetDefaultFreeOp
this article covers features introduced in spidermonkey 17 re
turn default jsfreeop for the runtime. syntax jsfreeop * js_getdefaultfreeop(jsruntime *rt); name type description rt jsruntime * a pointer to the runtime. description js_getdefaultfreeop re
turns default jsfreeop for the runtime. see also mxr id search for js_getdefaultfreeop js_freeop jsfreeop bug 737365 ...
JS_GetEmptyString
this article covers features introduced in spidermonkey 1.8.5 re
turns the empty string as a jsstring object. syntax jsstring * js_getemptystring(jsruntime *rt); name type description rt jsruntime * the runtime for which to re
turn the empty string. description the re
turned empty string has the length 0. see also mxr id search for js_getemptystring js_getstringlength js_getemptystringvalue bug 612150 ...
JS_GetEmptyStringValue
s::value. syntax // added in spidermonkey 42 js::value js_getemptystringvalue(jscontext *cx); // obsolete since spidermonkey 42 jsval js_getemptystringvalue(jscontext *cx); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_getemptystringvalue re
turns the empty string as a js::value. see also mxr id search for js_getemptystringvalue bug 1184564 -- changed jsval to js::value ...
JS_GetErrorPrototype
this article covers features introduced in spidermonkey 38 re
turn the original value of error.prototype. syntax jsobject * js_geterrorprototype(jscontext *cx); name type description cx jscontext * pointer to a js context whose errors should be reported via your function. other contexts in the same runtime can have their own error reporting functions. description js_geterrorprototype re
turns the original value of error.prototype from the global object of the current compartment of cx. see also mxr id search for js_geterrorprototype bug 997285 ...
JS_GetExternalStringClosure
obsolete since jsapi 13this 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. this article covers features introduced in spidermonkey 6 re
turns the string closure stored in a jsstring created by calling js_newexternalstringwithclosure. syntax void * js_getexternalstringclosure(jscontext *cx, jsstring *str); name type description cx jscontext * the context from which to retrieve the closure for a string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string for which to re
turn the closure. the result is null if the external string was created without one (that is, by callin...
JS_GetExternalStringFinalizer
this article covers features introduced in spidermonkey 17 get the string finalizer of an external string. syntax const jsstringfinalizer * js_getexternalstringfinalizer(jsstring *str); name type description str jsstring * a string to get finalizer. description js_getexternalstringfinalizer re
turns the fin parameter passed to js_newexternalstring. see also mxr id search for js_ js_newexternalstring bug 724810 ...
JS_GetFunctionArity
this is the same as the function object's arity property, if that property has not been overwritten. specifically, if fun is a native function, the result is the value that was passed to the nargs parameter of js_definefunction. ...
JS_GetFunctionName
retrieve the given name for a specified function. use js_getfunctionid instead. syntax const char * js_getfunctionname(jsfunction *fun); name type description fun jsfunction * a pointer to a javascript function. description js_getfunctionname retrieves the function name associated with a function pointer, fun. the re
turn value is either the name of a function, or the string "anonymous", which indicates that the function was not assigned a name when created. the pointer re
turned by this function is valid only as long as the specified function, fun, exists. see also js_getfunctionid js_getfunctiondisplayid bug 617215 ...
JS_GetFunctionPrototype
ript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose function.prototype is being retrieved. description js_getfunctionprototype() retrieves the original function.prototype of a specified object, obj. if an error occurs, it re
turns null. note: this expression might have different values over time if the global function property is modified, but this method re
turns only the original value. see also mxr id search for js_getfunctionprototype bug 726182 ...
JS_GetGCParameter
candidates. jsgc_pretenure_group_threshold / "pretenuregroupthreshold" if more than this number of objects in a given object group are tenured, then pretenruing will be enabled for new objects in this group. jsgc_min_last_ditch_gc_period / "minlastditchgcperiod" the minimum time to allow between triggering last ditch gcs in seconds. description js_getgcparameter re
turns the current parameter of the garbage collection. if successful, js_getgcparameter re
turns the current parameter. js_setgcparameter ajusts the parameter of the garbage collection. see also mxr id search for js_getgcparameter mxr id search for js_setgcparameter bug 474801 jsgc_bytes jsgc_number bug 474497 jsgc_max_code_cache_bytes this option no-longer exists js_...
JS_GetGlobalForCompartmentOrNull
this article covers features introduced in spidermonkey 17 re
turn the global object for the specified compartment. syntax jsobject * js_getglobalforcompartmentornull(jscontext *cx, jscompartment *c); name type description cx jscontext * the context for which to re
turn the global object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. c jscompartment * the compartment for which to re
turn the global object. description js_getglobalforcompartmentornull() re
turns the global object for the context and the compartment. this may re
turn null if c never had a global (e.g., the atoms compartment), or if c's global has been collected. see also mxr id search for js_getglobalforcom...
JS_GetGlobalForObject
re
turns the global object for the given object. syntax jsobject * js_getglobalforobject(jscontext *cx, jsobject *obj); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * a non-null jsobject. description js_getglobalforobject re
turns the last non-null object on the parent chain of the input object. for function object inputs, the result is "the global object" as referred to in the ecmascript specification. for example, if the function refers to a global variable foo, then foo is a property of the object re
turned by js_getglobalforobject. see also mxr id search for js_getglobalforobject ...
JS_GetImplementationVersion
get the version number of the js engine. syntax const char * js_getimplementationversion(void); description js_getimplementationversion re
turns a hard-coded, english language string that specifies the version number of the js engine currently in use, and its release date. see also mxr id search for js_getimplementationversion js_getversion js_setversionforcompartment ...
JS_GetInternedStringChars
et the chars of an interned string. syntax const jschar * js_getinternedstringchars(jsstring *str); const jschar * js_getinternedstringcharsandlength(jsstring *str, size_t *length); name type description str jsstring * the interned string. length size_t * out parameter. receives the length of the string. description js_getinternedstringchars re
turns a pointer to the interned string. js_getinternedstringcharsandlength re
turns a pointer to the interned string and stores the length of it to *length. see also bug 1037869 bug 609440 ...
JS_GetLatin1FlatStringChars
name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext.. nogc js::autocheckcannotgc & a reference to js::autocheckcannotgc. str jsflatstring * a string to get characters. description js_getlatin1flatstringchars and js_gettwobyteflatstringchars re
turn a pointer to the string. see also mxr id search for js_getlatin1flatstringchars mxr id search for js_gettwobyteflatstringchars js_getlatin1stringcharsandlength js_gettwobytestringcharsandlength js_getlatin1internedstringchars js_gettwobyteinternedstringchars bug 1037869 ...
JS_GetLatin1InternedStringChars
t be in a request on this jscontext.. nogc js::autocheckcannotgc & a reference to js::autocheckcannotgc. str jsstring * a string to get characters. description js_getlatin1internedstringchars and js_gettwobyteinternedstringchars gets the characters of the string, str. if successful, js_getlatin1stringcharsandlength and js_gettwobytestringcharsandlength re
turn a pointer to the string, otherwise re
turn null. see also mxr id search for js_getlatin1internedstringchars mxr id search for js_gettwobyteinternedstringchars js_getlatin1flatstringchars js_gettwobyteflatstringchars js_getlatin1stringcharsandlength js_gettwobytestringcharsandlength bug 1037869 ...
JS_GetLatin1StringCharsAndLength
to js::autocheckcannotgc. str jsstring * a string to get characters. length size_t * out parameter. receives the length of the string. description js_getlatin1stringcharsandlength and js_gettwobytestringcharsandlength get the characters and the length of the string, str. if successful, js_getlatin1stringcharsandlength and js_gettwobytestringcharsandlength re
turn a pointer to the string, and store the length to *length, otherwise re
turn null. see also mxr id search for js_getlatin1stringcharsandlength mxr id search for js_gettwobytestringcharsandlength js_getlatin1flatstringchars js_gettwobyteflatstringchars js_getlatin1internedstringchars js_gettwobyteinternedstringchars bug 1032726 ...
JS_GetLocaleCallbacks
mpare implementation of string.prototype.localecompare() function. if expose_intl_api is defined, intl api is used instead. jslocaletounicode convert locale specific string to unicode string. description js_setlocalecallbacks establishes locale callbacks. the pointer must persist as long as the jsruntime. passing nullptr restores the default behaviour. js_getlocalecallbacks re
turns the address of the current locale callbacks struct, which may be nullptr. see also mxr id search for js_getlocalecallbacks mxr id search for js_setlocalecallbacks mxr id search for jslocalecallbacks mxr id search for jslocaletouppercase mxr id search for jslocaletolowercase mxr id search for jslocalecompare mxr id search for jslocaletounicode ...
JS_GetNaNValue
get the not-a-number (nan) floating-point number as a value of type js::value. syntax // added in spidermonkey 42 js::value js_getnanvalue(jscontext *cx); // obsolete since spidermonkey 42 jsval js_getnanvalue(jscontext *cx); name type description cx jscontext * a context. description js_getnanvalue re
turns a value of type js::value that represents an ieee floating-point quiet not-a-number (nan). nan is typically used in javascript as the re
turn value of a numeric operation when an argument is invalid or conversion fails. for example, 0/0 and math.sqrt(-1) both re
turn nan. so do number("xyzzy") and math.sin("frank"). while the ieee standard defines many nan bit-patterns, they are indistinguishable in javascript, so in effect there's only one nan. ...
JS_GetObjectPrototype
javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. forobj js::handleobject an object from the global whose object.prototype is being retrieved. description js_getobjectprototype() retrieves the original object.prototype of a specified object, obj. if an error occurs, it re
turns null. note: this expression might have different values over time if the global object property is modified, but this method re
turns only the original value. see also mxr id search for js_getobjectprototype bug 725888 ...
JS_GetOptions
browsers, its use is discouraged since it could be removed at any time. try to avoid using it. get the currently enabled jscontext options. syntax uint32 js_getoptions(jscontext *cx); name type description cx jscontext * the context from which to read options. description js_getoptions retrieves the option flags of a given js context cx. this function re
turns a uint32 value that is the logical or of zero or more of the jsoption flags described in js_setoptions. see also mxr id search for js_getoptions js_setoptions js_toggleoptions bug 880330 ...
JS_GetOwnPropertyDescriptor
ndleid or const char16_t the name of the property to look up. desc js::mutablehandle<jspropertydescriptor> out parameter. on success, if no property is found, desc->obj is set to null. if a property is found, *desc receives a description of it. description js_getownpropertydescriptor and js_getownpropertydescriptorbyid get a detailed description of that property (re
turned in desc->obj). if desc->obj is null, then this property was not found on the prototype chain. see also mxr id search for js_getownpropertydescriptor mxr id search for js_getownpropertydescriptorbyid mxr id search for js_getownucpropertydescriptor js_getpropertydescriptor js_getpropertydescriptorbyid jspropertydescriptor bug 893186 bug 1135731 -- added js_getownpropertydescriptor ...
JS_GetParent
y domain as its parent. (but each application can define its own security rules. see the security section of the user guide for an introduction to the security model.) in some cases, javascript code can get an object's parent via the read-only obj.__parent__ property. but if an object's parent is an internal-use-only object (that is, a special call, with, or block object), js_getparent simply re
turns it, but obj.__parent__ === null. similarly, if an object's parent is an inner object, js_getparent simply re
turns it, but obj.__parent__ re
turns the corresponding outer object. see also mxr id search for js_getparent bug 1131805 -- removed ...
JS_GetParentRuntime
rmonkey 31 retrieve a pointer to the parent jsruntime. syntax jsruntime * js_getparentruntime(jscontext *cx); name type description cx jscontext * the context to query. description js_getparentruntime retrieves a pointer to the parent jsruntime of the runtime for a specified jscontext. if the cx's runtime has no parent runtime, js_getparentruntime re
turns cx's runtime itself. see also mxr id search for js_getparentruntime js_getruntime bug 964059 ...
JS_GetPendingException
tion was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp js::mutablehandlevalue out parameter. on success, *vp receives the current pending exception. description if an exception has been thrown in the context cx, and it has not yet been caught or cleared, js_getpendingexception stores the exception object in *vp and re
turns true. otherwise, it re
turns false, and the value left in *vp is undefined. see examples in the jsapi phrasebook. see also mxr id search for js_getpendingexception js_isexceptionpending js_clearpendingexception js_reportpendingexception js_setpendingexception ...
JS_GetPositiveInfinityValue
added in spidermonkey 42 js::value js_getpositiveinfinityvalue(jscontext *cx); js::value js_getnegativeinfinityvalue(jscontext *cx); // obsolete since spidermonkey 42 jsval js_getpositiveinfinityvalue(jscontext *cx); jsval js_getnegativeinfinityvalue(jscontext *cx); name type description cx jscontext * a context. description js_getpositiveinfinityvalue re
turns a js::value that represents an ieee floating-point positive infinity. js_getnegativeinfinityvalue re
turns the corresponding negative infinity. infinities are typically used to represent numbers that are greater in magnitude than the greatest representable finite values. as a value in mathematical calculations, an infinite value behaves like infinity. for example, any nonzero value multiplied by...
JS_GetPropertyDefault
js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getpropertydefault examines a specified js object obj and its prototype chain for a property with the specified name. on success, these functions set *vp to the current value of the property, or def if obj has no such property, and re
turn true. on an error or exception, these functions re
turn false, and the value left in *vp is undefined. see also bug 905774 ...
JS_GetPropertyDescriptor
k up. desc js::mutablehandle<jspropertydescriptor> out parameter. on success, if no property is found, desc->obj is set to null. if a property is found, *desc receives a description of it. description js_getpropertydescriptor and js_getpropertydescriptorbyid find a specified property of an object and gets a detailed description of that property on the prototype chain (re
turned in desc->obj). if desc->obj is null, then this property was not found on the prototype chain. see also mxr id search for js_getpropertydescriptor mxr id search for js_getpropertydescriptorbyid js_getownpropertydescriptor js_getownpropertydescriptorbyid jspropertydescriptor bug 482381 - added js_getpropertydescriptorbyid bug 893186 - added js_getpropertydescriptor ...
JS_GetPrototype
for which to retrieve the prototype. protop js::mutablehandleobject out parameter. if successful, receives prototype object of obj. description js_getprototype retrieves the prototype of a specified object, obj. a prototype object provides properties inherited by similar js objects. this is the equivalent of object.getprototypeof(obj) from javascript. if js_getprototype re
turns false, that signals an exception, which should be handled as usual. otherwise, it stores a pointer to the prototype or null to *protop and re
turns true. to set an object's prototype, use js_setprototype. see also mxr id search for js_getprototype js_setprototype ...
JS_GetRegExpFlags
this article covers features introduced in spidermonkey 17 get the flags of the given regexp object. syntax unsigned js_getregexpflags(jscontext *cx, handleobject obj) name type description cx jscontext * a context. obj js::handleobject the object to get the flags. description js_getregexpflags re
turns flags of the specified object, obj. if successful, js_getregexpflags re
turns the flags, otherwise re
turns false. see also mxr id search for js_getregexpflags js_newregexpobject js_newucregexpobject flags regexp bug 655641 ...
JS_GetRegExpSource
this article covers features introduced in spidermonkey 17 get the source string of the given regexp object. syntax jsstring * js_getregexpsource(jscontext *cx, js::handleobject obj); name type description cx jscontext * a context. obj js::handleobject the object to get the source string. description js_getregexpsource re
turns a source string of the specified object, obj. if successful, js_getregexpsource re
turns a pointer to the source string, otherwise re
turns null. see also mxr id search for js_getregexpsource js_newregexpobject js_newucregexpobject regexp bug 655641 ...
JS_GetReservedSlot
long as the object itself is alive. reserved slots may also contain private values to store pointer values (whose lowest bit is 0) or uint32_t, when non-javascript values must be stored; the garbage collector ignores such values when it sees them. (note that private values must not be exposed directly to javascript. it's only legal to store and retrieve data from private values. they cannot be re
turned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved slots are initialized to undefined. see also mxr id search for js_getreservedslot mxr id search for js_setreservedslot bug 1184564 -- changed jsval to js::value ...
JS_GetStringEncodingLength
get the length of a javascript string in bytes. syntax size_t js_getstringencodinglength(jscontext *cx, jsstring *str); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext.. str jsstring * a string to encode. description js_getstringencodinglength re
turns the length of the specified string in bytes, regardless of its encoding. you can use this value to create a buffer to encode the string into using the js_encodestringtobuffer function. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. see also mxr id search for js_getstringencodinglength js_encodestringtobuffer js::deflatestringtoutf8buffer ...
JS_GetTwoByteExternalStringChars
atures introduced in spidermonkey 38 get the chars of an external string. syntax const char16_t * js_gettwobyteexternalstringchars(jsstring *str); name type description str jsstring * a string to get characters. description js_gettwobyteexternalstringchars gets the characters of the string, str. js_gettwobyteexternalstringchars always succeeds, and re
turns a pointer to the string. see also mxr id search for js_gettwobyteexternalstringchars js_getlatin1flatstringchars js_gettwobyteflatstringchars js_getlatin1stringcharsandlength js_gettwobytestringcharsandlength js_getlatin1internedstringchars js_gettwobyteinternedstringchars bug 1034627 ...
JS_GetTypeName
obsolete since jsapi 34this 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. re
turns a pointer to the string literal description of a specified js data type. syntax const char * js_gettypename(jscontext *cx, jstype type); name type description cx jscontext * pointer to a js context from which to derive runtime information. type jstype one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. description js_gettypename re
turns a pointer to a string literal description of a specified js data type, type. the following table lists jstypes and the string literals reported by js_gettypename: ...
JS_GetVersion
the result is one of the jsversion constants. when a context is created, its version is initially jsversion_default. ...
JS_HasArrayLength
this jscontext. obj jsobject * array object to get the length of. lengthp jsuint * out parameter. on success, *lengthp receives the length of the array. description js_hasarraylength determines if an object, obj, has a length property. if the property exists, js_hasarraylength stores the current value of the property in *lengthp. on success, js_hasarraylength re
turns js_true, and *lengthp receives the current value of the length property. on failure, js_hasarraylength re
turns js_false, and the value left in *lengthp is undefined. this function differs from js_getarraylength in the treatment of errors and unusual cases, like when an object's length is negative or not a number. this function may re
turn js_false without having reported any error or exception. s...
JS_HasElement
index uint32_t index of the element to look up. foundp bool * out parameter. on success, it stores true to *foundp, false otherwise. description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_haselement sets *foundp to true. if not, it sets *foundp to false and re
turns true (to indicate no error occurred). if the search fails with an error or exception, js_haselement re
turns false, and the value left in *foundp is undefined. see also mxr id search for js_haselement js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_HasInstance
v js::handle<js::value> the value to test. bp bool * out parameter. on success, *bp receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof test in *bp and re
turns true. on error or exception, it re
turns false, and the value left in *bp is undefined. when providing a prototype as obj, the prototype's jsclass must have its hasinstance method set. otherwise js_hasinstance re
turns false. see also mxr id search for js_hasinstance js_instanceof ...
JS_HasOwnProperty
e if obj has an own property with the given name, and false if not. description js_hasownproperty searches an object, obj, for an own property with the specified name. it behaves like the javascript expression object.hasownproperty(obj, name). js_hasownpropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and re
turns true. if the object obj has no such property, the function sets *foundp to false and re
turns true (to indicate that no error occurred). if an error occurs during the search, the function re
turns false, and the value of *foundp is undefined. see also mxr id search for js_hasownproperty mxr id search for js_hasownpropertybyid bug 1163423 ...
JS_HasProperty
en name, and false if not. description js_hasproperty searches an object, obj, and its prototype chain, for a property with the specified name. it behaves like the javascript expression name in obj. js_hasucproperty is the corresponding unicode api. js_haspropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and re
turns true. if the object obj has no such property, the function sets *foundp to false and re
turns true (to indicate that no error occurred). if an error occurs during the search, the function re
turns false, and the value of *foundp is undefined. see also mxr id search for js_hasproperty mxr id search for js_hasucproperty mxr id search for js_haspropertybyid bug 461163 ...
JS_IdToProtoKey
type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. id js::handleid the property identifier to convert. description js_idtoprotokey converts a specified js id, id, to a prototype key. on success, js_idtoprotokey re
turns a jsprotokey. otherwise it re
turns jsproto_null. see also mxr id search for js_idtoprotokey js::protokeytoid bug 933681 ...
JS_IdToValue
est. in a js_threadsafe build, the caller must be in a request on this jscontext. id jsid the property identifier to convert. vp js::mutablehandle<js::value> out parameter. on success, *vp receives the converted value. description js_idtovalue converts a specified js id, id, to a js value. on success, js_idtovalue stores the converted value in *vp and re
turns true. otherwise it re
turns false. the inverse of js_idtovalue is js_valuetoid. see also mxr id search for js_idtovalue js_valuetoid ...
JS_Init
once this method has succeeded, it is safe to call js_newruntime and other jsapi methods. this method must be called before any other jsapi method is used on any thread. ...
JS_InitStandardClasses
nstructors, and constants are created as properties of obj. as a side effect, js_initstandardclasses establishes obj as the global object for cx, if one is not already established. this means that scripts executed in cx will see the properties of obj as global variables. see js_setglobalobject for details. obj must be of a jsclass that has the jsclass_global_flags flag. js_initstandardclasses re
turns js_true on success, and js_false if an error occurs. to initialize custom classes, use js_initclass. see also mxr id search for js_initstandardclasses ...
JS_InternJSString
ng * js_internjsstring(jscontext *cx, js::handlestring str); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str js::handlestring a string to be interned. description js_internjsstring converts a string str to interned string (interned atom) and re
turns the result string as jsstring *. on failure, js_internjsstring re
turns nullptr. see also mxr id search for js_internjsstring bug 609440 ...
JS_IsArrayObject
dleobject obj); name type description cx jscontext * a context. value js::handlevalue the value to examine. obj js::handleobject the object to examine. isarray bool whether the value/object is an array. description js_isarrayobject determines if a specified object, obj or value, is an array object. on success, re
turns true and sets isarray indicating whether obj is an array object or a wrapper around one. otherwise re
turns false on failure. see also mxr id search for js_isarrayobject bug 959787 - added value bug 1179003 - added isarray ...
JS_IsAssigning
obsolete since javascript 1.8.5this 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. determine whether script is executing assignment operation. syntax jsbool js_isassigning(jscontext *cx); name type description description js_isassigning re
turns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to js_isassigning. see also bug 458421 ...
JS_IsBuiltinEvalFunction
this article covers features introduced in spidermonkey 17 re
turn whether the given function is the global eval function. syntax bool js_isbuiltinevalfunction(jsfunction *fun); name type description obj jsfunction * pointer to the function to test. description js_isbuiltinevalfunction re
turns whether the given function is the global eval function. see also mxr id search for js_isbuiltinevalfunction js_isbuiltinfunctionconstructor bug 638312 ...
JS_IsBuiltinFunctionConstructor
this article covers features introduced in spidermonkey 17 re
turn whether the given function is the global function constructor. syntax bool js_isbuiltinfunctionconstructor(jsfunction *fun); name type description obj jsfunction * pointer to the function to test. description js::iscallable re
turns whether the given function is the global function constructor. see also mxr id search for js_isbuiltinfunctionconstructor js_isbuiltinevalfunction bug 638312 ...
JS_IsConstructor
this article covers features introduced in spidermonkey 24 re
turn whether the given function is a valid constructor. syntax bool js_isconstructor(jsfunction *fun); name type description fun jsfunction * the function to examine. description js_isconstructor determines if a specified function, fun is a valid constructor object. if so, js_isconstructor re
turns true. otherwise it re
turns false. see also mxr id search for js_isconstructor js::isconstructor bug 807228 ...
JS_IsExtensible
hreadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to examine. extensible bool * out parameter. receives true if extensible, false otherwise. description js_isextensible queries [[extensible]] property of the specified object, obj. if successful, js_isextensible stores [[extensible]] property to *extensible and re
turns true, otherwise re
turns false and the value of *extensible is undefined. see also mxr id search for js_preventextensions js_preventextensions bug 492845 ...
JS_IsGlobalObject
this article covers features introduced in spidermonkey 24 determine if given object is a global object. syntax bool js_isglobalobject(jsobject *obj); name type description obj jsobject * the object to examine. description js_isglobalobject re
turns true if obj is a global object, false otherwise. see also mxr id search for js_isglobalobject js_newglobalobject bug 797821 ...
JS_IsIdentifier
const char16_t * the pointer of the string to test. length size_t the length of chars. isidentifier bool * out parameter. on success, *isidentifier receives whether str is an identifier or not. description js_isidentifier tests if the given string is a valid ecmascript identifier. on successful, js_isidentifier stores the test result to *isidentifier and re
turns true, otherwise re
turns false and the value of *isidentifier is undefined. js_isidentifier which takes chars and length is infallible, so just re
turns whether the chars are an identifier. see also mxr id search for js_isidentifier js_valuetoid bug 692627 bug 990484 ...
JS_IsNative
this article covers features introduced in spidermonkey 17 determines if given jsobject is a native object. syntax bool js_isnative(jsobject *obj); name type description str jsobject * the object to check. description js_isnative re
turns true if the object is a native object. see also mxr id search for js_isnative js_isnativefunction bug 648647 ...
JS_IsNativeFunction
this article covers features introduced in spidermonkey 17 re
turn whether the given function object equals the specified native function. syntax bool js_isnativefunction(jsobject *funobj, jsnative call); name type description funobj jsobject * the function object to examine. call jsnative the native function to compare. description js_isnativefunction determines if a specified function object, funobj equals a specified native function, call. if so, js_isnativefunction re
turns true. otherwise it re
turns false. see also mxr id search for js_isnativefunction js_isnative bug 648801 ...
JS_IsRunning
indicates whether or not a script or function is currently executing in a given context. syntax bool js_isrunning(jscontext *cx); name type description cx jscontext * the context to query. description js_isrunning determines if a script or function is currently executing in a specified jscontext, cx. if a script is executing, js_isrunning re
turns true. otherwise it re
turns false. see also mxr id search for js_isrunning ...
JS_IsStopIteration
this article covers features introduced in spidermonkey 31 determine whether the value is a stopiteration exception or not. syntax // added in spidermonkey 42 bool js_isstopiteration(js::value v); // obsolete since spidermonkey 42 bool js_isstopiteration(jsval v); name type description v js::value the value to check. description js_isstopiteration re
turns true if v is stopiteration, otherwise false. see also mxr id search for js_isstopiteration js_throwstopiteration bug 918170 bug 1184564 -- changed jsval to js::value ...
JS_IterateCompartments
cx jsruntime * the runtime of the compartments. data void * data parameter passed to js_iteratecompartments. compartmentcallback jscompartment * the pointer to the compartment. description js_iteratecompartments calls compartmentcallback on every compartment. beware that there is no guarantee that the compartment will survive after the callback re
turns. also, barriers are disabled via the tracesession. see also mxr id search for js_iteratecompartments mxr id search for jsiteratecompartmentcallback bug 702300 bug 731618 bug 887030 ...
JS_LeaveCompartment
this article covers features introduced in spidermonkey 24 note: the preferred way of changing a context's current compartment is using jsautocompartment. leave a the compartment, re
turning to the compartment active before the corresponding js_entercompartment. syntax void js_leavecompartment(jscontext *cx, jscompartment *oldcompartment); name type description cx jscontext * the context in which to leave the compartment. oldcompartment jscompartment * value re
turned by previous call to js_entercompartment. description every jscontext has a current compartment. any access to an object in a different compartment must be bracketed by calls to js_entercompartment and js_leavecompartment. see also mxr id search for j...
JS_LeaveCrossCompartmentCall
obsolete since jsapi 18this 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. this article covers features introduced in spidermonkey 1.8.1 js_leavecrosscompartmentcall has been removed in bug 786068. use js_leavecompartment instead. leave a the compartment, re
turning to the compartment active before the corresponding js_entercrosscompartmentcall. syntax void js_leavecrosscompartmentcall(jscrosscompartmentcall *call); name type description call jscrosscompartmentcall * value re
turned by previous call to js_entercrosscompartmentcall. description every jscontext has a current compartment. any access to an object in a different compar...
JS_LinkConstructorAndPrototype
uctor object. proto js::handle<jsobject*> pointer to the prototype object. description js_linkconstructorandprototype sets the prototype property of class constructor function, ctor, to prototype object, proto with jsprop_permanent | jsprop_readonly flags, and sets the constructor property of proto to ctor with no flag. on successful, js_linkconstructorandprototype re
turns true. see also mxr id search for js_linkconstructorandprototype js_initclass bug 722729 ...
JS_LookupElement
ties whose names are numeric strings. for example, obj[6] is always exactly the same as obj["6"]. the ecmascript standard also specifies this behavior: see ecma 262-3 §11.2.1, step 6. so any call to js_lookupelement is equivalent to a call to js_lookupproperty passing a numeric string for the name. if the property obj[index] exists, js_lookupelement sets *vp to the property's stored value and re
turns true. if no such property exists, js_lookupelement sets *vp to undefined and re
turns true (to indicate that no error occurred). on error or exception, js_lookupelement re
turns false, and the value left in *vp is undefined. js_lookupelement does not distinguish between a property with a value of undefined and a property that does not exist. see also js_defineelement js_deleteelement js_get...
JS_LookupProperty
property, js_lookuppropertybyid, js_lookuppropertywithflags, and js_lookuppropertywithflagsbyid search a specified object, obj, for a property with the given name. these functions all have similar behavior: the search starts with obj and proceeds along the prototype chain. if the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the re
turn value is true. if neither obj nor any of its prototypes have such a property, *vp receives undefined and the re
turn value is true (to indicate no error occurred). on error or exception (such as running out of memory during the search), the re
turn value is false, and the value left in *vp is undefined. there is no way to tell the difference between not finding any property and finding a propert...
JS_LooselyEqual
the caller must be in a request on this jscontext. v1, v2 js::handle<js::value> the value to compare. equal bool * out parameter. receives the comparison result. description js_looselyequal determines if v1 is loosely equal to v2 under the javascript == operator, as specified in ecma 262-3 §11.9.3. if the comparison attempt was successful, the method re
turns js_true and stores the result in *equal; otherwise it re
turns js_false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent the same string or number. see also mxr id search for js_looselyequal js_strictlyequal js_samevalue ...
JS_MakeStringImmutable
d can read. (when an application shares a string by storing it in a javascript object that another thread can read, the javascript engine automatically makes the string thread-safe.) after a successful call to js_makestringimmutable, subsequent calls to js_getstringcharsz on the same string are guaranteed to succeed, and subsequent calls to js_getstringchars on the same string are guaranteed to re
turn a null-terminated string. see also bug 1115986 ...
JS_New
a new object as though by using the new operator, as described in ecma 262-3 §11.2.2. js_new(cx, ctor, args) is equivalent to the javascript expression new ctor(...args), and js_new(cx, ctor, argc, argv) is equivalent to the javascript expression new ctor(argv[0], argv[1], ... argv[argc-1]). if ctor is not an object that can be used as a constructor, a typeerror is raised. on success, js_new re
turns a pointer to the new object. on error, it re
turns null. see also mxr id search for js_new bug 480850 - added bug 959787 - added args parameter ...
JS_NewCompartmentAndGlobalObject
hat finally frees it. the usual way to do this is to make jsclasses global or static. principals jsprincipals * the security information to associate with this compartment. description js_newcompartmentandglobalobject creates a new compartment, and then creates a new global object as the first object in that compartment. on success, js_newcompartmentandglobalobject re
turns a pointer to the new global object. otherwise it re
turns null. see also js_newglobalobject bug 755186 bug 563099 ...
JS_NewContext
strings, and numbers may be shared among the contexts in a jsruntime, but they cannot be shared across jsruntimes. stackchunksize size_t the size, in bytes, of each "stack chunk". this is a memory management tuning parameter which most users should not adjust. 8192 is a good default value. description js_newcontext creates a new jscontext in the runtime rt. on success, it re
turns a pointer to the new context. otherwise it re
turns null. for more details about contexts, see jscontext. for sample code that creates and initializes a jscontext, see jsapi user guide. the stackchunksize parameter does not control the javascript stack size. (the jsapi does not provide a way to adjust the stack depth limit.) passing a large number for stackchunksize is a mistake. in a debug buil...
JS_NewDateObject
int the year to set the new object to. mon int the month to set the new object to. mday int the day of the month to set the new object to. hour int the hour to set the new object to. min int the minute to set the new object's time to. sec int the second to set the new object's time to. description creates and re
turns a new jsobject representing a javascript date object, which is pre-configured using the specified values. see also mxr id search for js_newdateobject js_newdateobjectmsec js_objectisdate bug 625870 ...
JS_NewDateObjectMsec
ated by the specified time in milliseconds since the unix epoch. syntax jsobject * js_newdateobjectmsec(jscontext *cx, double msec); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. msec double time since unix epoch in milliseconds. description the re
turned jsobject is a standard javascript date. see also mxr id search for js_newdateobjectmsec js_newdateobject js_objectisdate bug 625870 ...
JS_NewDependentString
string, str. the new string contains the same characters as if it were created with the javascript method str.substr(start, length). the characters are not copied. instead, the new string shares str's existing character storage. (implementation note: because of this sharing, the garbage collector will not collect str as long as the new substring is reachable.) on success, js_newdependentstring re
turns a pointer to the new string. otherwise it re
turns null. see also mxr id search for js_newdependentstring ...
JS_NewDouble
to a jsval, use js_newnumbervalue instead. warning: the argument d must not be a value that could fit in an integer jsval. if it is, js_newdouble creates a bad jsdouble that might behave as desired in some cases but not others. the new jsdouble is subject to garbage collection until you protect it using a local root, an object property, or the js_addroot function. on success, js_newdouble re
turns a pointer to the new number. otherwise it re
turns null. the application must treat the re
turned pointer as read-only. modifying a jsdouble allocated with this function can cause undefined behavior. see also js_numbervalue bug 549143 ...
JS_NewDoubleValue
eger jsval. if it is, js_newdoublevalue creates a bad jsval that might behave as desired in some cases but not others. the result is subject to garbage collection until you protect against it using a local root, an object property, or the js_addroot function. this can be avoided by using the address of a rooted variable as rval. on success, js_newdoublevalue stores a numeric jsval in *rval and re
turns js_true. otherwise it re
turns js_false and the value left in *rval is unspecified. see also js_numbervalue bug 549143 ...
JS_NewExternalString
acters in the array chars. fin jsstringfinalizer a string finalizer the javascript engine should use (later) to free the string buffer chars. added in spidermonkey 17 type int (js_newexternalstringwithclosure only) indicates which string finalizer callback the javascript engine should use (later) to free the string buffer chars. this must be an id number previously re
turned by a successful call to js_addexternalstringfinalizer. obsolete since jsapi 13 closure void * (js_newexternalstringwithclosure only) arbitrary, application-defined data to include in the string object after it's created. if you use this as a pointer, you should clean it up in the external string finalizer that was previously set up using js_addexternalstringfinalizer. obsolete si...
JS_NewFunction
t the new function wraps. nargs is the number of arguments the function expects. if flags is jsfun_constructor, a created function can be called as a constructor. parent may be used to specify the new function's parent; null is usually the right thing here. name is the name to assign to the function. if name is null, the new function has no name. (js_getfunctionid, passed the new function, will re
turn null.) on success, js_newfunction re
turns a pointer to the newly created function. otherwise it reports an out-of-memory error and re
turns null. see also mxr id search for js_newfunction mxr id search for js_newfunctionbyid js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_compileucfunction js_definefunction js_definefunctions js_getfunctionname js_getf...
JS_NewNumberValue
int jsval is created. some space for the new value may be allocated from the js garbage collection heap. in this case, the value is subject to garbage collection until you protect against it using a local root, an object property, or the js_addroot function. this can be avoided by using the address of a rooted variable as rval. on success, js_newnumbervalue stores a numeric jsval in *rval and re
turns js_true. otherwise it re
turns js_false and the value left in *rval is unspecified. see also js_numbervalue bug 752223 ...
JS_NewObject
lt parent object is used. obsolete since jsapi 39 description js_newobject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to establish the new object. clasp is a pointer to an existing class to use for internal methods, such as finalize. the javascript engine selects a prototype object for you. on success, js_newobject re
turns a pointer to the new object. otherwise it re
turns null. added in spidermonkey 1.8 js_newobjectwithgivenproto creates a new object with the specified prototype. if null is passed as proto, the new object will have a prototype with the js value of null. to create a new object as a property of an existing object, use js_defineobject, a convenience function that combines js_newobject and js_define...
JS_NewObjectForConstructor
nkey 38 description js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this function will assert (in debug builds). if the constructor does not have a prototype property, this function will re
turn null and set an exception on cx. the standard object creation api, js_newobject, takes explicit arguments for the class, prototype, and parent of the new object. with js_newobjectforconstructor, the prototype and parent are determined by the constructor, and class is still determined by the caller. the prototype is the prototype of the constructor if it is an object, otherwise null. the parent is...
JS_NewPlainObject
newplainobject(jscontext *cx); name type description cx jscontext * the context in which to create the new object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]]. on success, js_newplainobject re
turns a pointer to the new object. otherwise it re
turns nullptr. see also mxr id search for js_newplainobject js_newobject bug 1125356 ...
JS_NewPropertyIterator
gt; the object whose properties are to be enumerated. description create an object to iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this re
turns an iterator object that can be passed to js_nextproperty to fetch the property ids. on error, it re
turns null. the iterator object created by this function is not a javascript iterator. it is an opaque object with no properties visible from javascript. see also bug 1081660 ...
JS_NewRuntime
e jsruntime and initializes certain internal runtime structures. maxbytes specifies the number of allocated bytes after which garbage collection is run. if parentruntime is specified, the resulting runtime shares significant amounts of read-only state (the self-hosting and initial atoms compartments). it is recommended to make use of this for every runtime in a process after the first one. the re
turned jsruntime can be used from the calling thread only. (the engine may use helper threads internally, though.) on success, js_newruntime re
turns a pointer to the newly created runtime, which the caller must later destroy using js_destroyruntime. otherwise it re
turns null. notes ordinarily, js_newruntime should be the first jsapi call in an application, and js_destroyruntime and js_shutdown shou...
JS_NewStringCopyN
e array s contains more than n characters, the new string contains a truncated version of the original string. the string may contain null characters ('\0'). they are copied into the new string like any other character. you can use js_newstringcopyn to copy binary data or to copy only a certain portion of a c string into a javascript string. on success, js_newstringcopyn and js_newucstringcopyn re
turn a pointer to the new js string. otherwise they re
turn null. see also mxr id search for js_newstringcopyn mxr id search for js_newucstringcopyn js_getemptystringvalue js_newstringcopyz js_newucstringcopyz js_valuetostring ...
JS_NewStringCopyZ
a request on this jscontext. s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null. description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. on success, js_newstringcopyz re
turns a pointer to the new javascript string. on error, it re
turns null. if s is null, an empty javascript string is re
turned. js_newstringcopy(cx, s) is equivalent to js_newstringcopyn(cx, s, strlen(s)) when s is a null-terminated string. see also mxr id search for js_newstringcopyz mxr id search for js_newucstringcopyz js_getemptystringvalue js_newstringcopyn js_newucstringcopyn js_valuetostring ...
JS_Now
microseconds since the epoch, midnight, january 1, 1970 utc. syntax int64_t js_now(void); description js_now re
turns microseconds since the epoch, midnight, january 1, 1970 utc. see also mxr id search for js_now ...
JS_ObjectIsDate
which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * jsobject that should be checked. description js_objectisdate() can be used to check if you are dealing with a date object, or a date object used across compartments (or windows or sites, in the browser embedding). this function re
turns true if the object is a date. see also mxr id search for js_objectisdate js_newdateobject js_newdateobjectmsec bug 625870 ...
JS_ObjectIsFunction
bj jsobject * the object to test. this must not be null. description js_objectisfunction tests whether obj is a function object (faster than comparing obj's class name to function, but equivalent unless someone has overwritten the function identifier with a different constructor and then created instances using that constructor that might be passed in as obj). js_objectisfunction re
turns true if obj is a function and false otherwise. if js_objectisfunction re
turns true, js_valuetofunction will always re
turn non-null. js_objectisfunction always succeeds. note that the result may be false even for some callable objects, such as regular expression objects or proxy objects see also mxr id search for js_objectisfunction js_valuetofunction js_objectisfunction ...
JS_ObjectIsRegExp
n spidermonkey 17 determine if a specified object is a regexp. syntax bool js_objectisregexp(jscontext *cx, js::handleobject obj); name type description cx jscontext * a context. obj js::handleobject the object to examine. description js_objectisregexp determines if a specified object, obj, is a regexp object. if so, js_objectisregexp re
turns true. otherwise it re
turns false. see also mxr id search for js_objectisregexp js_newregexpobject js_newucregexpobject regexp bug 650931 ...
JS_ParseJSON
syntax jsbool js_parsejson(jscontext *cx, const jschar *chars, uint32 len, jsval *vp); jsbool js_parsejsonwithreviver(jscontext *cx, const jschar *chars, uint32 len, jsval reviver, jsval *vp); name type description cx jscontext * pointer to a js context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ch jsobject * the object to be searched. chars const jschar * the characters of the string. ...
JS_PopArguments
rmation. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. mark void * pointer to a void * which holds the stack frame pointer previously supplied by js_pusharguments. description js_poparguments frees the stack frame pointer previously allocated by js_pusharguments and unroots the jsvals which have been associated with it (those re
turned by js_pusharguments as well). see also js_pusharguments js_convertvalue js_addargumentformatter js_convertarguments bug 542091 ...
JS_PutEscapedString
ytes. str jsstring * or jsflatstring * a string to write into the file. quote char one of 0, single quote, and double quote. description js_putescapedstring and js_putescapedstring write str into buffer escaping any non-printable or non-ascii character using \escapes for js string literals. guarantees that a nul is at the end of the buffer unless size is 0. re
turns the length of the written output, not including the nul. thus, a re
turn value of size or more means that the output was truncated. if buffer is null, just re
turns the length of the output. if quote is not 0, it must be a single or double quote character that will quote the output. see also mxr id search for js_putescapedstring mxr id search for js_putescapedflatstring bug 609440 ...
JS_RemoveExternalStringFinalizer
owsers, its use is discouraged since it could be removed at any time. try to avoid using it. unregister a custom string memory manager. syntax int js_removeexternalstringfinalizer(jsstringfinalizeop finalizer); name type description finalizer jsstringfinalizeop the finalizer to remove. description remove finalizer from the global gc finalizers table, re
turning its type code if found, -1 if not found. as with js_addexternalstringfinalizer, there is a threading restriction if you compile the engine js_threadsafe: this function may be called for a given finalizer pointer on only one thread; different threads may call to remove distinct finalizers safely. you must ensure that all strings with finalizer's type have been collected before calling this fu...
JS_Remove*Root
rp void ** address of the pointer variable to remove from the root set. this must have been passed to either js_addgcthingroot or js_addnamedgcthingroot. description js_removeroot removes the variable that rp points to from the garbage collector's root set. the entry for rp is removed from the root set for the jsruntime associated with the context cx. js_removeroot always re
turns js_true. see also mxr id search for js_removevalueroot mxr id search for js_removestringroot mxr id search for js_removeobjectroot mxr id search for js_removegcthingroot bug 912581 ...
JS_RemoveRootRT
ngs that are protected from garbage collection. rp is thus a pointer to a pointer to a js double, string, or object. do not pass a pointer to a js double, string, or object -- you must pass a pointer to a pointer or a pointer to a jsval that's a gc thing. the entry for the gc thing rp points to is removed in the garbage collection hash table for the specified runtime, rt. js_removerootrt always re
turns js_true. see also mxr id search for js_removeroot jsval_is_gcthing js_addroot js_addnamedroot js_addnamedrootrt js_dumpnamedroots, js_removeroot ...
JS_ReportError
or reporting errors. first it builds an error message from the given sprintf-style format string and any additional arguments passed after it. the resulting error message is passed to the context's jserrorreporter callback, if any. if the caller is in a jsapi callback, js_reporterror also creates a new javascript error object and sets it to be the pending exception on cx. the callback must then re
turn js_false to cause the exception to be propagated to the calling script. an example is shown in the jsapi phrasebook. for internationalization, use js_reporterrornumber instead. to report an out-of-memory error, use js_reportoutofmemory. see also mxr id search for js_reporterror mxr id search for js_reportwarning ...
JS_ReportErrorNumber
signed the errornumber that was passed to the reporterrornumber api. description these functions create a jserrorreport, populate it with an error message obtained from the given jserrorcallback, and either report it to the current error reporter callback or create an error object and set it as the pending exception. first errorcallback(userref, errornumber) is called. if errorcallback re
turns null, (??? what happens?). otherwise, if the jserrorformatstring re
turned by the jserrorcallback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created. (??? the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnat...
JS_ReportPendingException
he context in which the exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description if an exception is pending in the context cx, js_reportpendingexception converts the exception to a string and reports it to the current error reporter. on success, it clears the exception as though by calling js_clearpendingexception and re
turns true. if no exception is pending, or if a second error occurs while trying to report the first one, it re
turns false. this function can be used to catch exceptions thrown from scripts and send them to the error reporter to be logged or ignored. note that certain jsapi functions automatically do this for uncaught exceptions; see "automatic handling of uncaught exceptions" in the jsapi user guide.
JS_ResolveStandardClass
ed if success. false otherwise. description js_resolvestandardclass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing true in *resolved. if id does not name a standard class or a top-level property induced by initializing a standard class, store false in *resolved and just re
turn true. re
turn false on error, as usual for bool result-typed api entry points. this api can be called directly from a global object class's resolve op, to define standard classes lazily. the class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in loops any classes not yet resolved lazily. see also mxr id search for js_resolvestandardclass js_e...
JS_SetArrayLength
o longer fit in the array are destroyed. setting the number of array elements does not initialize those elements. to initialize an element call js_defineelement. if you call js_setarraylength on an existing array, and length is less than the highest index number for previously defined elements, all elements greater than or equal to length are automatically deleted. on success, js_setarraylength re
turns true. otherwise it re
turns false. see also mxr id search for js_setarraylength js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement ...
JS_SetCheckObjectAccessCallback
t-access callback, which is used as the fallback jsclass.checkaccess method for all classes that leave the checkaccess field null. this callback is also used to check access to the caller property of function objects (as, for example, when the javascript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters. js_setcheckobjectaccesscallback re
turns the previous check-object-access callback. mxr id search for js_setcheckobjectaccesscallback ...
JS_SetElement
js::mutablehandlevalue in/out parameter. *vp is the value to assign to the element. js_setelement ordinarily leaves *vp unchanged, but a jsclass.addproperty hook or non-default setter may modify it. obsolete since jsapi 29 description js_setelement assigns a value to a numeric property of an object. it behaves like the javascript expression obj[index] = v. on success, js_setelement re
turns true. on error or exception, js_setelement re
turns false. obsolete since jsapi 29 on success, js_setelement re
turns true and the value left in *vp is left unchanged unless an addproperty hook or setter modified it. on error or exception, js_setelement re
turns false and the value left in *vp is unspecified. see also mxr id search for js_setelement bug 963167 - added v ...
JS_SetErrorReporter
ort jserrorreport * an error report record containing additional details about the error. description js_seterrorreporter enables you to define and use your own error reporting mechanism in your applications. the reporter you define is automatically passed a jserrorreport structure when an error occurs and has been parsed by js_reporterror. js_seterrorreporter js_geterrorreporter re
turns the value set by js_seterrorreporter. typically, the error reporting mechanism you define should log the error where appropriate (such as to a log file), and display an error to the user of your application. the error you log and display can make use of the information passed about the error condition in the jserrorreport structure. the error reporter callback must not reenter the jsapi. like ...
JS_SetInterruptCallback
t 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 re
turning false.) js_getinterruptcallback re
turns the currently installed interrupt callback, or null if none is currently installed. js_requestinterruptcallback requests a callback set using js_setinterruptcallback. see also mxr id search for js_setinterruptcallback mxr id search for js_getinterruptcallback mxr id search for js_requestinterruptcallback bug 977287 ...
JS_SetObjectPrincipalsFinder
cipalsfinder fop); name type description rt jsruntime * the runtime to configure. fop jsobjectprincipalsfinder the new object-principals-finder callback. description js_setobjectprincipalsfinder allows the application to set a callback that the javascript engine uses to obtain an object's principals. this callback is described in jsobjectprincipalsfinder. js_setobjectprincipalsfinder re
turns the previous object-principals-finder callback. mxr id search for js_setobjectprincipalsfinder ...
JS_SetParent
t__ property. in fact, once an object is exposed to a script, the object's parent must not change. the javascript engine relies on this invariant. js_setparent has no way to check that this is the case, but nonetheless, applications must not call js_setparent on an object that has already been exposed to a script. if an application does this, the behavior is undefined. on success, js_setparent re
turns js_true. otherwise, it reports an error or sets an exception and re
turns js_false. see also mxr id search for js_setparent bug 1136980 - removed ...
JS_SetPendingException
must be in a request on this jscontext. v js::handlevalue value to throw as an exception. description js_setpendingexception sets the current exception being thrown within a context. if an exception is already being thrown, it is replaced with the new one given. v is the new value to throw as an exception. a native function or hook using this to throw an exception must also re
turn false to ensure the exception is thrown. each jscontext's pending-exception field is a gc root. that is, garbage collection never collects a pending exception. see examples in the jsapi phrasebook. see also mxr id search for js_setpendingexception js_isexceptionpending js_getpendingexception js_clearpendingexception js_reportpendingexception ...
JS_SetPrincipalsTranscoder
jsprincipalstranscoder px); name type description rt jsruntime * the runtime to configure. px jsprincipalstranscoder the new principals transcoder. description js_setprincipalstranscoder sets a runtime-wide callback which the javascript engine uses to serialize and deserialize principals. this callback is described at jsprincipalstranscoder. js_setprincipalstranscoder re
turns the previous principals transcoder. mxr id search for js_setprincipalstranscoder ...
JS_SetProperty
y of obj. this is done as follows. if the property has a javascript setter, it is called; otherwise, if it has a javascript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). if the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. on success, js_setproperty re
turns true, and the value in v is left unchanged unless a hook or setter modified it. on error or exception, it re
turns false, and the value left in v is unspecified. internally, property assignment, including all the behavior described above, is implemented by obj's jsobjectops.setproperty callback. see also mxr id search for js_setproperty mxr id search for js_setucproperty mxr id search for ...
JS_SetPrototype
s that are shared by similar js object instances. ordinarily you set a prototype for an object when you create the object with js_newobject, but if you do not set a prototype at that time, you can later call js_setprototype to do so. obj is a pointer to an existing js object, and proto is a pointer to second existing object upon which the first object is to be based. on success, js_setprototype re
turns true. otherwise it re
turns false. take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite loop. to get an object's prototype, use js_getprototype. see also lxr id search js_getprototype ...
JS_SetRegExpInput
inter to a global object. input js::handlestring a pointer to the input string. multiline bool true if input is multiline. description js_setregexpinput sets the pending input string of the built-in regexp object to the specified input string. the jsreg_multiline is set to multiline parameter, and other flags are all reset. on successful, js_setregexpinput re
turns true, otherwise re
turns false. see also mxr id search for js_setregexpinput js_newregexpobject js_newucregexpobject jsreg_multiline js_clearregexpstatics regexp ...
JS_SetVersion
name type description cx jscontext * pointer to a js context from which to derive runtime information. version jsversion version of javascript to set context to. description js_setversion attempts to set the version of javascript to version for a specified executable script context, cx. the version comes from the jsversion enumerated type. js_setversion re
turns the js version in effect for the context before you changed it. see also mxr id search for js_setversion jsversion js_getversion js_versiontostring js_stringtoversion bug 880917 ...
JS_StrictlyEqual
must be in a request on this jscontext. v1, v2 js::handle<js::value> / jsval the value to compare. equal bool * out parameter. receives the comparison result. description js_strictlyequal determines if v1 is strictly equal to v2 under the javascript === operator, as specified in ecma 262-3 §11.9.6. if the comparison attempt was successful, the method re
turns true and stores the result in *equal; otherwise it re
turns false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent the same string or number. see also mxr id search for js_strictlyequal js_looselyequal js_samevalue bug 1132045 -- use handle ...
JS_StringEqualsAscii
g * string to compare. asciibytes const char * ascii string to compare with. match bool * (js_stringequalsascii only) out parameter. received the comparison result. description js_stringequalsascii and js_flatstringequalsascii compare string str and ascii string asciibytes. on successful, js_stringequalsascii stores the comparison result into *match and re
turns true, otherwise re
turns false. js_flatstringequalsascii always succeeds, and re
turns the comparison result. see also mxr id search for js_stringequalsascii mxr id search for js_flatstringequalsascii bug 609440 ...
JS_StringHasBeenInterned
this article covers features introduced in spidermonkey 17 determine if string is interned. syntax bool js_stringhasbeeninterned(jscontext *cx, jsstring *str); name type description str jsstring * a string to examine. description js_stringhasbeeninterned re
turns true if the string str is interned. see also mxr id search for js_stringhasbeeninterned bug 724810 ...
JS_StringHasLatin1Chars
this article covers features introduced in spidermonkey 38 determine if a string's characters are stored as latin1. syntax bool js_stringhaslatin1chars(jsstring *str); name type description str jsstring * string to examine. description js_stringhaslatin1chars re
turns true iff the string's characters are stored as latin1. string characters are stored as either latin1char (8-bit) or char16_t (16-bit). clients can use js_stringhaslatin1chars and can then call either the latin1* or twobyte* functions. some functions like js_copystringchars and js_getstringcharat accept both latin1 and twobyte strings. see also mxr id search for js_stringhaslatin1chars bug 1032726 ...
JS_StringIsFlat
this article covers features introduced in spidermonkey 38 determine if a string is flattened. syntax bool js_stringisflat(jsstring *str); name type description str jsstring * string to examine. description js_stringisflat re
turns true if the string is flattened. see also mxr id search for js_stringisflat bug 1037869 ...
JS_TypeOfValue
ofvalue(jscontext *cx, js::handle<js::value> v); name type description cx jscontext * the context in which to perform the type check. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handle<js::value> the value to examine. description js_typeofvalue examines a specified js value, v, and re
turns its js data type. the re
turn value is always one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. see also mxr id search for js_typeofvalue js_convertvalue js_gettypename js_valuetoboolean js_valuetofunction js_valuetoint32 js_valuetonumber js_valuetoobject js_valuetostring ...
JS_ValueToBoolean
t on this jscontext. v jsval the value to convert. bp jsbool * out parameter. on success, *bp receives the converted boolean value. description js_valuetoboolean converts a specified javascript value, v, to a boolean value. it implements the toboolean operator specified in ecma 262-3 §9.2. on success, js_valuetoboolean stores the converted value in *bp and re
turns js_true. on error or exception, it re
turns js_false, and the value left in *bp is undefined. for versions greater than jsversion_1_2, all objects convert to js_true, even boolean wrapper objects like the one produced by new boolean(false). this is the behavior specified in ecma 262-3 §9.2. see related discussion on google groups. see also mxr id search for js_valuetoboolean js::toboolean ...
JS_ValueToECMAInt32
valuetouint16 implements the touint16 operator specified in ecma 262-3 9.7. all three functions first convert v to a floating-point number as if by calling js_valuetonumber; nan values are then converted to zero. if that succeeds, the result is then converted to the target integer type. this second conversion cannot fail. on success, js_valuetoecmaint32 stores the converted value in *ip and re
turns js_true. on error or exception, it re
turns js_false, and the value left in *ip is undefined. see also js::touint16 js::toint32 js::touint32 js::toint64 js::touint64 js::tonumber bug 933810 bug 933946 ...
JS_ValueToId
nterned string jsid based on the value of v. if v is not a string, it is converted to a string as if by calling js_valuetostring. js_stringtoid and js_charstoid convert a specified string to a jsid. js_indextoid converts a specified integer index to an integer jsid. js::protokeytoid converts a specified prototype key to a jsid. on success, js_valuetoid stores the converted value in *idp and re
turns true. otherwise it re
turns false. the inverse of js_valuetoid is js_idtovalue. mxr id search for js_valuetoid see also mxr id search for js_idtovalue mxr id search for js_stringtoid mxr id search for js_indextoid mxr id search for js_charstoid mxr id search for js::protokeytoid js_valuetoid bug 698495 - added js_indextoid bug 830500 - added js_charstoid bug 959787 - added js_string...
JS_ValueToInt32
it signed integer (-2147483648 to 2147483647). first it converts v to a floating-point number as if by calling js::tonumber. if the result is nan, an infinity, or a number outside the 32-bit range, js_valuetoint32 reports an error and conversion fails. otherwise, the floating-point number is rounded to the nearest integer value. on success, js_valuetoint32 stores the converted value in *ip and re
turns js_true. on error or exception, it re
turns js_false, and the value left in *ip is undefined. js_valuetoint32 is pre-ecma-262 edition 1, and rounds differently than js_valuetoecmaint32 and js::toint32. this routine was added for layers-based graphics programming in netscape 4, but unless you know you need its rounding behavior, it is best to avoid it in favour of js::toint32. js::toint32 rounds ...
JS_ValueToObject
request on this jscontext. v js::handlevalue the value to convert. objp js::mutablehandleobject out parameter. on success, *objp receives null or a pointer to the resulting object. description js_valuetoobject converts a specified javascript value, v, to an object. on success, this function stores either null or a pointer to the resulting object in *objp and re
turns true. otherwise it re
turns false and the value left in *objp is unspecified. if v is jsval_null or jsval_void, the result is null. if v is a boolean value, a number, or a string, the result is a new wrapper object of type boolean, number, or string. otherwise v is an object, and the result depends on the object. if v is a native javascript object, this calls the object's valueof method, if a...
JS_ValueToSource
e type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handle<js::value> the value to convert. description js_valuetosource converts a specified javascript value, v, to a javascript source. on success, js_valuetosource re
turns a pointer to a string. on error or exception, it re
turns null. this happens, for example, if v is an object and v.tosource() throws an exception. see also bug 462910 ...
Stored value
tored value is the result of getting or setting the property, after the getter or setter, if any, is called. js_defineproperty allows the application to specify a property's initial stored value. js_lookupproperty fetches a property's stored value without triggering its getter. properties with the jsprop_shared attribute do not have a stored value. es5 accessor properties, as in {get length() { re
turn 0; }, automatically have jsprop_shared. properties of objects that have custom jsobjectops do not have a stored value. stored values are strong references for the purpose of garbage collection. as long as an object is reachable, the stored values of its properties are reachable and will not be collected. ...
jsid
teger, interned string or object. a few jsapi functions use jsids instead of js::values for property names: js_nextproperty, js_enumerate, and all functions with names ending in byid. also, there is an additional jsid value, jsid_void, which does not occur in js scripts but may be used to indicate the absence of a valid jsid. a void jsid is not a valid id and only arises as an exceptional api re
turn value, such as in js_nextproperty. embeddings must not pass jsid_void into jsapi entry points expecting a jsid and do not need to handle jsid_void in hooks receiving a jsid except when explicitly noted in the api contract. a jsid is not implicitly convertible to or from a jsval; js_valuetoid or js_idtovalue must be used instead. ...
JSDBGAPI
_frameiterator js_getframescript js_getframepc js_getscriptedcaller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframecallobject js_getframethis js_getframefunction js_getframefunctionobject js_isconstructorframe js_isdebuggerframe js_getframere
turnvalue js_setframere
turnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe examining object properties typedef jspro...
SpiderMonkey 1.8.7
rlying functions to retrieve the characters in the string failed. additionally, js_newstring, js_getstringbytes, and js_getstringchars were removed, replaced by fallible interfaces like js_getstringcharszandlength and js_encodestringtobuffer (not an exhaustive list). numbers spidermonkey 1.8.5 now stores integers up to 32-bits in the jsval. this means that the int_fits_in_jsval macro is always re
turns true (be careful to only use this macro with jsints, not 64-bit integers). the jsval now also stores jsdoubles directly, rather than storing them on the heap. the jsval_to_double and double_to_jsval macros have been updated to work directly on jsdoubles rather than their pointers, and the js_newdoublevalue and js_newdouble interfaces have been removed. javascript shell changes there are many ne...
SpiderMonkey 38
stub (bug 1103152) js_setfinalizecallback (bug 996785) js_setfunctioncallback (bug 1103269) jschar (bug 1063962) api changes jschar, a typedef for the standard c++ type char16_t, has been removed. jsapi functions that used jschar now use char16_t directly. embedder code should use char16_t, too. (see bug 1063962.) js_preventextensions now indicates its success or failure in two ways: via re
turn value (as with most jsapi methods), and via outparam (indicating whether the attempt took effect or not, independent of jsapi failure). this change better aligns with ecmascript's [[preventextensions]] hook, which generally re
turns true or false to indicate whether subsequent attempts to add a new property will fail, yet also itself may throw in some cases. javascript shell changes detail adde...
Running Automated JavaScript Tests
es. or you can run all but selected tests with the --exclude option. now that the full set of test262 tests is included in the tree, jstests take a long time to complete. for a smoke test or if you are not changing language-level functionality, you may wish to use jstests.py path_to_js_shell --exclude=test262 other options allow you to show the test command lines being run, command output and re
turn codes, run tests named in a given file, exclude tests named in a given file, hide the progress bar, change the timeout, run skipped tests, print output in tinderbox format, run a test in the debugger, or run tests in valgrind. run with the -h option to see all the options. the jstests test suite also includes some tests from web-platform-tests. by default, these are only run when no tests paths ...
SavedFrame
ated. if the frame responsible for the call is not accessible to the caller, this points to the youngest accessible ancestor of the real frame, if any. in all other cases, this is null. parent this stack frame’s caller, or null if this is the oldest frame on the stack. in this case, there might be an asyncparent instead. function properties of the savedframe.prototype object tostring re
turn this frame and its parents formatted as a human readable stack trace string. source metadata generated from file: js/src/doc/savedframe/savedframe.md watermark: sha256:3475238d6704c659cb3e411b9c601d6ee836762dea14203f1f00ecf2c3b32452 changeset: 251fccc1f62b ...
Retrieving part of the bookmarks tree
der; the placesroot is the root folder in the whole places hierarchy. it contains administrative data as well as user data, and is therefore not recommended for use in querying. configure the query to get a hierarchical bookmarks result, pass the folder id to setfolders in your query object: query.setfolders([toolbarfolder], 1); run the query the executequery and executequeries functions will re
turn an nsinavhistoryresult object containing the results of your query: var result = historyservice.executequery(query, options); get the results when you are querying for exactly one folder grouped by folder with no fancy query parameters such as keywords or date ranges (as in this example), the root of the result will be an nsinavhistorycontainerresultnode corresponding to your folder. if you have...
Using the Places livemark service
(livemarkservice.islivemark(folderid)) { // it's a livemark } else { // it's not a livemark } accessing the container's site uri the nsilivemarkservice.getsiteuri() method lets you obtain the nsiuri of the website associated with a livemark container. var siteuri = livemarkservice.getsiteuri(newlvmkid); //newlvmkid = see "create a new livemark" for more detail. getsiteuri() re
turns null if there is no uri for the specified livemark. nsilivemarkservice.setsiteuri() sets the uri of the website associated with a livemark container. livemarkservice.setsiteuri(newlvmkid, uri("http://newuri.com/"); //newlvmkid = see "create a new livemark" for more detail. accessing a livemark's feed uri nsilivemarkservice.getfeeduri() gets the uri of the syndication feed assoc...
Using the Places tagging service
ri nsitaggingservice.untaguri() removes tags from a url. from the given set of tags, a tag is ignored if it isn't set for the given url. tagginsvc.untaguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) finding all urls with a given tag the nsitaggingservice.geturisfortag() method re
turns an array of all urls tagged with the given tag. var tag1uris = taggingsvc.geturisfortag("tag 1"); //"tag 1" = given tag getting all tags associated with a url the nsitaggingservice.gettagsforuri() method re
turns an array of all tags set for the given url. var tags = taggingsvc.gettagsforuri(uri("http://example.com/", {})); //tags = an array of tags stored in http://example.com/ see also...
places.sqlite Database Troubleshooting
org/download.html extract sqlite3 executable into the work folder. open a terminal window and navigate to the work folder. then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> pragma integrity_check; if the result is ok, this guide won't help; stop here and please file a bug. sqlite> .clone places.sqlite sqlite> pragma user_version; note the version number re
turned by the last pragma query. sqlite> .exit open a new shell for the new database: my_work_folder> sqlite3 places.sqlite sqlite> pragma integrity_check; if the result is not ok, the file cannot be recovered; stop here and please file a bug. let's fix the schema version. nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_si...
The Publicity Stream API
ude: denied - if the user does not log in correctly permissiondenied - if the site is not allowed to access the publicity stream networkerror - if the publicity server is unreachable for_apps is a json list of apps that this store has (each represented as its origin url), so that stream events not relating to applications in a given presentation context can be excluded from the re
turn value. if null or an empty list is passed, events for all apps are re
turned. since the timestamp of the earliest event you want re
turned. if not specified, will default to the beginning of the stream. before the timestamp of the latest event you want re
turned. if not specified, will default to now. count the maximum number of events to re
turn, with preference given to more recent events [ma...
Building the WebLock UI
of the structure of the mozilla user interface, into which it may be possible to install both the weblock component and the user interface described in this chapter. note, however, that currently weblock probably does not install cleanly in mozilla firefox due to firefox's newness compared to this book (which was originally written in 2003). « previousnext » copyright (c) 2003 by doug
turner and ian oeschger. this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
Packaging WebLock
se for the reader. note: install-object-methods the methods are available on the main install object, which is implied in the script below in the same way that the window object is implied in javascript manipulation of the dom of a web page. in other words, the fragment initinstall() from the script is equivalent to install.initinstall(). « previousnext » copyright (c) 2003 by doug
turner and ian oeschger. this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
Preface
ey are described in detail. link references to other sections and to figures and tables are links to those sections. acknowledgements thanks to peter lubczynski, john gaunt, ellen evans, and alec flett for technical reviews. a special thanks goes to darin fisher for his very acute observations, close reading, and attention to detail. next » copyright (c) 2003 by doug
turner and ian oeschger. this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
Resources
this material may be distributed only subject to the terms and conditions set forth in the open publication license, v1.02 or later. distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prio...
XPCOM hashtable guide
able<nsstringhashkey> hashtable api the hashtable classes all expose the same basic api. there are three key methods, get, put, and remove, which retrieve entries from the hashtable, write entries into the hashtable, and remove entries from the hashtable respectively. the hashtables that hold references to pointers (nsrefptrhashtable and nsinterfacehashtable) also have getweak methods that re
turn non-addrefed pointers. all of these hashtable classes can be iterated over via the iterator class and cleared via the clear method. ...
Receiving startup notifications
er case, there's no need to additionally register for the startup notifications. simply registering with the category manager is enough. what happens next once you've registered with the category manager, at mozilla startup time (or when the embedding application's ns_initembedding() function is called), the appstartupnotifier component is instantiated, and its observe() method is called; this in
turn enumerates all components in the app-startup category and sends them the appropriate notifications. ...
Components.interfaces
reateinstance() when called from javascript, and nsiclassinfo.getinterfaces(). the properties of the components.interfaces object can be enumerated using a for...in loop. usage accessing an interface object properties of the components.interfaces object are indexed by interface name. you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will re
turn you the interface object for the nsisupportsarray interface. accessing constants defined in an interface interface descriptions (cf. xpidl) may not only contain method declarations, but also constants. for example, assume we have the following interface declaration: interface nsifoo : nsisupports { const pruint32 myflag = 5; }; the constant myflag can then be accessed using var myflag = c...
Components.utils.Sandbox
urity principals. system principal to specify the system principal, you can create it using code like: cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); content principal you can specify a content principal for a particular origin in one of three ways: as an nsiprincipal, for example by using the nodeprincipal property of a dom node as an nsidomwindow, such as that re
turned by the dom window property as a string uri like "http://www.example.com/" (discouraged) when possible, specify a window or an nsiprincipal object instead of using a string uri. window objects and nsiprincipal carry additional information such as origin attributes and same-origin privilege changes caused by setting document.domain. example of obtaining content principal from the window: var...
Components.utils.evalInSandbox
n the constructor you define the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox. the sandbox will become the global scope object when you pass it to evalinsandbox(text, sandbox). you can import functions or objects into the sandbox simply by assigning them to the sandbox object. for example: function double(n) { re
turn n * 2; } // create new sandbox instance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope. mysandbox.double = double; var result = components.utils.evalinsandbox("x = y + 2; double(x) + 3", mysandbox); console.log(result); // 17 console.log(mysandbox.x); // 7 operations on object...
Components.utils.importGlobalProperties
s not support the targeted firefox version, here are some alternative methods to import these objects. import from jsm this method worked until blob and file were no longer apart of jsm modules. it is suspected this works up till firefox 35. this imports blob, file, along with the regular services. the reason this works is because js code modules actually have blob and file. cu.import() will re
turn the full global of a code module. knowing that, we can just get a valid blob by importing a known module that has the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow the hidden domwindow has all of these objects automatically imported. the downside of using...
Components.utils.isXrayWrapper
r example, privileged code using an xray to a dom object sees only the original, native version of the dom object. any expando properties are not visible, and if any native properties have been redefined, this has no effect. use this function to determine whether a given object is an xray or not. syntax boolean components.utils.isxraywrapper(obj); parameters obj the object to check. re
turns true if the object is an xray: false otherwise. example var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false ...
Components.utils.reportError
it is meant for use by extension developers who have exception handler blocks which want to "eat" an exception, but still want to report it to the console. it must be called with one parameter, usually an object which was caught by an exception handler. if it is not a javascript error object, the parameter is converted to a string and reported as a new error. this means you can use components.utils.reporterror to report debugging messages to the error console, just like dump() can be used to print messages to the native console. ...
Components.utils.unwaiveXrays
for the object. the waivexrays operation is transitive: it waives xrays not just for the given object, but for all properties of the object (and their properties, and so on). the unwaivexrays operation undoes the operation, so xray vision is restored transitively as well. syntax xray = components.utils.unwaivexrays(obj); parameters obj the object for which we wish to restore xrays. re
turns the object with xrays restored. example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection. the chrome code can then use unwaivexrays to restore xray protection: // chrome code // contentwindow is an xray var ...
XPConnect wrappers
cwrappedjs code into your javascript implementation. these wrappers are created by xpconnect, so you should not have to worry about how to construct them or whether to construct them. double wrapping. there is one case where an xpcwrappednative wraps another wrapper object. this case is where a js object was passed in via some idl-declared interface, creating an xpcwrappedjs, and is now being re
turned to javascript via some other interface. in order to preserve api compatibility, an xpcwrappednative is created around the xpcwrappedjs. security wrappers exposed to chrome to learn about security wrappers, see the article on script security in gecko. note that a previous version of the current page recommended using __exposedprops__ to expose objects from chrome to content. this is now depre...
nsLocalFile
2e23e220-60be-11d3-8c4a-000064657374 contractid @mozilla.org/file/local;1 supported interfaces nsilocalfile, nsifile remarks this component should be accessed via the xpcom component manager. example code function getfilesize(path) { var file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath(path); re
turn file.filesize; } see also components, nsicomponentmanager ...
Standard XPCOM components
there are a number of components provided in the standard implementation of xpcom; these are as follows. nscategorymanagerthe xpcom category manager.nsdirectoryservicethe xpcom directory service. this service re
turns the locations of "well known" directories in an os-independent manner. for instance, it can give you the path of the system's temporary directory, desktop directory, current working directory, and so on.nslocalfilea component implementing nsilocalfile. nsobserverservicethe xpcom observer service.nsscriptableinputstreama component implementing nsiscriptableinputstream. ...
NS_Alloc
« xpcom api reference summary infallibly allocates a block of memory using the xpcom memory manager. #include "nsxpcom.h" void* ns_alloc( prsize asize ); parameters asize [in] the size in bytes of the block to allocate. re
turn values this function re
turns a pointer to the allocated block of memory, which is suitably aligned for any kind of variable, or null if the allocation failed. remarks this function provides a convenient way to access the xpcom memory manager. it is equivalent to calling alloc on the nsimemory instance re
turned from ns_getmemorymanager. history this function was finalized for mozilla 1.8. see bug 267767 for details. see also ns_free, nsimemory, ns_getmemorymanager ...
NS_Free
« xpcom api reference summary frees a block of memory using the xpcom memory manager. #include "nsxpcom.h" void ns_free( void* aptr ); parameters aptr [in] a pointer to the block of memory to free. remarks this function provides a convenient way to access the xpcom memory manager. it is equivalent to calling free on the nsimemory instance re
turned from ns_getmemorymanager. history this function was finalized for mozilla 1.8. see bug 267767 for details. see also ns_alloc, nsimemory, ns_getmemorymanager ...
NS_Realloc
sxpcom.h" void* ns_realloc( void* aptr, prsize asize ); parameters aptr [in] a pointer to the block of memory to reallocate. this pointer must have been previously allocated by the xpcom memory manager, or this parameter may be null in which case this function behaves like ns_alloc. asize [in] the size in bytes of the block to allocate, or zero if the given block is to be freed. re
turn values this function re
turns a pointer to the allocated block of memory, which is suitably aligned for any kind of variable, or null if the allocation failed. remarks this function provides a convenient way to access the xpcom memory manager. it is equivalent to calling realloc on the nsimemory instance re
turned from ns_getmemorymanager. history this function was finalized for mozilla 1.8.
NS_ShutdownXPCOM
« xpcom api reference summary the ns_shutdownxpcom function terminates use of xpcom in the calling process. #include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was re
turned by ns_initxpcom2 (or ns_initxpcom3) or null. re
turn values the ns_shutdownxpcom function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to re
turn object instances. history this function was finalized for mozilla 0.9.6. see bug bu...
Length
size_type length() const; ...
operator=
« xpcom api reference summary this operator is a shortcut for the assign family of functions. self_type& operator=( const self_type& astring ); parameters astring [in] a nsacstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also ...
operator+=
« xpcom api reference summary this operator+= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsacstring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator+=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. se...
nsACString
clude "nsstringapi.h" class nsacstring { ... }; typedefs char_type [char] storage unit for this class. self_type [nsacstring] an alias for the type of this class. size_type [pruint32] type used to represent the number of bytes stored in the string. index_type [pruint32] type used to represent an offset into the string. methods beginreading the beginreading function re
turns a const pointer to the first element of the string's internal buffer. endreading the endreading function re
turns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function re
turns the number of storage units in the string's internal buffer (not including the null-terminator if present). assign the assign family...
Length
size_type length() const; ...
operator=
« xpcom api reference summary this operator= is a shortcut for the append family of functions. self_type& operator+=( const self_type& astring ); parameters astring [in] a nsastring to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. self_type& operator=( char_type achar ); parameters achar [in] a character to append to this string. re
turn values this operator re
turns a reference back to the object being modified to allow operator chaining. see also...
nsAString
sastring { ... }; typedefs char_type [prunichar] storage unit for this class. self_type [nsastring] an alias for the type of this class. size_type [pruint32] type used to represent the number of double-byte units stored in the string. index_type [pruint32] type used to represent an offset into the string. methods beginreading the beginreading function re
turns a const pointer to the first element of the string's internal buffer. endreading the endreading function re
turns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function re
turns the number of storage units in the string's internal buffer (not including the null-terminator if present). assign the assi...
get
« xpcom api reference summary the get function re
turns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code nsembedcstring str("hello world"); printf("%s\n", str.get()); ...
nsEmbedCString
ct a nsacstring object that allocates null-terminated storage. #include "nsembedstring.h" class nsembedcstring : public nsacstring { ... }; typedefs self_type [nsembedcstring] an alias for the type of this class. abstract_string_type [nsacstring] an alias for the abstract string type this class specializes. methods nsembedcstring constructors for nsembedcstring. get the get function re
turns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsacstring::assign family of functions. remarks the methods defined on nsembedcstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_cstring. see, for example, ns_cstringcontainerinit. see also ns_cstringcontainerinit, nsa...
get
« xpcom api reference summary the get function re
turns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code void getbar(nsastring &result); void func() { nsembedstring str; getbar(str); const prunichar *data = str.get(); ... } ...
nsEmbedString
-terminated storage. #include "nsembedstring.h" // or: #include "nsstringglue.h" if inside gecko class nsembedstring : public nsastring { ... }; typedefs self_type [nsembedstring] an alias for the type of this class. abstract_string_type [nsastring] an alias for the abstract string type this class specializes. methods nsembedstring constructors for nsembedstring. get the get function re
turns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsastring::assign family of functions. remarks the methods defined on nsembedstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_string. see, for example, ns_stringcontainerinit. see also ns_stringcontainerinit, nsastring...
Alloc
« xpcom api reference summary the alloc function allocates a block of memory of a particular size. static void* alloc( size_t asize ); parameters asize [in] specifies the size in bytes of the block of memory to allocate. re
turn values this function is infallible, therefore guaranteed to re
turn a pointer to the newly allocated buffer. the result must be freed with a call to nsmemory::free() when it is no longer needed. note: prior to gecko 13.0, this function re
turned nsnull if memory allocation failed. see also nsmemory::free() ...
Clone
reference summary the clone function creates a copy of an existing memory block up to the size specified. static void* clone( const void* aptr, size_t asize ); parameters aptr [in] the address of the memory block to copy. this must be non-null. asize [in] specifies the new size in bytes of the block of memory to allocate. the buffer at aptr must be at least asize bytes in length. re
turn values this function re
turns nsnull if the memory allocation fails. otherwise, it re
turns a pointer to the newly allocated buffer. the result must be freed with a call to nsmemory::free when it is no longer needed. see also nsmemory::free ...
GetGlobalMemoryService
« xpcom api reference summary the getglobalmemoryservice function re
turns a reference to xpcom's global nsimemory object. static nsimemory* getglobalmemoryservice(); re
turn values this function re
turns nsnull if the global memory manager does not exist or could not be initialized. remarks this function re
turns the same value as the ns_getmemorymanager function. see also ns_getmemorymanager ...
HeapMinimize
« xpcom api reference summary the heapminimize function attempts to shrink the size of the heap. static nsresult heapminimize( prbool aimmediate ); parameters aimmediate [in] if true, heap minimization will occur immediately if the call was made on the main thread. if false, the flush will be scheduled to happen when the app is idle. re
turn values this function re
turn ns_ok if successful. otherwise, it re
turns an error code. ...
Realloc
tion reallocates a block of memory to a new size. static void* realloc( void* aptr, size_t asize ); parameters aptr [in] the address of the memory block to reallocate. this may be nsnull, in which case realloc behaves like nsmemory::alloc. asize [in] specifies the new size in bytes of the block of memory to allocate. this may be 0, in which case realloc behaves like nsmemory::free. re
turn values this function re
turns nsnull if the memory allocation fails. otherwise, it re
turns a pointer to the newly allocated buffer. the result must be freed with a call to nsmemory::free when it is no longer needed. remarks if aptr is non-null, then its contents will be unchanged to the minimum of the old and new sizes. newly allocated memory is uninitialized. see also nsmemory::free ...
nsMemory
to a new size. free the free function frees a block of memory that was allocated by xpcom's memory manager. heapminimize the heapminimize function attempts to shrink the size of the heap. clone the clone function creates a copy of an existing memory block up to the size specified. getglobalmemoryservice the getglobalmemoryservice function re
turns a reference to xpcom's global nsimemory object. remarks to use the methods in this class, you must link your component or application against the xpcom glue library. the static methods defined on this class are not frozen. however, if you use these functions in your xpcom component, and if you link to the xpcom glue library, then your component will only have a runtime dependency on the frozen ...
IJSDebugger
only time you should directly use this interface to create the debugger object is if you need to debug chrome; due to bug 707237, the javascript code module doesn't work in that case. see the javascript debugger api guide for details on using the debugger api. method overview [implicit_jscontext] void addclass(); methods addclass() defines the global debugger constructor. on re
turn, the debugger object has been added to the global context. [implicit_jscontext] void addclass(); parameters none. see also js debugger api reference js debugger api guide ...
imgIDecoder
r (if any). if this method was provided as an external facility, a separate char * buffer would need to be used in order to call the output stream's other write() method. unsigned long writefrom( in nsiinputstream instr, in unsigned long count ); parameters instr the stream from which to read the encoded image data. count the maximum number of bytes to write to the image. re
turn value the number of bytes actually written to the image, or undefined if an error occurred. see also imgidecoderobserver imgiload ...
imgIDecoderObserver
ver, they can be interleaved in various ways. in general, any presumed ordering between load and decode notifications should not be relied upon. decode notifications may or may not be synchronous, depending on the situation. if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call re
turns. if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call re
turns. method overview void ondataavailable(in imgirequest arequest, in boolean acurrentframe, [const] in nsintrect arect); native code only! void ondiscard(in imgirequest arequest); void onimageisanimated(in imgirequest arequest); void onstartcontainer(in ...
mozIJSSubScriptLoader
sible. the loaded script is executed with the principal associated with the target object. any top-level functions or variables created by the loaded script via var are created as properties of the targetobj target object (but things declared via let and const are not). additionally, properties of the targetobj target object can be referred to as variables in the loaded script. if the script re
turns a value, it will be re
turned by this method. note: this method must only be called from javascript! jsval loadsubscript( in string url, in object targetobj optional, in string charset optional, ); example let context = {}; services.scriptloader.loadsubscript("chrome://my-package/content/foo-script.js", context, "utf-8" /* the script's encoding */)...
mozIPersonalDictionary
tionary. void addword( in wstring word, in wstring lang ); parameters word the word to add to the dictionary. lang the language of the word. note that this parameter is currently unused. check() checks a unicode string. boolean check( in wstring word, in wstring lang ); parameters word the word to check. lang the language of the word. note that this parameter is currently ignored. re
turn value true if the word is in either the dictionary or the ignore list, false if it is not in either list. endsession() clears the ignore list. void endsession(); parameters none. getcorrection() gets a list of previous corrections for the word. void getcorrection( in wstring word, [array, size_is(count)] out wstring words, out pruint32 count ); parameters word the word to get the list of...
mozIRegistry
implementation of these components in this document. lastly, there's one component (labelled "mozrdfregistry/nsirdfdatabase") that potentially will emerge as an improved implementation of one of the moziregistry interfaces. i'll be discussing that implementation only briefly (mainly because i'm hoping i can pawn off the chore of implementing it to somebody else). there's another component that
turns out to also be real important when you go to hook up your code with other mozilla components. that's the service manager. i'm just starting to understand the role it plays in this and it isn't really under my jurisdiction, so there's nothing about it here right now. in the future, i'll either add the information about it or at least put in a link to it's documentation. higher-level applicatio...
mozIStorageBindingParamsArray
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 re
turns a new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding. mozistoragebindingparams newbindingparams(); parameters none. ...
mozIStorageError
storage/public/mozistorageerror.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports attributes attribute type description message autf8string a human readable error string with details; this may be null if no details are available. read only. result long one of the error code values listed under constants on this page. ...
mozIStoragePendingStatement
ko 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. re
turn value in versions of gecko prior to gecko 1.9.2, this re
turned a boolean value that was true if the query was canceled successfully or false if not. starting with gecko 1.9.2, this information is no longer provided and the method doesn't re
turn a value. see also storage mozistorageconnection mozistoragestatement ...
mozIStorageProgressHandler
methods onprogress() the onprogress() method is called periodically while an sqlite operation is ongoing. this allows you to monitor the progress and possibly display status information to the user. boolean onprogress( in mozistorageconnection aconnection ); parameters <tt>aconnection</tt> a mozistorageconnection connection indicating the connection for which the callback was invoked. re
turn value re
turn true to abort the request or false to allow it to continue. see also storage mozstorage introduction and how-to article mozistorageconnection database connection to a specific file or in-memory data storage mozistoragestatement create and execute sql statements on a sqlite database. mozistoragevaluearray wraps an array of sql values, such as a result row. mozistoragefunction crea...
mozIStorageResultSet
the mozistorageresultset interface represents a set of results from a storage statement. storage/public/mozistorageresultset.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview mozistoragerow getnextrow(); methods getnextrow() re
turns the next row from the result set. mozistoragerow getnextrow(); parameters none. re
turn value a mozistoragerow object containing the next row from the result set, or null if there are no more results. see also storage mozistorageconnection mozistoragestatement ...
mozIStorageStatementWrapper
e call notation on this. methods initialize() this method initializes this wrapper with astatement. void initialize( in mozistoragestatement astatement ); parameters astatement the statement to be initialized. reset() this method resets the wrapped statement. void reset(); parameters none. step() this method steps the wrapped statement. boolean step(); parameters none. re
turn value re
turns true if the stepping the wrapped statement was successful, otherwise re
turns false. execute() this method executes the wrapped statement. void execute(); parameters none. see also storage mozistoragestatement mozistoragestatementrow mozistoragestatementparams ...
mozIStorageVacuumParticipant
will try to restore wal mode, but this will only work reliably if the participant properly resets statements. if the attempt to restore the journal node fails, it will remain truncate. methods onbeginvacuum() called when a vacuum operation begins. once you receive this notification, you should avoid using the database until onendvacuum() is called. boolean onbeginvacuum(); parameters none. re
turn value re
turn true to allow the vacuum operation to proceed, or false if you don't want the database to be vacuumed. you may wish to re
turn false, for example, if you're in the middle of an operation that you don't want to (or can't) interrupt. onendvacuum() called when a vacuum operation ends. void onendvacuum( in boolean asucceeded ); parameters asucceeded true if the vacuum operation was su...
nsIAboutModule
g that indicates whether this about: uri doesn't want to be listed in about:about, especially if it's not useful without a query string. methods geturiflags() a method to get the flags that apply to a given about: uri. the uri passed in is guaranteed to be one of the uris that this module registered to deal with. unsigned long geturiflags( in nsiuri auri ); parameters auri re
turn value a combination of the flags above corresponding to the appropriate flags for this about uri. newchannel() constructs a new channel for the about protocol module. nsichannel newchannel( in nsiuri auri ); parameters auri the uri of the new channel. re
turn value a fully constructed channel that will load the about uri. see also on this page is seen how to make a custom about page.
FirstChild
attribute nsiaccessible firstchild; exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
GetAccessibleAbove
« nsiaccessible page summary this method re
turns an accessible node geometrically above this one. nsiaccessible getaccessibleabove(); re
turn value re
turns an accessible node geometrically above this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessiblebelow() ...
GetAccessibleBelow
« nsiaccessible page summary this method re
turns an accessible node geometrically below this one. nsiaccessible getaccessiblebelow(); re
turn value re
turns an accessible node geometrically below this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessibleabove() ...
GetAccessibleRelated
« nsiaccessible page summary this method re
turns an accessible related to this one by the given relation type. nsiaccessible getaccessiblerelated( in unsigned long arelationtype ); parameters arelationtype[in] the relation type between the accessible (see constants listed in relations documentation). re
turn value re
turns an accessible which is related to the one provided by the given relation type. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.ns_error_not_implemented indicates that the given relation type is unsupported see also nsiaccessible.getrelations() nsiaccessible.relationscount nsiaccessible.getrelation() ...
GetAccessibleToLeft
« nsiaccessible page summary this method re
turns an accessible node geometrically to the left of this one. nsiaccessible getaccessibletoleft(); re
turn value re
turns an accessible node geometrically to the left of this one. see also nsiaccessible.getaccessibletoright() nsiaccessible.getaccessibleabove() nsiaccessible.getaccessiblebelow() ...
GetAccessibleToRight
« nsiaccessible page summary this method re
turns an accessible node geometrically to the right of this one. nsiaccessible getaccessibletoright(); re
turn value re
turns an accessible node geometrically to the right of this one. see also nsiaccessible.getaccessibletoleft() nsiaccessible.getaccessibleabove() nsiaccessible.getaccessiblebelow() ...
GetActionDescription
« nsiaccessible page summary this method retrieves the description (localized name) of the accessible action at the given zero-based index. astring getactiondescription( in pruint8 aindex ); parameters aindex[in] the zero-based index. re
turn value re
turns the description of the accessible action. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ns_error_invalid_arg indicates that the given index is our of range. see also nsiaccessible.numactions nsiaccessible.getactionname() nsiaccessible.doaction() ...
GetActionName
« nsiaccessible page summary this method retrieves the name of the accessible action at the given zero-based index. astring getactionname( in pruint8 aindex ); parameters aindex[in] the zero-based index. re
turn value re
turns the name of the accessible action. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree.ns_error_invalid_arg indicates that the given index is our of range. see also nsiaccessible.numactions nsiaccessible.getactiondescription() nsiaccessible.doaction() ...
GetBounds
void getbounds( out long ax, out long ay, out long awidth, out long aheight ) parameters ax[out] accessible's x-coordinate. ay[out] accessible's y-coordinate. awidth[out] accessible's width. ...
GetChildAtPoint
« nsiaccessible page summary this method re
turns an accessible child which contains the coordinate at (x, y) in screen pixels. nsiaccessible getchildatpoint( in long ax, in long ay ); parameters ax[in] accessible's x-coordinate.ay[out] accessible's y-coordinate. re
turn value re
turns an accessible child at given (x, y) coordinate. remarks if the point is in the current accessible but not in a child, the current accessible will be re
turned. if the point is in neither the current accessible or a child, then null will be re
turned. ...
GetKeyBindings
« nsiaccessible page summary this method provides array of localized string of global keyboard accelerator for the given action index supported by accessible. nsidomdomstringlist getkeybindings( in pruint8 aactionindex ); parameters aactionindex[in] index of the given action. re
turn values re
turns array of localized string of global keyboard accelerator. exceptions thrown ns_error_invalid_arg the given index doesn't correspond to default action (not zero). remark key bindings are supported for default action only. see also nsiaccessible.defaultkeybinding nsiaccessible.keyboardshortcut ...
GetRelations
« nsiaccessible page summary this method re
turns multiple accessible relations for this accessible object. nsiarray getrelations(); re
turn value re
turns nsiarray array of accessible relations for this object, every accessible relation object implements nsiaccessiblerelation interface. see also nsiaccessible.getaccessiblerelation() nsiaccessible.relationscount nsiaccessible.getrelation() ...
GroupPosition
used for tree items, list items, tab panel labels, radio buttons, etc. also used for collectons of non-text objects. void groupposition( out long agrouplevel, out long asimilaritemsingroup, out long apositioningroup ); parameters agrouplevel 1-based, similar to aria aria-level property asimilaritemsingroup 1-based, similar to aria aria-setsize property, inclusive of the current item. apositioningroup 1-based, similar to aria aria-posinset property. remark alternatively this information is exposed by nsiaccessible.attribute attribute, also see group attributes page. ...
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() re
turns successfully. they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() re
turns. 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 nsisup...
nsIBadCertListener2
ommunication context that can be used to obtain more information about the active connection. this object usually supports nsisslsocketcontrol, nsitransportsecurityinfo, nsiidentityinfo, nsisslstatusprovider, nsiclientauthuserdecision and possibly other interfaces. status the ssl status object that describes the problem(s). targetsite the site name that was used to open the current connection. re
turn value the consumer shall re
turn true if it wants to suppress the error message related to the bad cert (the connection will still get canceled). see also nsisockettransport ...
nsIBidiKeyboard
d right-to-left) installed. read only. note: this throws ns_error_not_implemented if the widget layer doesn't provide this information. currently, this is only implemented on windows. methods islangrtl() determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to re
turn the value. boolean islangrtl(); parameters none. re
turn value true if the current keyboard is right-to-left, false if it is not. exceptions thrown ns_error_failure if no right-to-left keyboards are installed. setlangfrombidilevel() sets the keyboard language to left-to-right or right-to-left. (supported on: win32) void setlangfrombidilevel( in pruint8 alevel ); parameters aleve...
nsIBrowserHistory
te since gecko 9.0 note: the markpageasfollowedlink and markpageastyped methods were moved to nsinavhistoryservice in gecko 22.0 so that all markpageas* methods can be found in one interface. attributes attribute type description count obsolete since gecko 15.0 pruint32 indicates if there are entries in global history. for performance reasons this does not re
turn the real number of entries. read only. lastpagevisited obsolete since gecko 10.0 autf8string the last page that was visited in a top-level window. read only. note: the 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 ...
nsICacheEntryInfo
ntifying the cache entry. read only. lastfetched pruint32 get the last time the cache entry was opened (in seconds since the epoch). read only. lastmodified pruint32 get the last time the cache entry was modified (in seconds since the epoch). read only. methods isstreambased() this method finds out whether or not the cache entry is stream based. boolean isstreambased(); parameters none. re
turn value re
turns true if the cache entry is stream based, otherwise re
turns false. see also nsicache nsicachevisitor ...
nsIChannelEventSink
pened. it is important to understand that oldchannel will continue loading as if it received a response of http 200, which includes notifying observers and possibly display or process content attached to the http response. if the sink wants to prevent this loading it must explicitly deal with it, e.g. by calling oldchannel->cancel() there is a certain freedom in implementing this method: if the re
turn-value indicates success, a callback on callback is required. this callback can be done from within asynconchannelredirect() (effectively making the call synchronous) or at some point later (making the call asynchronous). if the re
turn value indicates that an error occurred, in which case an exception is thrown, the redirect is vetoed and no callback must be done. void asynconchannelredirect( in...
nsIClipboardDragDropHookList
s(in nsiclipboarddragdrophooks ahooks); methods addclipboarddragdrophooks() this method adds a hook to the list. void addclipboarddragdrophooks( in nsiclipboarddragdrophooks ahooks ); parameters ahooks implementation of hooks. gethookenumerator() this method retrieves an enumerator for all hooks which have been added. nsisimpleenumerator gethookenumerator(); parameters none. re
turn value re
turns nsisimpleenumerator for nsiclipboarddragdrophooks. removeclipboarddragdrophooks() this method removes a hook from the list. note: if this implementation is not present in the list then removal will be ignored. void removeclipboarddragdrophooks( in nsiclipboarddragdrophooks ahooks ); parameters ahooks implementation of hooks. see also nsiclipboarddragdrophooks nsiclip...
nsICompositionStringSynthesizer
ds, commits composition string. if appendclause() and/or setcaret() are not called properly, e.g., sum of alength of calls of appendclause() is not same as composition string set by setstring(), this throws an exception. after a call of this, all stored composition string information is cleared. therefore, you can reuse the instance for modifying composition string. boolean dispatchevent(); re
turn value if dispatched event's default is prevented, re
turns true. however, this must always re
turn false since all dispatching dom events are not cancelable. setcaret() sets caret position in the composition string set by setstring(). this is optional. i.e., you may not call this before dispatchevent(). void setcaret(in unsigned long aoffset, in unsigned long alength); paramete...
nsIContentFrameMessageManager
ing); domstring btoa(in domstring abase64data); dump() prints the specified string to standard output. parameters name type description astr string the message to log. atob() convert ascii base64 data to binary data. parameters name type description aasciistring string ascii string to decode. re
turns string: the decoded binary data. btoa() convert binary data to ascii base64 data . parameters name type description abase64data string binary data to encode as base64. re
turns string: the base64-encoded ascii string. attributes content nsidomwindow: the current top level window in the frame or null. read only. docshell nsidocshell: the top leve...
nsICookiePromptService
); parameters parent the parent window for the dialog. cookie the cookie about which permission is being requested. hostname the host that wants to set the cookie, not the domain; this is part of the cookie. cookiesfromhost the number of cookies there are already for this host. changingcookie are we changing this cookie? rememberdecision should we set the matching permission for this host? re
turn value re
turns 0 for denying a cookie, 1 for accepting a cookie, and 2 for accepting cookie for the current session only. see also nsicookie nsicookie2 nsicookiemanager nsicookiemanager2 ...
nsICryptoHMAC
256 sha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes this hmac object and produces the actual hmac diegest data. note: this method may be called any time after init() is called. this call resets the object to its pre-init state. acstring finish( in prbool aascii ); parameters aascii if true then the re
turned value is a base-64 encoded string. if false, then the re
turned value is binary data. re
turn value a hash of the data that was read by this object. this can be either binary data or base 64 encoded. exceptions thrown ns_error_not_initialized if init() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. w...
nsICycleCollectorListener
/ thunderbird 3.3 / seamonkey 2.1) the order of calls will be call to begin(); then for every node in the graph a call to noteobject() and calls to noteedge() for every edge starting at that node; then a call to begindescriptions(); then for every black node in the cycle collector graph a call to either describerefcountedobject() or to describegcedobject(); and then a call to end(). if begin() re
turns an error none of the other functions will be called. method overview void begin(); void begindescriptions(); void describegcedobject(in unsigned long long aaddress, in boolean amarked); void describerefcountedobject(in unsigned long long aaddress, in unsigned long aknownedges, in unsigned long atotaledges); void end(); void noteedge(in unsigned long long afromaddress, in unsigned lo...
nsIDBChangeListener
there are a couple of ways to access the message database: if you have a nsimsgfolder, you can do this like so: somefolder.msgdatabase.addlistener(mylistener); alternately, you can access the message database through the nsimsgdbview like so: gfolderdisplay...
nsIDNSListener
rticle. 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 re
turned 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. ...
nsIDOMChromeWindow
attributes attribute type description browserdomwindow nsibrowserdomwindow the related nsibrowserdomwindow instance which provides access to yet another layer of utility functions by chrome script. it will be null for domwindows not corresponding to browsers. messagemanager nsichromeframemessagemanager read only. title domstring obsolete since gecko 1.9.1 windowstate unsigned short re
turns current window state, the value is one of state_* constants. read only. constants constant value description state_maximized 1 the window is maximized. state_minimized 2 the window is minimized. state_normal 3 the window is normal. state_fullscreen 4 the window is in full screen mode. methods beginwindowmove() on some operating systems, we must allow the window manager to handl...
nsIEditor
etoendofline 6 attributes attribute type description contentsmimetype string the mime type of the document. document document read only. the dom document this editor is associated with. documentcharacterset acstring sets the current 'save' document character set. documentisempty boolean read only. re
turns true if the document has no *meaningful* content. documentmodified boolean read only. re
turns true if the document is modifed and needs saving. flags unsigned long edit flags for this editor. may be set at any time. isdocumenteditable prbool read only. re
turns true if we have a document that is not marked read-only. isselectioneditable ...
nsIException
string a custom message set by the thrower. [binaryname(messagemoz)] read only. name string the name of the error code (a string representation of result) read only. result nsresult the nsresult associated with this exception. read only. methods tostring() a generic formatter - make it suitable to print, etc. string tostring(); parameters none. re
turn value a string suitable for output. ...
nsIFactory
ithout specifying a concrete class type. inherits from: nsisupports last changed in gecko 0.9.5 method overview void createinstance(in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result); void lockfactory(in prbool lock); methods createinstance() creates an instance of the class associated with this factory. unlike getservice, this re
turns a new instance each time it is called. (see also nsicomponentmanager.createinstance.) void createinstance( in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result ); parameters aouter pointer to a component that wishes to be aggregated in the resulting instance. this can be nsnull if no aggregation is requested. iid the iid of the interface being reques...
nsIFeed
onday" in this array. note: this field is rarely implemented. skiphours nsiarray an array of the hours of the day during which the feed should not be fetched. the hours are represented as integer values from 0 (midnight) to 23 (11:00 pm), and are always indicated using utc. note: this field is rarely implemented. subtitle nsifeedtextconstruct re
turns a subtitle for the feed, based on its description, subtitle, and appropriate extensions. textinput nsiwritablepropertybag2 information about a text box that can be displayed along with the feed by aggregators that support it, to allow the reader to send a response back to the source of the feed. note: this field is almost never used, and is incompatible with many aggrega...
nsIFeedContainer
edelementbase last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) method overview void normalize(); attributes attribute type description authors nsiarray an array of nsifeedperson objects describing the authors of the feed or entry. categories nsiarray an array of the categories found in a feed or entry. note: the re
turned array will contain nsifeedcategory objects, except that interface has not been implemented yet. contributors nsiarray an array of nsifeedperson objects describing contributors to the feed or entry. fields nsiwritablepropertybag2 provides access to all the fields found in the document. common atom and rss fields are normalized, including some namespaced extensions s...
nsIFileURL
ble provides access to the underlying nsifile object corresponding to a url. the url scheme need not be file:, since other local protocols may map urls to files (e.g., resource:). inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) attributes attribute type description file nsifile get/set nsifile corresponding to this url. the getter re
turns a reference to an immutable object. callers must clone before attempting to modify the re
turned nsifile object. note: this constraint might not be enforced at runtime, so beware! the setter clones the nsifile object (allowing the caller to safely modify the nsifile object after setting it on this interface). ...
nsIFrameLoaderOwner
4 / thunderbird 3.3 / seamonkey 2.1) method overview [noscript, notxpcom] alreadyaddrefed_nsframeloader getframeloader(); void swapframeloaders(in nsiframeloaderowner aotherowner); attributes attribute type description frameloader nsiframeloader the frame loader owned by this nsiframeloaderowner. read only. methods getframeloader() re
turns the frame loader object owned by this object. [noscript, notxpcom] alreadyaddrefed_nsframeloader getframeloader(); parameters none. re
turn value the nsiframeloader owned by this object. swapframeloaders() swaps frame loaders with the given nsiframeloaderowner. this may only be possible in a very limited set of circumstances, or never, depending on the object implementing this interface. void sw...
nsIFrameMessageListener
ivemessage(); methods receivemessage() note: this method is for javascript only. called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name the name of the message. sync a boolean value indicating whether or not the message should be handled synchronously. if true, the response should be re
turned in the specified json object. json the json object in which to re
turn the response if the message is being handled synchronously. objects unimplemented an array of cpow, or null if sync is false. when the listener is called, the this value is the target of the message. void receivemessage(); parameters none. see also content process event handling nsiframelist...
nsIFrameScriptLoader
cancels the effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into new frames. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedframescripts() re
turns all delayed scripts that will be loaded once a (remote) frame becomes available. the re
turn value is a list of pairs [<url>, <wasloadedinglobalscope>]. re
turns list of the delayed scripts. each script is re
turned as a pair: [<url>, <wasloadedinglobalscope>]. ...
nsIGSettingsCollection
.3) method overview boolean getboolean(in autf8string key); long getint(in autf8string key); autf8string getstring(in autf8string key); void setboolean(in autf8string key, in boolean value); void setint(in autf8string key, in long value); void setstring(in autf8string key, in autf8string value); methods getboolean() boolean getboolean( in autf8string key ); parameters key re
turn value getint() long getint( in autf8string key ); parameters key re
turn value getstring() autf8string getstring( in autf8string key ); parameters key re
turn value setboolean() void setboolean( in autf8string key, in boolean value ); parameters key value setint() void setint( in autf8string key, in long value ); parameters key value setstring() void setstring( in...
nsIGSettingsService
as a service: var gsettingsservice = components.classes["@mozilla.org/gsettings-service;1"] .createinstance(components.interfaces.nsigsettingsservice); method overview nsigsettingscollection getcollectionforschema(in autf8string schema); methods getcollectionforschema() nsigsettingscollection getcollectionforschema( in autf8string schema ); parameters schema re
turn value ...
nsIGeolocationProvider
rite a geolocation provider. method overview boolean isready(); obsolete since gecko 1.9.2 void shutdown(); void startup(); void watch(in nsigeolocationupdate callback); methods isready() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) reports whether or not the device is ready and has a position. boolean isready(); parameters none. re
turn value true if the device is ready and has a position available to re
turn; otherwise false. shutdown() shuts down the location device. void shutdown(); parameters none. startup() start up the provider. this is called before any other method and may be called multiple times. void startup(); parameters none. watch() attaches a callback listener to be notified when a location change is observed. vo...
nsIGlobalHistory2
whether the uri was redirected to another location; this is true for the original uri which is redirected. atoplevel whether the uri is loaded in a top-level window. areferrer the uri of the referring page. isvisited() checks to see whether the given uri is in history. boolean isvisited( in nsiuri auri ); parameters auri the nsiuri of the page. re
turn value true if a uri has been visited. setpagetitle() set the page title for the given uri. uris that are not already in global history will not be added. void setpagetitle( in nsiuri auri, in astring atitle ); parameters auri the nsiuri for which to set to the title. atitle the page title. see also nsiglobalhistory3 ...
nsIGlobalHistory3
aflags flags to add. these are defined by the history that is implementing this interface. atoplevel whether the uri is loaded in a top-level window. if false, the load is in a subframe. geturigeckoflags() get the gecko flags for this uri. these flags are used by gecko as hints to optimize page loading. not all histories have them; this need not be supported (just re
turn ns_error_not_implemented. these flags are opaque and should not be interpreted by the history engine. unsigned long geturigeckoflags( in nsiuri auri ); parameters auri the nsiuri to get flags for. flags are defined by the history that is implementing this interface. re
turn value the gecko flags for the uri. seturigeckoflags() set the gecko flags for this uri. may fail if the hi...
nsIHttpHeaderVisitor
rvisitor = function ( ) { this._isflash = false; }; mynsihttpheadervisitor.prototype.visitheader = function ( aheader, avalue ) { if ( aheader.indexof( "content-type" ) !== -1 ) { if ( avalue.indexof( "application/x-shockwave-flash" ) !== -1 ) { this._isflash = true; } } }; mynsihttpheadervisitor.prototype.isflash = function ( ) { re
turn this._isflash; }; myhttprequestobserver = function ( ) { this.register( ); this.aborted = components.results.ns_binding_aborted; this.nsihttpchannel = components.interfaces.nsihttpchannel; this.nsichannel = components.interfaces.nsichannel; this.nsirequest = components.interfaces.nsirequest; }; myhttprequestobserver.prototype.observe = function ( subject,...
nsIINIParserFactory
create nsiiniparser objects for use in parsing ini files. 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) see example for how to use this interface. method overview nsiiniparser createiniparser(in nsilocalfile ainifile); methods createiniparser() creates an ini parser, re
turning the nsiiniparser object that you can use to parse it. nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse. re
turn value the nsiiniparser object you can use to parse the ini file. example obtaining a parser object to obtain a parser for an ini file, you can use code that looks like this: to get an nsiiniparser instance for an in...
nsIInterfaceRequestor
xpcom/base/nsiinterfacerequestor.idlscriptable this interface defines a generic interface for requesting interfaces that a given object might provide access to. inherits from: nsisupports last changed in gecko 0.9.5 this is similar to nsisupports.queryinterface(). the main difference is that interfaces re
turned are not required to provide a way back to the object implementing nsiinterfacerequestor. the semantics of nsisupports.queryinterface() dictate that given an interface a that you nsisupports.queryinterface() on to get to interface b, you must be able to nsisupports.queryinterface() on b to get back to a. nsiinterfacerequestor, however, allows you to obtain an interface c from a that may (or most likely) will not have the ability to get back to a. method overview void g...
nsIJSCID
js/src/xpconnect/idl/xpcjsid.idlscriptable this interface provides methods to instantiate a component and access service components. inherits from: nsijsid last changed in gecko 1.7 method overview nsisupports createinstance(); nsisupports getservice(); methods createinstance() nsisupports createinstance(); parameters none. re
turn value getservice() nsisupports getservice(); parameters none. re
turn value see also see components.classes for usage patterns of the createinstance() and getservice() methods. ...
nsIJetpackService
e.idlscriptable this interface enables the creation of new jetpack processes. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/jetpack/service;1. method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and re
turns an nsijetpack interface that represents it. nsijetpack createjetpack(); parameters none. re
turn value an nsijetpack interface representing the remote process. history see bug 556846 for details. see also nsijetpack jetpack processes ...
nsILocale
alid strings are stored in nsilocale.idl. currently those are: nsilocale_collate - collation order. how strings are sorted. nsilocale_ctype - character classification and case conversion. nsilocale_monetary - monetary formatting. nsilocale_numeric - numeric, non-monetary formatting. nsilocale_time - date and time formats. nsilocale_messages - related to fonts, character encodings and so on. re
turn value the locale code to be used for the given category. a locale code is of the form language[-country[-region]], where "language" is an iso 639 language code (two letter codes preferred over three letter codes when available), "country" is an iso 3166 two letter country code, and "region" is a string of up to 5 letters. see also stringbundle ...
nsIMenuBoxObject
opened using the keyboard; otherwise false. note: for gecko 2.0, the openedwithkey attribute exists on the nsimenuboxobject_mozilla_2_0_branch interface. subsequent gecko versions will have the attribute on the nsimenuboxobject interface. methods handlekeypress() boolean handlekeypress( in nsidomkeyevent keyevent ); parameters keyevent the key event to handle for the menu. re
turn value true if the event was handled, false if not. openmenu() void openmenu( in boolean openflag ); parameters openflag true to open the menu or false to close it. see also nsiboxobject menu ...
nsIMessageBroadcaster
age. obj object. the message payload. a structured clone of this becomes the data property of the received message. objects object. an object each of whose properties is an object. this becomes the objects property of the received message, with each original object replaced with a cross process object wrapper for it. getchildat() re
turn a single subordinate message manager. parameters name type description aindex number the index of the subordinate message manager to retrieve. re
turns nsimessagelistenermanager: the message manager at the given index. attributes childcount number: the number of subordinate message managers. read only. ...
nsIMessageListener
bjects an object whose properties are any cross process object wrappers exposed by the sender as the third argument to the message-sending function. principal principal for the window app. each listener is invoked with its own copy of the message parameter. when the listener is called, 'this' value is the target of the message. if the message is synchronous, the possible re
turn value is re
turned as json (will be changed to use structured clones). when there are multiple listeners to synchronous messages, each listener's re
turn value is sent back as an element in an array. undefined re
turn values show up as undefined values in the array. ...
nsIMicrosummary
r( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to add. equals() microsummary equivalence test. microsummaries equal if they summarize the same page with the same microsummary-generator (see also nsimicrosummarygenerator.equals()). boolean equals( in nsimicrosummary aother ); parameters aother the microsummary to compare against. re
turn value re
turns true if the microsummaries are equal. false if they aren't. note: this method re
turns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading ...
nsIMimeHeaders
string allheaders, in long allheaderssize); attributes attribute type description allheaders string read only. ...
nsIModule
tion, in string aloaderstr, in string atype); void unregisterself(in nsicomponentmanager acompmgr, in nsifile alocation, in string aloaderstr); methods canunload() this method may be queried to determine whether or not the component module can be unloaded by xpcom. boolean canunload( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. re
turn value indicates to the caller whether or not the component module can be unloaded. re
turning true is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. it is very important to ensure that no outstanding references to the module's code/data exist before re
turning true. re
turning false guaratees that the module will not be unloaded. if the...
Building an Account Manager Extension
import("resource://gre/modules/xpcomutils.jsm"); //class constructor function devmoaccountmanagerextension() {}; // class definition devmoaccountmanagerextension.prototype = { name : "devmo-account", chromepackagename : "example@mozilla.org", showpanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") re
turn true; re
turn false; }, queryinterface: xpcomutils.generateqi([ components.interfaces.nsimsgaccountmanagerextension ]) } step 2: building a component we convert the interface to a xpcom component and register it in the component manager as account manager extension. therefore we add the following code to the previous. the javascript file has to be saved either in the ...
nsIMsgAccountManagerExtension
ring chrome package, where the files for the new panel are located. this is usually guid of the id of the addons which adds the new panel. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. re
turn value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded. see also nsimsgaccountmanager building an account manager extension ...
nsIMsgIdentity
n to an autocomplete address with no matches. valid boolean determines if the ui should use this identity and the wizard uses this to determine whether or not to ask the user to complete all the fields. smtpserverkey astring the preferred smtp server for this identity. if this is set, this is the smtp server that should be used for the message send. requestre
turnreceipt boolean readonly: default request for re
turn receipt option for this identity. if this is set, the re
turn receipt menu item on the compose window will be checked. receiptheadertype long readonly: requestdsn boolean readonly: default request for dsn option for this identity. if this is set, the dsn menu item on the compose window will be checked. m...
nsIMsgProtocolInfo
serveriid nsiidptr the iid of the server-specific interface, used during account creation. read only. showcomposemsglink boolean true if compose ui actions should be enabled for the account type. read only. specialfoldersdeletionallowed boolean true if the user can delete folders like inbox, trash, etc. read only. methods getdefaultserverport() re
turns the default port for a connection to a server of this account type. long getdefaultserverport( in boolean issecure ); parameters issecure whether or not the connection will be secure. re
turn value the default port number for connections of this account type. remarks this is one of the interfaces that is required to create a new account type. see also nsimsgincomingserver ...
nsIMsgSearchSession
in nsmsgsearchopvalue op, in nsimsgsearchvalue value); parameters whichterm attrib op value note: this parameter should be an out. countsearchscopes() long countsearchscopes(); getnthsearchscope() void getnthsearchscope(in long which, out nsmsgsearchscopevalue scopeid, out nsimsgfolder folder); parameters which re
turn values scopeid folder addscopeterm() add a scope (e.g. a mail folder) to the search. void addscopeterm(in nsmsgsearchscopevalue scope, in nsimsgfolder folder); parameters scope folder adddirectoryscopeterm() void adddirectoryscopeterm(in nsmsgsearchscopevalue scope); parameters scope clearscopes() void clearscopes(); scopeusescustomh...
nsIMsgSearchTerm
iorityvalue priority); matchage boolean matchage(in prtime days); matchsize boolean matchsize(in unsigned long size); matchlabel boolean matchlabel(in nsmsglabelvalue alabelvalue); matchjunkstatus boolean matchjunkstatus(in string ajunkscore); matchjunkpercent /* * test search term match for junkpercent * * @param ajunkpercent junkpercent for message (0-100, 100 is junk) * @re
turn true if matches */ boolean matchjunkpercent(in unsigned long ajunkpercent); matchjunkscoreorigin /* * test search term match for junkscoreorigin * @param ajunkscoreorigin who set junk score? possible values: * plugin filter imapflag user whitelist * @re
turn true if matches */ boolean matchjunkscoreorigin(in string ajunkscoreorig...
nsIMsgSendLater
() add an event listener to this nsisendmsglater instance. void addlistener(in nsimsgsendlaterlistener listener); parameters listener the nsimsgsendlaterlistener to add. getunsentmessagesfolder() get the unsent messages folder for an identity. nsimsgfolder getunsentmessagesfolder(in nsimsgidentity identity); parameters identity the nsimsgidentity to get the folder for. re
turn value the nsimsgfolder containing unsent messages. ...
nsIMsgWindow
ification callbacks on protocol channels to handle things like bad cert exceptions. promptdialog nsiprompt readonly: this is the equivalent of calling getinterface on the rootdocshell object. mailcharacterset acstring this is used to track the character set of the currently displayed message. if set to an alias, the actual character set is re
turned. charsetoverride boolean remember the message's charset was overridden, so it can be inherited (e.g for quoting). stopped boolean check if a running url been stopped. if you are checking this flag, you need to clear it before you start your operation since there's no convenient place to clear it. domwindow nsidomwindo...
nsIMutableArray
rs of nsiarray should not queryinterface to nsimutablearray unless they own the array. as above, it is legal to add null elements to the array. note also that null elements can be created as a side effect of insertelementat(). conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never re
turn a null value. any of these methods may throw ns_error_out_of_memory when the array must grow to complete the call, but the allocation fails. method overview void appendelement(in nsisupports element, in boolean weak); void clear(); void insertelementat(in nsisupports element, in unsigned long index, in boolean weak); void removeelementat(in unsigned long index)...
nsINavBookmarkObserver
() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavbookmarkobserver and nsinavbookmarkobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { re
turn this; } throw cr.ns_error_no_interface; } see also places manipulating bookmarks using places nsinavbookmarksservice ...
nsINavHistoryFullVisitResultNode
toolkit/components/places/public/nsinavhistoryservice.idlscriptable this interface describes a result from a result_type_full_visit query on the places service. this includes more detailed information than the result_type_visit query (which re
turns nsinavhistoryvisitresultnode, and as such takes more time to look up. 1.0 66 introduced gecko 1.9 inherits from: nsinavhistoryvisitresultnode last changed in gecko 1.9 (firefox 3) the information re
turned in this interface is not commonly used, hence its separation into a separate query type for efficiency. attributes attribute type description referringvisitid long long the referring visit id; the referrer should have the same session id as the visit described by this record. read only...
nsINavHistoryObserver
euri() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavhistoryobserver) || iid.equals(ci.nsinavhistoryobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { re
turn this; } throw cr.ns_error_no_interface; } see also nsinavhistoryresult ...
nsINavHistoryQueryResultNode
yquery queries); attributes attribute type description folderitemid long long for both simple folder nodes and simple-folder-query nodes, this is set to the concrete itemid of the folder. otherwise, this is set to -1. read only. queryoptions nsinavhistoryqueryoptions the options that group the node's children; only valid for result_type_query nodes. read only. methods getqueries() re
turns the queries that build the node's children; only valid for result_type_query nodes. void getqueries( out unsigned long querycount, optional from gecko 2.0 [retval,array,size_is(querycount)] out nsinavhistoryquery queries ); parameters querycount optional from gecko 2.0 the number of queries in the queries array. queries an array of nsinavhistoryquery objects describing the set of querie...
nsINavHistoryResult
e in sort_by_annotation_* sorting modes; you must set this value before setting the sortingmode attribute. sortingmode unsigned short specifies the sorting mode for the result. this value must be one of nsinavhistoryqueryoptions.sort_by_*. changing this value updates the corresponding options for the result so that reusing the current options and queries will always re
turn results based on the current view. suppressnotifications boolean if true, notifications are suppressed. this is used to prevent rapid flickering of changes when performing batch or temporary operations on the result structure. viewer nsinavhistoryresultviewer the viewer for this result. the viewer is responsible for actually updating the vi...
nsINetworkLinkService
onfigured). if the link status is not currently known, we generally assume that it is up. read only. linkstatusknown boolean this is set to true when we believe that islinkup is accurate. read only. linktype unsigned long the type of network connection, one of the link_type_* constants. read only. note: as of gecko 8.0, all operating systems currently re
turn link_type_unknown. android support was backed out due to perceived security concerns, see bug 691054. as of gecko 28.0 android support is available again, see bug 939680. constants constant value description link_type_unknown 0 we were unable to determine the network connection type. link_type_ethernet 1 a standard wired ethernet c...
nsIObserverService
ing atopic, in boolean ownsweak ); parameters anobserver the nsiobserver object which will receive notifications. atopic the notification topic or subject. ownsweak if set to false, the nsiobserverservice will hold a strong reference to anobserver. if set to true and anobserver supports the nsisupportsweakreference interface, a weak reference will be held. otherwise an error will be re
turned. (in most cases, you should use false.) enumerateobservers() called to enumerate all observers registered for a particular topic. nsisimpleenumerator enumerateobservers( in string atopic ); parameters atopic the notification topic or subject. re
turn value re
turns an enumeration of all registered listeners. see nsisimpleenumerator. notifyobservers() this method is called to noti...
nsIPrefLocalizedString
ould not include space for the null terminator, nor should it account for the size of a character. it should only be the number of characters for which there is space in the string. data the string data to be stored. tostring() used to retrieve the contents of this object into a wide string. note: this makes a copy of the string argument passed in. wstring tostring(); parameters none. re
turn value re
turns wstring - the string containing the data stored within this object. ...
nsIPrinterEnumerator
read only. printernamelist nsistringenumerator the list of printer names. read only. methods displaypropertiesdlg() void displaypropertiesdlg( in wstring aprinter, in nsiprintsettings aprintsettings ); parameters aprinter aprintsettings enumerateprinters() obsolete since gecko 1.9 (firefox 3) re
turns an array of the names of all installed printers. void enumerateprinters( out pruint32 acount, [retval, array, size_is(acount)] out wstring aresult ); parameters acount re
turns number of printers re
turned. aresult re
turns array of names. initprintsettingsfromprinter() initializes certain settings from the native printer into the printsettings these settings incl...
nsIProcessScriptLoader
effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into new child processes. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedprocessscripts() re
turns all delayed scripts that will be loaded once a child process becomes available. the re
turn value is a list of pairs [<url>, false]. re
turns list of the delayed scripts. each script is re
turned as a pair: [<url>, false]. ...
nsIProfileLock
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void unlock(); attributes attribute type description directory nsilocalfile the main profile directory. read only. ...
nsIProfileUnlocker
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 unlock(in unsigned long aseverity); constants constant value description attempt_quit 0 politely ask the process currently holding the profile's lock to quit. force_quit 1 forcibly terminate the process holding the profile lock. ...
nsIPropertyBag
d overview nsivariant getproperty(in astring name); attributes attribute type description enumerator nsisimpleenumerator get a nsisimpleenumerator whose elements are nsiproperty objects. read only. methods getproperty() get a property value for the given name. nsivariant getproperty( in astring name ); parameters name the name to re
turn the matching property. re
turn value the property matching the given name. exceptions thrown ns_error_failure if a property with that name doesn't exist. examples get user agent information (operating system specifics. the window scope is not always accessible so the window.navigator cannot be accessed. goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscap...
nsIProtocolProxyFilter
proxyservice, in nsiuri auri, in nsiproxyinfo aproxy ); parameters aproxyservice a reference to the protocol proxy service. this is passed so that implementations may easily access methods such as newproxyinfo. auri the uri for which these proxy settings apply. aproxy the proxy (or list of proxies) that would be used by default for the given uri. this may be null. re
turn value the proxy (or list of proxies) that should be used in place of aproxy. this can be just be aproxy if the filter chooses not to modify the proxy. it can also be null to indicate that a direct connection should be used. use aproxyservice.newproxyinfo to construct nsiproxyinfo objects. see also nsiproxyinfo nsiprotocolproxyservice ...
nsIPushMessage
s the message data as json. jsval json(); parameters none. binary() extracts the message data as a byte array. void binary( [optional] out uint32_t datalen, [array, retval, size_is(datalen)] out uint8_t data ); parameters datalen the data size. data the byte array containing the data. datalen and data are out parameters. when called from javascript, nsipushmessage.binary() re
turns data. please see method parameters in xpidl for more details on using out parameters in javascript. see also nsipushservice nsipushsubscription pushmessagedata ...
nsIRequest
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 re
turns successfully). requests can become pending multiple times during their lifetime. note: suspended requests are still considered pending. boolean ispending(); parameters none. re
turn value true if the request has yet to reach completion. resume() resumes the current request. this may have the effect of re-opening any underlying transport and will resume the delivery of data to any open s...
nsISearchEngine
pe that we'd like to receive in response to this submission. if null, will default to "text/html". purpose [optional] a string meant to indicate the context of the search request. this allows the search service to provide a different nsisearchsubmission depending on e.g. where the search is triggered in the ui. possible values depend on the application's installed search engines. re
turn value an nsisearchsubmission supportsresponsetype() determines whether the engine can re
turn responses in the given mime type. boolean supportsresponsetype( in astring responsetype ); parameters responsetype the mime type to check for. re
turn value re
turns true if the engine spec has a url with the given responsetype, false otherwise. see also nsisearchsubmission nsibrowse...
nsISeekableStream
erse direction. exceptions thrown ns_base_stream_closed if called on a closed stream. seteof() this method truncates the stream at the current offset. void seteof(); parameters none. exceptions thrown ns_base_stream_closed if called on a closed stream. tell() this method reports the current offset, in bytes, from the start of the stream. long long tell(); parameters none. re
turn value the current offset, in bytes, from the start of the stream. exceptions thrown ns_base_stream_closed if called on a closed stream. ...
nsIServerSocketListener
netwerk/base/public/nsiserversocket.idlscriptable this interface is notified whenever a server socket accepts a new connection. the transport is in the connected state, and read/write streams can be opened using the normal nsitransport api. the address of the client can be found by calling the nsisockettransport.getaddress() method or by inspecting nsisockettransport.gethost(), which re
turns a string representation of the client's ip address, which may be either an ipv4 or an ipv6 address. inherits from: nsisupports last changed in gecko 1.7 method overview void onsocketaccepted(in nsiserversocket aserv, in nsisockettransport atransport); void onstoplistening(in nsiserversocket aserv, in nsresult astatus); methods onsocketaccepted() this method is called...
nsISessionStartup
ssionrestore will be displayed. resume_session 2 the previous session should be restored at startup. defer_session 3 the previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case). methods dorestore() determines whether or not there is a session to restore. boolean dorestore(); parameters none. re
turn value true if the session should be restored, otherwise false. ...
nsISmsRequestManager
mmozsmsmessage amessage); constants all sms related errors that could apply to smsrequest objects. constant value description success_no_error 0 no_signal_error 1 not_found_error 2 unknown_error 3 internal_error 4 methods addrequest() track an already existing request object. long addrequest( in nsidommozsmsrequest arequest ); parameters arequest an smsrequest. re
turn value the request id. createrequest() create a new request object. long createrequest( in nsidommozsmsmanager amanager, out nsidommozsmsrequest arequest ); parameters amanager an smsmanager. arequest an smsrequest. re
turn value the request id. notifycreatemessagelist() void notifycreatemessagelist( in long arequestid, in long alistid, in nsidommozsmsmessage amessage ); parameters a...
nsISmsService
a domstring which can either be "received" or "sent" and is representing the way the sms was delivered. sender a domstring with the name of the sender. receiver a domstring with the name of the receiver. body a domstring with the text of the message. timestamp a date object with the timestamp of the message. read a boolean indicating whether a message is marked as read or unread. re
turn value a smsmessage getnumberofmessagesfortext() unsigned short getnumberofmessagesfortext( in domstring text ); parameters text a domstring text to check. re
turn value the number of multi-part sms needed for a given text (160 characters for one sms). hassupport() checks if the current platform has sms support. boolean hassupport(); re
turn value boolean. send() void send( i...
nsISocketProviderService
rovides a mapping between a socket type and its associated socket provider instance. one could also use the service manager directly. 66 introduced gecko 1.0 inherits from: nsisupports last changed in gecko 1.7 method overview nsisocketprovider getsocketprovider(in string sockettype); methods getsocketprovider() given a string representing a socket type, this method re
turns an nsisocketprovider representing that socket type. nsisocketprovider getsocketprovider( in string sockettype ); parameters sockettype the socket type for which to get a socket provider. re
turn value nsisocketprovider that handles the specified socket type. see also nsisocketprovider nsiservicemanager ...
nsISocketTransportService
literal of the peer for this socket. aport specifies the target port of the peer for this socket. aproxyinfo specifies the transport-layer proxy type to use. set to null if no proxy should be used. for more details on communicating information about proxies like socks (which are transparent to upper protocols), see nsiproxiedprotocolhandler , nsiprotocolproxyservice or proxies in necko. re
turn 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...
nsIStackFrame
string the name of the function at this point in the stack. read only. sourceline string the location of this function in filename read only. example to output the stack at a particular location: var s = components.stack; while(s) { console.log(s.name); s = s.caller; } methods tostring() a generic formatter - make it suitable to print, and so forth. string tostring(); parameters none. re
turn value a string suitable for output. see also jsdistackframe ...
nsIStructuredCloneContainer
iant adata); attributes attribute type description formatversion unsigned long get the version of the structured clone algorithm which was used to generate this container's serialized buffer. read only. serializednbytes unsigned long long get the size in bytes of this container's serialized data. read only. methods deserializetovariant() deserialize the object this container holds, re
turning it wrapped as an nsivariant. nsivariant deserializetovariant(); parameters none. re
turn value an nsivariant. getdataasbase64() get this structured clone container's data as a base-64-encoded string. astring getdataasbase64(); parameters none. re
turn value a base-64-encoded string. initfrombase64() initialize this structured clone container from a base-64-encoded byte stream. void initfrombas...
nsIStyleSheetService
unsigned long type ); parameters sheeturi uri of the stylesheet to load and register. type one of the type constants. sheetregistered() check if a stylesheet has been registered boolean sheetregistered( in nsiuri sheeturi, in unsigned long type ); parameters sheeturi uri of the stylesheet to check. type one of the type constants. re
turn value re
turns true if a style sheet at sheeturi has previously been added to the list of style sheets specified by type. unregistersheet() remove the style sheet at sheeturi from the list of style sheets specified by type. the removal takes effect immediately, even for already-loaded documents. void unregistersheet( in nsiuri sheeturi, in unsigned long type ); parameters sheeturi ...
nsISupportsCString
sprimitives.idlscriptable this interface provides scriptable access for ascii character strings. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data acstring provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsChar
sprimitives.idlscriptable this interface provides scriptable access for single character values (often used to store an ascii character). inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data char provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsDouble
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for double-precision floating-point values. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data double provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsFloat
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for single-precision floating-point values. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data float provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsID
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for boolean values. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data nsidptr provides access to the native type represented by the object. methods tostring() this method re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsInterfacePointer
idlscriptable this interface provides scriptable access for xpcom objects. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data nsisupports provides access to the native type represented by the object. dataiid nsidptr stores an iid corresponding to the data attribute. methods tostring() re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRBool
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for boolean values. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data prbool provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt16
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 16-bit signed integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print16 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt32
imitives.idlscriptable this interface provides scriptable access for 32-bit signed integers. 66 introduced gecko 1.0 inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print32 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRInt64
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 64-bit signed integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data print64 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRTime
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for prtime values. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data prtime provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint16
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 16-bit unsigned integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint16 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint32
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 32-bit unsigned integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint32 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint64
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 64-bit unsigned integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint64 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsPRUint8
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for 8-bit unsigned integers. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data pruint8 provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsString
primitives.idlscriptable this interface provides scriptable access for unicode character strings. inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data astring provides access to the native type represented by the object. methods tostring() this methods re
turns a string valued representation of the object. string tostring(); parameters none. re
turn value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. see bug 166426 for details. from gecko 2.0 interfaces are no longer frozen. ...
nsISupportsVoid
idlscriptable this interface provides scriptable access for generic pointers. inherits from: nsisupportsprimitive last changed in gecko 1.0 method overview string tostring(); attributes attribute type description data voidptr this attribute provides access to the native type represented by the object. native code only! methods tostring() string tostring(); parameters none. re
turn value a string valued representation of the object. ...
nsISupportsWeakReference
instances of nsiweakreference. weak references in this scheme can only be produced for objects that implement this interface. inherits from: nsisupports last changed in gecko 1.7 method overview nsiweakreference getweakreference(); methods getweakreference() produces an appropriate instance of nsiweakreference. nsiweakreference getweakreference(); parameters none. re
turn value the resulting nsiweakreference instance. remarks the xpcom glue library provides nssupportsweakreference, a canonical implementation of nsisupportsweakreference. this interface was frozen for gecko 0.9.9. see bug 48726 for details. from gecko 2.0 interfaces are no longer frozen. see also nsiweakreference nssupportsweakreference ...
nsISyncJPAKE
ng ar2); void round2(in acstring apeerid, in acstring apin, in acstring agx3, in acstring agv3, in acstring ar3, in acstring agx4, in acstring agv4, in acstring ar4, out acstring aa, out acstring agva, out acstring ara); methods final() perform the final step of the jpake exchange. this will compute the key and expand the key to two keys, an aes256 encryption key and a 256 bit hmac key. it re
turns a key confirmation value (sha256d of the key) and the encryption and hmac keys. void final( in acstring ab, in acstring agvb, in acstring arb, in acstring ahkdfinfo, out acstring aaes256key, out acstring ahmac256key ); parameters ab schnorr signature value b, in hex representation. agvb schnorr signature value g^vb (vb is a random value), in hex representation. arb schnorr signatur...
nsITaskbarTabPreview
eview is not registered, the api call to set its sibling (via the move() method) will fail silently. this method is only invoked when it's safe to make taskbar api calls. void ensureregistration(); parameters none. violates the xpcom interface guidelines gethwnd() used internally to obtain the handle to the proxy window for the preview. nativewindow gethwnd(); parameters none. re
turn value the hwnd for the preview's proxy window. move() relocates the preview relative to another tab preview from the same window. void move( in nsitaskbartabpreview anext ); parameters anext the preview that this preview should be placed to the left of. a value of null indicates that this preview should be the rightmost one. see also nsitaskbarpreview nsitaskbarpreviewcontroller...
nsIThreadEventFilter
ines methods violates the xpcom interface guidelines acceptevent() this method is called to determine whether or not an event may be accepted by a nested event queue. (see nsithreadinternal.pusheventqueue()) warning: this method must not make any calls on the thread object. boolean acceptevent( in nsirunnable event ); parameters event the event being dispatched. re
turn value implement this method to re
turn true if the event is accepted, or false to reject it. see also the thread manager nsithreadmanager nsithread nsithreadpool nsithreadobserver nsithreadinternal ...
nsIThreadPool
threadlimit unsigned long the maximum number of threads allowed at once in the pool; you may change this value by altering this attribute. methods shutdown() shuts down the thread pool. you must not call this method from any thread within the thread pool. instead, you should call it from another thread (typically the one that created the thread pool). when this method re
turns, the thread pool and all its threads will have been shut down, and it is no longer be possible to dispatch events to the thread pool. void shutdown(); parameters none. see also the thread manager nsithreadmanager nsithread nsithreadinternal nsithreadobserver nsithreadeventfilter nsithreadpoollistener ...
nsIToolkitProfile
profile's name. rootdir nsilocalfile the location of the profile directory. read only. methods lock() locks the profile using platform-specific locking methods. nsiprofilelock lock( out nsiprofileunlocker aunlocker ); parameters aunlocker on error, contains an nsiprofileunlocker object you can use to unlock the profile. note: the unlocker object cannot be re
turned to javascript as the error causes an exception to be thrown. the unlocker object is only available in gecko 34 or later when running on windows vista or later. re
turn value an nsiprofilelock object which holds a profile lock as long as you hold a reference to it. example: var profile = profilelist.getnext().queryinterface(ci.nsitoolkitprofile); var locker = profile.lock({}); remove() remov...
nsITreeContentView
nt getitematindex(in long index); attributes attribute type description root nsidomelement the element in the dom which this view uses as root content. read only. obsolete since gecko 1.8 methods getindexofitem() retrieve the index associated with the specified content item. long getindexofitem( in nsidomelement item ); parameters item a tree row for which to find the row index. re
turn value a non-negative integer row index if the row was found within the tree. re
turns -1 if the item was not found. getitematindex() retrieve the content item associated with the specified index. nsidomelement getitematindex( in long index ); parameters index the row index for which to get the item re
turn value the nsidomelement item. remarks the nsitreecontentview interface only applies to t...
nsIUUIDGenerator
uid-generator;1"] .getservice(components.interfaces.nsiuuidgenerator); method overview nsidptr generateuuid(); void generateuuidinplace(in nsnonconstidptr id); native code only! methods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique. nsidptr generateuuid(); parameters none. re
turn value this method re
turns a nsidptr containing a unique id. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid. void generateuuidinplace( in nsnoncons...
nsIUpdate
type astring the type of patch represented by the object: "major" a major new version of the application. "minor" a minor update, such as a security update. version astring the application version of the update.obsolete since gecko 2.0 methods getpatchat() retrieves a patch. nsiupdatepatch getpatchat( in unsigned long index ); parameters index the index of the patch to retrieve. re
turn value an nsiupdatepatch object describing the specified patch. serialize() serializes the update object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the update. re
turn value the patch object serialized into an nsidomelement. see also nsiupdatepatch nsiupdatechecklistener nsiupdatechecker nsiapplicationu...
nsIUpdateItem
where this item is installed. read only. maxappversion astring the maximum version of the application that this item works with, in fvf format. read only. minappversion astring the minimum version of the application that this item works with, in fvf format. read only. name astring the name of this item. read only. objectsource astring re
turns a js object source representing an nsiupdateitem. read only. targetappid astring the target application id used for checking compatibility for this item. note: add-ons can specify a targetapplication id of toolkit@mozilla.org in their install manifest for compatibility with all apps using a specific release of the toolkit. read only. type long the type of ...
nsIUpdateManager
iew nsiupdate getupdateat(in long index); void saveupdates(); attributes attribute type description activeupdate nsiupdate an nsiupdate object describing the currently in use update. this update is not in the history list. read only. updatecount long the number of updates in the history list; the updates can be fetched by calling getupdateat(). read only. methods getupdateat() re
turns the update at the specified index into the history list. nsiupdate getupdateat( in long index ); parameters index an index into the history list for the nsiupdate to retrieve. re
turn value the nsiupdate at the specified index into the history list. saveupdates() saves all updates to disk. void saveupdates(); parameters none. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiup...
nsIUpdatePatch
erence between two application versions. "complete" a complete patch containing all the replacement files to update to the new version. url astring the url from which the patch was downloaded. methods serialize() serializes the patch object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the patch. re
turn value the patch object serialized into an nsidomelement. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt nsiupdatetimermanager ...
nsIUserCertPicker
an allowinvalid, in boolean allowduplicatenicknames, out boolean canceled); methods pickbyusage() nsix509cert pickbyusage( in nsiinterfacerequestor ctx, in wstring selectednickname, in long certusage, in boolean allowinvalid, in boolean allowduplicatenicknames, out boolean canceled ); parameters ctx selectednickname certusage allowinvalid allowduplicatenicknames canceled re
turn value ...
nsIWebBrowserChrome3
eforelinktraversal() determines the appropriate target for a link. astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the original link target. linkuri link destination uri. linknode link dom node. isapptab whether or not the link is in an application tab. re
turn value a new link target, if appropriate. otherwise re
turns originaltarget. see also nsiwebbrowserchrome2 ...
nsIWebNavigation
ward prbool indicates if the object can go forward. if true this indicates that there is forward session history available for navigation. read only. currenturi nsiuri the currently loaded uri or null. read only. document nsidomdocument retrieves the current dom document for the frame, or lazily creates a blank document if there is none. this attribute never re
turns null except for unexpected error situations. read only. referringuri nsiuri the referring uri for the currently loaded uri or null. read only. sessionhistory nsishistory the session history object used by this web navigation instance. methods goback() tells the object to navigate to the previous session history item. when a page is loaded from session histo...
nsIWebSocketChannel
ilable 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() re
turns. if asyncopen() re
turns successfully, the protocol implementation promises to call at least onstart and onstop of the listener. note: implementations should throw ns_error_already_opened if the websocket connection is reopened. void asyncopen( in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext ); parameters auri the uri of the websoc...
nsIWebappsSupport
ta ); parameters title the user-friendly name of the application. uri the uri of the web application. iconuri the uri of icon of the web application. icondata a base64 encoded representation of the application's icon. isapplicationinstalled() checks is a web application is already installed. boolean isapplicationinstalled( in wstring uri ); parameters uri the uri of the web application. re
turn value true if the web application is installed, false if it's not installed. ...
nsIWinAccessNode
public/msaa/nsiwinaccessnode.idlnot scriptable please add a summary to this article. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview voidptr querynativeinterface([const] in mscomiidref aiid); methods querynativeinterface() voidptr querynativeinterface( [const] in mscomiidref aiid ); parameters aiid re
turn value ...
nsIWinAppHelper
mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsiwinapphelper); the nsixulappinfo and nsixulruntime interfaces are also implemented by "xre/app-info". method overview void fixreg(); obsolete since gecko 1.9 void postupdate(in nsilocalfile logfile); obsolete since gecko 1.9.2 attributes attribute type description usercanelevate boolean read only. re
turns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not already running with elevated permissions otherwise it re
turns false. methods fixreg() obsolete since gecko 1.9 (firefox 3) invokes helper.exe with the /fixreg parameter. ...
nsIWindowCreator
s. nsiwebbrowserchrome createchromewindow( in nsiwebbrowserchrome parent, in pruint32 chromeflags ); parameters parent the nsiwebbrowserchrome of the parent window, if any. null if no parent exists. the newly created window should be made a child/dependent window of the parent, if any (and if the concept applies to the underlying os). chromeflags chrome features from nsiwebbrowserchrome. re
turn value an nsiwebbrowserchrome for the new window. see also nsiwindowwatcher for more details. ...
nsIWindowsShellService
te since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) retrieves a windows registry entry value. string getregistryentry( in long ahkeyconstant, in string asubkeyname, in string avaluename ); parameters ahkeyconstant the starting key, using the constants defined above. asubkeyname the sub key to locate. avaluename the value to locate in the sub key. the empty string re
turns the default value of the sub key. re
turn value the value of the specified sub key/value, truncated to 4096 bytes. restorefilesettings() obsolete since gecko 1.9 (firefox 3) restores system settings to what they were before firefox modified them. void restorefilesettings( in boolean aforallusers ); parameters aforallusers whether or not firefox should restore setti...
nsIWorkerGlobalScope
nformation about itself, as well as to control itself. 1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) attributes attribute type description location nsiworkerlocation read only. navigator nsiworkernavigator read only. onerror nsidomeventlistener self nsiworkerglobalscope re
turns the global scope object itself. read only. see also using web workers nsiworkermessageport nsiworkermessageevent nsiworkerscope nsiabstractworker nsiworker ...
nsIXFormsNSInstanceElement
lement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(80669b92-8331-4f92-aaf8-06e80e6827b3)] interface nsixformsnsinstanceelement : nsisupports { nsidomdocument getinstancedocument(); }; methods getinstancedocument nsidomdocument getinstancedocument(); getinstancedocument re
turns a dom document that corresponds to the instance data associated with the instance element. essentially it is just a shortcut to nsixformsmodelelement::getinstancedocument() for the given instance element. related interfaces nsixformsmodelelement example code none. ...
nsIXFormsNSModelElement
ement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(85fd60c7-1db7-40c0-ae8d-f723fdd1eea8)] interface nsixformsnsmodelelement : nsisupports { nsidomnodelist getinstancedocuments(); }; methods getinstancedocuments nsidomnodelist getinstancedocuments(); getinstancedocuments re
turns a nsidomnodelist containing all the instance documents for the model, making it possible to enumerate over instances in the model without knowing their names. related interfaces nsixformsmodelelement example code none. ...
nsIXMLHttpRequest
you only want this if your url is to a zip file or some file you want to download and make a nsiarraybufferinputstream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=pg&f=1', data => { services.prompt.alert(null, 'xhr success', data); var file = os.path.join(os.const...
nsIXPCException
towjsval(in xpcexjscontextptr cx, in xpcexjsval val); native code only! methods initialize() void initialize( in string amessage, in nsresult aresult, in string aname, in nsistackframe alocation, in nsisupports adata, in nsiexception ainner ); parameters amessage aresult aname alocation adata ainner native code only!stealjsval xpcexjsval stealjsval(); parameters none. re
turn value native code only!stowjsval void stowjsval( in xpcexjscontextptr cx, in xpcexjsval val ); parameters cx val remarks components.exception is a javascript constructor to create nsixpcexception objects. the call signature of the constructor is: components.exception(message, result, stack, data, inner) all parameters are optional and the appropriate placeholder is 'unknown'. message...
nsIXULBrowserWindow
string onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the specified target for the link. linkuri the uri of the link that is about to be traversed. linknode the nsidomnode representing the dom node in which the link is located. isapptab whether or not the link being clicked is in an app tab. re
turn value a string indicating the revised target for the link. setjsdefaultstatus() sets the default status according to javascript's version of the default status. void setjsdefaultstatus( in astring status ); parameters status the status string. setjsstatus() sets the status according to javascript's version of the status. void setjsstatus( in astring status ); parameters status the status...
nsIXULBuilderListener
rebuilds its content. void willrebuild( in nsixultemplatebuilder abuilder ); parameters abuilder the template builder that rebuilds the content. ...
nsIXULRuntime
ng proper ui, it should set this flag to true. os autf8string a string tag identifying the current operating system. this is taken from the os_target configure variable. it will always be available. read only. processid unsigned long the system process id of the caller's process. read only. processtype unsigned long the type of the caller's process. re
turns one of process type constants. read only. widgettoolkit autf8string a string tag identifying the target widget toolkit in use. this is taken from the moz_widget_toolkit configure variable. read only. xpcomabi autf8string a string tag identifying the binary abi of the current processor and compiler vtable. this is taken from the target_xpcom_abi configure vari...
nsIXmlRpcFault
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. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable an xml-rpc exception. xml-rpc server fault codes are re
turned wrapped in this; access it using nsixpconnect.getpendingexception->data. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. methods init() void getdata( in print32 fa...
nsPIPromptService
nd obsolete since gecko 1.9.2 the value is 13. this is the system sound name which should be played when the dialog is shown. see also nsisound.playsystemsound(). this is obsolete on gecko 1.9.2 and later. you should use esoundeventid instead. the indexes for getint() and setint() are: ebuttonpressed the value is 0. this is used for the result of the dialog. the pressed button number will be re
turned. echeckboxstate the value is 1. this is the default checkbox state and the result of it. enumberbuttons the value is 2. this is the number of the visible buttons on the dialog. enumbereditfields the value is 3. this is the number of the visible text fields on the dialog. eeditfield1password the value is 4. if this value is 1, the first text field becomes a password field. otherwise, it's a norm...
NS_CStringAppendData
cstring& astring, const char* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. re
turn values the ns_cstringappenddata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", dat...
NS_CStringContainerInit
« xpcom api reference summary the ns_cstringcontainerinit function initializes a nscstringcontainer instance for use as a nsacstring. #include "nsstringapi.h" nsresult ns_cstringcontainerinit( nscstringcontainer& astring ); parameters astring [in] a nscstringcontainer instance to be initialized. re
turn values the ns_cstringcontainerinit function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is equivalent to ns_cstringcontainerinit2(container, nsnull, 0, 0). the nscstringcontainer structure has private members that should not be accessed directly. after a nscstringcontainer object has been initialized via ns_cstringcontainerinit, it may be used as an ordinary nsacstring object. with ns_cstringcontainerinit, the coder is requ...
NS_CStringCutData
ta( nsacstring& astring, pruint32 acutstart, pruint32 acutlength ); parameters astring [in] a nsacstring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. re
turn values the ns_cstringcutdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange . example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello world"); // remove " world" portion of string ns_cstringcutdata(str, 5, pr_uint32_max); const ch...
NS_CStringInsertData
ng [in] a nsacstring instance to be modified. aoffset [in] an offset into the string's internal buffer specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_cstringinsertdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"); const char* data; ns_cstringgetdata(str, &data); ...
NS_CStringSetData
nsacstring& astring, const char* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. re
turn values the ns_cstringsetdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstring&| parameter. } ns_cstringcontainerfinish(str); } h...
NS_CStringSetDataRange
ing index of the section to replace, measured in storage units. acutlength [in] the length of the section to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_cstringsetdatarange function re
turns ns_ok if successful. otherwise, it re
turns an error code. example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &s...
NS_CStringToUTF16
nsastring& adest ); parameters asrc [in] a nsacstring instance containing the source string to be converted. asrcencoding [in] the character encoding of the source string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsastring instance that will contain the result of the conversion. the result will be encoded using the host byte order. re
turn values the ns_cstringtoutf16 function re
turns ns_ok if successful. otherwise, it re
turns an error code. the set of possible error codes is currently unspecified. example code nsembedcstring str("hello"); nsembedstring ustr; ns_cstringtoutf16(str, ns_cstring_encoding_ascii, ustr); const prunichar *unicharbuf = ustr.get(); history this function was frozen for mozilla 1.7. see bug bug 23...
NS_StringAppendData
astring, const prunichar* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsastring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_stringappenddata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stri...
NS_StringContainerFinish
« xpcom api reference summary the ns_stringcontainerfinish function releases any memory allocated by a nsstringcontainer instance. this is a low-level api. #include "nsstringapi.h" void ns_stringcontainerfinish( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance that is no longer needed. re
turn values this function does not re
turn a value. example code see ns_stringcontainerinit for an example. history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringcontainerinit ...
NS_StringContainerInit
« xpcom api reference summary the ns_stringcontainerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcontainerinit( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance to be initialized. re
turn values the ns_stringcontainerinit function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks the nsstringcontainer structure has unspecified size and layout. its members may not be accessed directly. after a nsstringcontainer object has been initialized, it may be used as an ordinary nsastring object. the internal buffer allocated by a nsstringcontainer is always null-terminated. with ns_stringcontainerinit, the coder is r...
NS_StringCutData
nsastring& astring, pruint32 acutstart, pruint32 acutlength ); parameters astring [in] a nsastring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. re
turn values the ns_stringcutdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange. note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_string...
NS_StringInsertData
[in] a nsacstring instance to be modified. aoffset [in] an offset into the string's internal buffer specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_stringinsertdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange . note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_st...
NS_StringSetData
nsastring& astring, const prunichar* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsastring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_stringsetdata function re
turns ns_ok if successful. otherwise, it re
turns an error code. example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsastring&| parameter. } ns_stringcontainerfi...
NS_StringSetDataRange
e starting index of the section to replace, measured in storage units. acutlength [in] the length of the section to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. re
turn values the ns_stringsetdatarange function re
turns ns_ok if successful. otherwise, it re
turns an error code. example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_str...
NS_UTF16ToCString
asrc [in] a nsastring instance containing the source utf-16 string to be converted. the source string should be encoded using the host byte order. adestencoding [in] the character encoding of the destination string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsacstring instance that will contain the result of the conversion. re
turn values the ns_utf16tocstring function re
turns ns_ok if successful. otherwise, it re
turns an error code. the set of possible error codes is currently unspecified. example code // convert utf-16 (or ucs-2) string to utf-8 void copyutf16toutf8(const nsastring& in, nsacstring& out) { ns_utf16tocstring(in, ns_cstring_encoding_utf8, out); } history this function was frozen for mozil...
nsMsgMessageFlags
ther or not a delivery receipt was requested. mdnreportsent 0x00800000 indicates whether or not a delivery receipt was sent. template 0x01000000 indicates whether or not the message is a template. attachment 0x10000000 indicates whether or not the message has an attachment. labels 0x0e000000 the set of bits used to identify labels. not re
turned in header.flags. runtimeonly 0x00000020 indicates the flags which are not emitted to the database. ...
XPCOM reference
primitive is an xpcom object that "boxes" a value of a primitive type. all xpcom primitives are scriptable, and they all implement an xpcom interface from the table below.xpcom string functionsxpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions. many xpcom pages re
turn an nsresult. prior to gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16), this was an integer that simply re
turned an error code. it is now a strongly typed enum when xpcom is built using a c++11 compiler. this causes compile-time errors to occur when improper values are re
turned as nsresult values, thereby making it easier to catch many bugs. ...
Using nsCOMPtr
this document is the sum total of everything written down about nscomptr. if you have a question about nscomptr, and this document doesn't answer it, there probably isn't a document that answers it. you'll have to
turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation. if you've never used nscomptr before, you're starting in the right place. just keep reading. you'll know when to stop. after you've been using nscomptrs for a while, and you reach unfamiliar territory, or run into compiler errors; you may want to re
turn to this document to get help from the reference manual or the faq. contents status, recent changes, and plans recent changes to nscomptr getting started guide introduction using nscomptr summar...
Working with out parameters
hen working with xpcom components, you might come across method declarations like the following one: [scriptable, uuid(8b5314bc-db01-11d2-96ce-0060b0fb9956)] interface nsitransferable : nsisupports { ... void gettransferdata ( in string aflavor, out nsisupports adata, out unsigned long adatalen ) ; ... } the gettransferdata method takes three parameters, aflavor, adata, and adatalen, and re
turns nothing. adata and adatalen are marked as out, meaning that they act as "re
turn values" for this method, and are changed during the method call. these are so-called out parameters. usage in order to use such a method from javascript via xpconnect, you have to follow a specific rule. to get at the out parameters, you have to pass in an object. after the call, this object will have a new property ...
already_AddRefed
« xpcom api reference already_addrefed in association with nscomptr allows you to assign in a pointer without addrefing it. you may want to use this as a re
turn type from a function that has already produced an addrefed pointer as a result. in fact, it is preferred to use already_addrefed in this case over re
turning a raw pointer or nscomptr (see the nscomptr user manual). defined in: mfbt/alreadyaddrefed.h. example ... already_addrefed<nsifoo> getfoo() { nsifoo* foo = mfoo; ns_if_addref(foo); re
turn foo; } // or already_addrefed<nsifoo> getfoo() { nscomptr<nsifoo> foo = mfoo; // ... re
turn foo.forget(); } ... // the following assignment doesn't perform an additional addref, // as it would do if getfoo() re
turned a raw pointer. nscomptr<nsifoo> foo = getfoo(); se...
xptcall FAQ
eric function stubs in xptcall. these stubs forward calls to a shared function whose job it is to use the typelib information to extract the parameters from the platform specific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call. this code also does the platform specific cleanup as the call re
turns. this all works and is being used in mozilla today on numerous platforms. why can't xptcall just be implemented in c or c++? neither of these two facilities can be done in a fully cross platform way. nor can they generally be done fully in c or c++. let's take them one at a time to see why. the invoke facility requires code that can build and invoke an arbitrary call frame. the c++ compiler ...
XPCOM
ching events to them for processing. troubleshooting xpcom components registrationoften the first time you create an xpcom component, it may fail to register correctly.using nscomptrthis document is the sum total of everything written down about nscomptr. if you have a question about nscomptr, and this document doesn't answer it, there probably isn't a document that answers it. you'll have to
turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation.using nsiclassinfoif you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces.using nsidirectoryservicensdirectoryservice implements the nsiproperties interface. this implementa...
XPIDL Syntax
sed on xpidl syntax and grammar. see xpidl main page for more links and introductory content. simplifications, conventions and notation the syntax is specified according to abnf as defined by rfc 5234, although a few productions use prose for clarity of understanding. lexically, tokens are delimited by whitespace (defined here as spaces, tabs, vertical tabs, form feeds, line feeds, and carriage re
turns, or [ \t\v\f\r\n] in regular expression form). libidl only considers a single line feed as a newline, and not carriage re
turns (although xpidl begs to differ). additionally, the use of both c-style (/* ... */) and c++-style (// ... end-of-line) comments are permitted between any two tokens. some productions can only occur at the beginning of lines; to simplify the grammar, i will not mention the...
xpidl
on on where to get libidl and glib. using xpidl to add an idl file to the build, use the xpidlsrcs makefile variable. for testing purposes, or one-off interface compilation, xpidl can be run from the command line: usage: ./xpidl -m mode [-w] [-v] [-t version number] [-d filename.pp] [-i path] [-o basename | -e filename.ext] filename.idl -a emit annotations to typelib -w
turn on warnings (recommended) -v verbose mode (nyi) -t create a typelib of a specific version number -i add entry to start of include path for ``#include "nsithing.idl" -o use basename (e.g. ``/tmp/nsithing) for output -e use explicit output filename -d write dependencies (requires -e) -m specify output mode: header generate c++ header...
XUL Overlays
cel buttons, may be used in dozens of places in the ui. rather than redefining this set of buttons each time they are necessary in a particular dialog, base xul files can overlay the xul file in which these buttons are defined, dialogoverlay.xul. (actually, the implementation is one step more complicated than this: base files overlay dialogoverlay.xul from the global component directory, which in
turn overlays a platform-specific xul file such as platformdialogoverlay.xul. the mechanism is the same, however.) any dialog that wants to overlay these buttons just declares the overlay at the top: <?xul-overlay href="chrome://global/content/dialogoverlay.xul"?> and includes an empty box with an id of okcancelbuttons in the ui. the following snippet shows a dialog with custom ui elements at the top ...
DB Views (message lists)
ead pane is driven by an nsmsgthreadeddbview object (even when we're in a flat sort). if the user does a quick search or picks a view from the view menu, we create an nsmsgquicksearchdbview. advanced search results are displayed with an nsmsgsearchdbview, and cross-folder saved searches use nsmsgxfvirtualfolderdbview, which inherits from nsmsgsearchdbview. nsmsggroupview is used when grouping is
turned on. one unique thing about nsmsggroupview is that instead of using the message database's nsmsgthread objects like the other view classes, it uses an nsmsggroupthread object, which also implements nsimsgthread. view flags and types the view flags (external reference) are not exclusive. the view types (external reference) are. these are the values filed in nsidbfolderinfo to remember the vie...
MailNews Filters
xecution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. applyfilterstohdr will in
turn call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr. the protocol specific code will then apply all of the actions of the filter to the current msg header. if one of the actions is a move, or a stop filter execution action, we move on to the next header; otherwise, we move on to the next filter. in the case of pop3, filter execution is synchronous. for each new hea...
Demo Addon
e.enumeratemessages(). each message is a nsimsgdbhdr. we iterate over the first ten of them and extract author, subject and date for each one. demo 3- search messages by subject this demo shows how to find messages by a subject accross all folders using gloda. ...
Access Window
indow/tab or setting its title, registering timer events and much more. the window api will give you the complete details. since window is a global variable you can use it directly from your javascript file. check if the window is a tab or the root window window.addeventlistener("load", function(e) { alert("is root?: " + isroot()); }, false); function isroot() { if(window != window.top) re
turn "false"; else re
turn "true"; } the example above tells you if the window object is a reference of the application window or of one of it is a tabs. register a timer window.setinterval( function() { alert('foobar'); }, 60000); //execute the function once very minute if you periodically need to perform a certain action then you can use the setinterval function, it will then ca...
Use SQLite
service(ci.mozistorageservice); var dbconnection; if (!dbfile.exists()) dbconnection = this._dbcreate(dbservice, dbfile); else { dbconnection = dbservice.opendatabase(dbfile); } this.dbconnection = dbconnection; }, _dbcreate: function(adbservice, adbfile) { var dbconnection = adbservice.opendatabase(adbfile); this._dbcreatetables(dbconnection); re
turn dbconnection; }, _dbcreatetables: function(adbconnection) { for(var name in this.dbschema.tables) adbconnection.createtable(name, this.dbschema.tables[name]); }, }; window.addeventlistener("load", function(e) { tbirdsqlite.onload(e); }, false); this is another practical sample on how to handle opendatabase and sql queries on the client side, using in-memory (blob) storage of 2mb...
Styling the Folder Pane
ernamecol -- a property for indicating that a column is the folder name column. hasunreadmessages-true afolder.getnumunread(false) > 0 indicates that the folder (but not subfolders) has unread messages. isserver-true afolder.isserver indicates that the folder is a root folder (one that represents a server). servertype-server afolder.server.type re
turns the type of the server. for example, imap servers are "imap". specialfolder-foldertype afolder.flags & nsmsgfolderflags.<name> re
turns the folder type if it is a special folder (or "none" if it is a regular folder). for example, if the inbox flag is set, this will be "inbox". biffstate-biffstate afolder.biffstate == nsimsgfolder.nsmsgbiffstate_<name> indicates wheth...
customDBHeaders Preference
ous_overlay.xul file: dump(" ~ ~ ~ ~ superfluous ~ ~ ~ ~ \n"); var columnhandler = { getcelltext: function(row, col) { //get the messages header so that we can extract the 'x-superfluous' field var key = gdbview.getkeyat(row); var hdr = gdbview.db.getmsghdrforkey(key); var retval = hdr.getstringproperty("x-superfluous"); dump("x-superfluous: " + retval + "\n"); re
turn retval; }, getsortstringforrow: function(hdr) { re
turn hdr.getstringproperty("x-superfluous"); }, isstring: function() {re
turn true;}, getcellproperties: function(row, col, props){}, getimagesrc: function(row, col) {re
turn null;}, getsortlongforrow: function(hdr) {re
turn 0;} } function addcustomcolumnhandler() { gdbview.addcolumnhandler("colsupe...
libmime content type handlers
types.h" #include "nsisupports.h" #include "mimecth.h" // {20dabd99-f8b5-11d2-8ee0-00a024a7d144} #define ns_imime_content_type_handler_iid \ { 0x20dabd99, 0xf8b5, 0x11d2, \ { 0x8e, 0xe0, 0x0, 0xa0, 0x24, 0xa7, 0xd1, 0x44 } } class nsimimecontenttypehandler : public nsisupports { public: static const nsiid& getiid() { static nsiid iid = ns_imime_content_type_handler_iid; re
turn iid; } ns_imethod getcontenttype(char **contenttype) = 0; ns_imethod createcontenttypehandlerclass(const char *content_type, contenttypehandlerinitstruct *initstruct, mimeobjectclass **objclass) = 0; }; #endif /* nsimimecontenttypehandler_h_ */ plugin installation/location the installatio...
Toolkit version format
version format, as used in firefox 1.5 (xulrunner 1.8) and later. this format is used by the extension manager, software update, and other parts of the platform. versions in at least the following places must conform to this format: addon's and target application's version in install and update manifests. the following preferences: app.extensions.version, extensions.lastappversion versions re
turned by nsixulappinfo. application.ini in xulrunner applications appversion flag in chrome manifests. you can use nsiversioncomparator to compare versions from your application. see older version formats below for description of the older version format used in firefox/thunderbird 1.0. version format a version string consists of one or more version parts, separated with dots. each version pa...
Zombie compartments
example, for an add-on that remembers passwords, visit a site that requires a password; for an add-on that performs an operation involving a specific page element such as an image or a chunk of text, perform that operation. the more you exercise the add-on, the more thorough the testing will be, but in practice a lot of problems show up quickly. open about:memory and close all other pages. re
turn to about:memory and minimize memory and remeasure, multiple times if necessary. if only system compartments are present, and there are no ghost windows, congratulations! that's a good sign that the add-on doesn't cause zombie compartments. otherwise, please file a bug (using the "tech evangelism" product and the "add-ons" component), add "[memshrink]" to its whiteboard, and mark it as blocking...
Type conversion
implicit convert in js-ctypes, data could be converted implicitly when passing to or re
turning from a functiontype call, or setting pointer content, an array element or a struct field. var buffer = ctypes.char.array(10)(); var somecfunction = library.declare("somecfunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); somecfunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type implicit conversion can be tested in the following way: var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' boolean type target type source converted value ctypes.bool js boolean src js number (0 or 1) if src == 0: false if src == 1...
ABI
mes like those used by stdcall_abi above. os specific win32 and os2 callbacks in js-ctypes under these operating systems use a different abi than regular function declarations. other all other operating systems use ctypes.default_abi as their calling convention for all function declarations. method overview string tosource() string tostring() methods tosource() re
turns the string "ctypes.***_abi". string tosource() parameters none. re
turn value a javascript expression that evaluates to the abi. tostring() re
turns a string identifying the abi. string tostring(); parameters none. re
turn value a string identifying the abi. see also ctypes functiontype library ...
Browser Side Plug-in API - Plugins
ugins reloads all plug-ins in the plugins directory. npn_requestread requests a range of bytes for a seekable stream. npn_setvalue sets windowless plug-in as transparent or opaque. npn_setvalueforurl allows a plug-in to change the stored information associated with a url, in particular its cookies. npn_status displays a message on the status line of the browser window. npn_useragent re
turns the browser's user agent field. npn_version re
turns version information for the plug-in api. npn_write pushes data into a stream produced by the plug-in and consumed by the browser. ...
Structures - Plugins
n full-page or embedded mode. npprintcallbackstruct contains information required by the platformprint field of the npembedprint during embedded mode printing. nprect represents a rectangular area of a page. npregion represents a platform-defined region of a page. npsaveddata block of instance information saved after the plug-in is deleted; can be re
turned to the plug-in. npsetwindowcallbackstruct contains information about the plug-in's unix window environment. npstream represents a stream of data either produced by the browser and consumed by the plug-in, or produced by the plug-in and consumed by the browser. npwindow contains information about the target into which the plug-in instance can draw. ...
Gecko Plugin API Reference - Plugins
lugins reloads all plug-ins in the plugins directory. npn_requestread requests a range of bytes for a seekable stream. npn_setvalue sets windowless plug-in as transparent or opaque. npn_setvalueforurl allows a plug-in to change the stored information associated with a url, in particular its cookies. npn_status displays a message on the status line of the browser window. npn_useragent re
turns the browser's user agent field. npn_version re
turns version information for the plug-in api. npn_write pushes data into a stream produced by the plug-in and consumed by the browser. scripting plugins how the dom handles scripting threading model security model what's in the plugin code? accessing browser objects from a plugin how to call plugin native methods the api extensions ...
Color vision simulation - Firefox Developer Tools
ina; it can be age-related, congenital, or due to an injury. to enable this feature, you must have webrender enabled; it may be enabled by default, depending on your configuration of firefox. in the firefox configuration editor, make sure the gfx.webrender.all option is set to true. in the simulate menu, you can choose one option at a time from the following list: none — choose this to re
turn to normal display protanomaly (low red) deuteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medically accurate. however, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you judge whether you need to make adjustments...
DOM Inspector FAQ - Firefox Developer Tools
d enter your search criteria there. the dom inspector's search uses javascript regexps to find nodes for tag and attribute searches, and will do partial matching. for example, if you search nodes' tags for "tab", you'll get matches for tabpanel and tabbox as well as tab. to restrict the search, you can use the beginning-of-string and end-of-string markers; e.g., searching nodes for "^tab$" will re
turn only nodes whose names are exactly "tab". or, if you do not know anything about the node, you can try to select it by clicking on it. scroll the node into view, choose the select-by-click toolbar button, and then click on the element you wish to inspect. the edit menu also includes a select element by click menu item. how do i inspect pseudo-classes and pseudo-elements in the css rules viewer?
DOM Inspector internals - Firefox Developer Tools
iewer list, a label displaying the name of the currently active viewer, and another menu button allowing you to issue viewer-specific commands. viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place. in this way, the panelset and panels function like a frameset and frames. this comparison
turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. this separation allows for viewers to be self-contained, with a viewer's xul defined in its own document and loaded in its own scope, without fear of collisions in the xul, css, or js. another convenient consequence of this is that if you use a p...
Set watch expressions - Firefox Developer Tools
to set a watch expression, expand the watch expressions sidebar, then click "add watch expression." type the expression you'd like to watch into the text field. the debugger will save the expression and watch it as you step through your code. ...
Set a conditional breakpoint - Firefox Developer Tools
es it possible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or errors that occur the last time through a loop, for example. to set a conditional breakpoint, activate the context menu in the source pane, on the line where you want the breakpoint, and select "add conditional breakpoint". you'll then see a textbox where you can enter the expression. press re
turn to finish. conditional breakpoints are shown as orange arrows laid over the line number. if you context-click on any breakpoint, you'll see a menu item "edit breakpoint". you can use this to modify an existing condition or to add a condition to a normal breakpoint. ...
Set an XHR breakpoint - Firefox Developer Tools
an xhr (xmlhttprequest) breakpoint breaks code execution when an xhr request is dispatched so that you can examine the current state of the program. you can break on all requests or on those that include a specific url. to
turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter. note: if you enter a key word instead of a url, code execution will pause on any call to a url that contains that keyword. when your code breaks on an xhr request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executin...
Tutorial: Set a breakpoint - Firefox Developer Tools
ddebuggee(tabs[0].content); // get a debugger.object referring to the window's `report` // function. var reportdo = windowdo.getownpropertydescriptor('report').value; // set a breakpoint at the entry point of `report`. reportdo.script.setbreakpoint(0, { hit: function (frame) { console.log('hit breakpoint in ' + frame.callee.name); console.log('what = ' + frame.eval('what').re
turn); } }); console.log('finished setting breakpoint!'); in the scratchpad, ensure that no text is selected, and press the “run” button. now, click on the text that says “click me!” in the web page. this runs the div element’s onclick handler. when control reaches the start of the report function, debugger calls the breakpoint handler’s hit method, passing a debugger.frame i...
Eyedropper - Firefox Developer Tools
ew have color samples next to them: clicking the sample shows a color picker popup. from firefox 31, the popup contains an eyedropper icon: click this icon to activate the eyedropper. ...
Network request details - Firefox Developer Tools
ality. the tabs at the top of this pane enable you to switch between the following pages: headers messages (only for websocket items) cookies params response cache timings security (only for secure pages) stack trace (only when the request has a stack trace, e.g. a script called by another script). clicking the icon at the right-hand end of the toolbar closes the details pane and re
turns you to the list view. headers tab the headers tab has a toolbar, followed by three main sections. this includes: information about the request status: the response status code for the request; click the "?" icon to go to the reference page for the status code. version: the version of http used. transferred: the amount of data transferred for the request. referrer policy: the...
Use the Inspector API - Firefox Developer Tools
firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context: window.inspector defined in inspector-panel.js. attributes and functions: .selection - information about the inspector's selection: .isnode() - re
turns true if selection is node. .node - re
turns the actual element from the page .window - the window object of the frame the selection is in. .markdirty() - marks that the page has been changed by the inspector - a warning will be shown when leaving the page, since changes made through the inspector are rewritten on reload. bindable events using on: markuploaded called when the left panel has been refreshed, after page change. ready called on first markuploaded. pseudoclass called after ...
Animation inspector example: CSS transitions - Firefox Developer Tools
font: 1.5em "open sans",arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; transition: opacity 500ms 150ms, width 500ms 150ms; } .icon#selected { filter: grayscale(0%); transform: scale(1.5); } .icon#selected+span { opacity: 1; width: 300px; } javascript content function toggleselection(e) { if (e.button != 0) { re
turn; } if (e.target.classlist.contains("icon")) { var wasselected = (e.target.getattribute("id") == "selected"); clearselection(); if (!wasselected) { e.target.setattribute("id", "selected"); } } } function clearselection() { var selected = document.getelementbyid("selected"); if (selected) { selected.removeattribute("id"); } } document.addeventlistener("click"...
Animation inspector example: Web Animations API - Firefox Developer Tools
easing: 'ease-out', delay: 150 } var icon = document.getelementbyid("icon"); var note = document.getelementbyid("note"); var iconanimation = icon.animate(iconkeyframeset, iconkeyframeoptions); var noteanimation = note.animate(notekeyframeset, notekeyframeoptions); iconanimation.pause(); noteanimation.pause(); var firsttime = true; function animatechannel(e) { if (e.button != 0) { re
turn; } if (e.target.id != "icon") { re
turn; } if (firsttime) { iconanimation.play(); noteanimation.play(); firsttime = false; } else { iconanimation.reverse(); noteanimation.reverse(); } } document.addeventlistener("click", animatechannel); ...
UI Tour - Firefox Developer Tools
view" tab, but had its own tab. to learn more about the css declarations listed in this view, see examine computed css. changes view when you are editing in the rules view, you can see the changes you have made in the changes view. computed view the computed view shows you the complete computed css for the selected element (the computed values are the same as what getcomputedstyle would re
turn.): compatibility view starting with firefox developer edition version 77, the compatibility view shows css compability issues, if any, for properties applied to the selected element, and for the current page as a whole. it shows icons for the browsers that do support the properties, and notes properties that are experimental or deprecated. click the name of the property to open the refer...
Call Tree - Firefox Developer Tools
escribing the structure of this program here. note that we use the same program - the same profile, in fact - in the documentation page for the flame chart. the screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. to do this, it generates some arrays filled with random integers and sorts them using each algorithm in
turn. we've zoomed into the part of the recording that shows a long javascript marker: the call tree presents the results in a table. each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest. samples is the number of samples that were taken when we were executing this particular functio...
Sorting algorithms comparison - Firefox Developer Tools
tree and the guide to the flame chart. this program compares the performance of three different sorting algorithms: bubble sort selection sort quicksort it consists of the following functions: sortall() top-level function. iteratively (200 iterations) generates a randomized array and calls sort(). sort() calls each of bubblesort(), selectionsort(), quicksort() in
turn and logs the result. bubblesort() implements a bubble sort, re
turning the sorted array. selectionsort() implements a selection sort, re
turning the sorted array. quicksort() implements quicksort, re
turning the sorted array. swap() helper function for bubblesort() and selectionsort(). partition() helper function for quicksort(). its...
Responsive Design Mode - Firefox Developer Tools
vents; this includes (starting in firefox 79) translating a mouse-drag event into a touch-drag event. (note that when touch simulation is enabled, this toolbar icon is blue; when simulation is disabled, it is black. ...
Tips - Firefox Developer Tools
which other property overrides it. right-click on a name, value, or rule to copy anything from the name, the value, the declaration or the whole rule to your clipboard. web console in all panels: esc opens the split console; useful when debugging, or inspecting nodes in the command line: $0 references the currently selected node. $() is a shortcut to document.queryselector(). $$() re
turns an array with the results from document.queryselectorall(). copy copies anything as a string. right-click a node in the inspector and click "use in console" to create a tempn variable for it. cd switches the javascript evaluation context to a different iframe in the page. console.table() displays tabular data as table. help opens the mdn page describing the available commands. :screenshot ...
Web console keyboard shortcuts - Firefox Developer Tools
history/step backwards through matching commands f9 ctrl + r f9 step forward through matching command history (after initiating reverse search) shift + f9 ctrl + s shift + f9 move to the beginning of the line home ctrl + a ctrl + a move to the end of the line end ctrl + e ctrl + e execute the current expression enter re
turn enter add a new line, for entering multiline expressions shift + enter shift + re
turn shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc mo...
about:debugging (before Firefox 68) - Firefox Developer Tools
"enable add-on debugging" box. if you click "debug", you'll see a dialog asking you to accept an incoming connection. click "ok", and the add-on debugger will start in a separate window. note that sometimes the debugger window is hidden by the main firefox window. see the page on the add-on debugger for all the things you can do with this tool. the "enable add-on debugging" button works by
turning on the devtools.chrome.enabled and devtools.debugger.remote-enabled preferences. both preferences must be true to enable add-on debugging. checking the box sets both preferences to true, and unchecking it sets them both to false. you can also modify the preferences directly in about:config, or by checking "enable browser chrome and add-on debugging toolboxes" and "enable remote debugging" in ...
Firefox Developer Tools
d side of developer tools contains several commands that let you perform actions or change tool settings. this button only appears when there are multiple iframes on a page. click it to display a list of the iframes on the current page and select the one with which you want to work. click this button to take a screenshot of the current page. (note: this feature is not
turned on by default and must be enabled in settings before the icon will appear.) toggles responsive design mode. opens the menu that includes docking options, the ability to show or hide the split console, and developer tools settings. the menu also includes links to the documentation for firefox web tools and the mozilla community. closes the developer tools ...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. primcount a glsizei specifying the number of instances of the range of elements to execute. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if first, count or primcount are negative, a gl.invalid_value error is thrown. if gl.current_program is null, a gl.invalid_operation error is thrown. examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawarraysinstancedangle(gl.points, 0, 8, 4); specifications ...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. primcount a glsizei specifying the number of instances of the set of elements to execute. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a invalid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count or primcount are negative, a gl.invalid_value error is thrown. examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawelementsinstancedangle(gl.points, 2, gl.uns...
Ambient Light Sensor API - Web APIs
the ambient light sensor api provides an interface to monitor the ambient light level or illuminance of the device’s environment. interfaces ambientlightsensor re
turns an interface for accessing ambientlightsensorreadings. specifications specification status comment ambient light sensor candidate recommendation initial definition. ...
AnalyserNode.AnalyserNode() - Web APIs
the desired initial size of the fft for frequency-domain analysis. the default is 2048. maxdecibels: the desired initial maximum power in db for fft analysis. the default is -30. mindecibels: the desired initial minimum power in db for fft analysis. the default is -100. smoothingtimeconstant: the desired initial smoothing constant for the fft analysis. the default is 0.8. re
turn value a new analysernode object instance. specifications specification status comment web audio apithe definition of 'analysernode() constructor' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out ht...
AnalyserNode.getByteFrequencyData() - Web APIs
ybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new uint8array(analyser.frequencybincount); // uint8array should be the same length as the frequencybincount void analyser.getbytefrequencydata(dataarray); // fill the uint8array with data re
turned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to. for any sample which is silent, the value is -infinity. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. re
turn value none. example the following exampl...
AnalyserNode.getFloatTimeDomainData() - Web APIs
the analysernode.fftsize, excess elements are dropped. if it has more elements than needed, excess elements are ignored. syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data re
turned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to. if the array has fewer elements than the analysernode.frequencybincount, excess elements are dropped. if it has more elements than needed, excess elements are ignored. re
turn value none. example the following example shows basic usage of an audiocontext to create an analyse...
AnalyserNode.maxDecibels - Web APIs
alysernode.maxdecibels; analysernode.maxdecibels = newvalue; value a double, representing the maximum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -30 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of maxdecibels or higher will be re
turned as +1.0 or 255, respectively. note: if a value less than or equal to analysernode.mindecibels is set, an indexsizeerror exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more com...
AnalyserNode.minDecibels - Web APIs
alysernode.mindecibels; analysernode.mindecibels = newvalue; value a double, representing the minimum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -100 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of mindecibels or lower will be re
turned as 0.0 or 0, respectively. note: if a value greater than analysernode.maxdecibels is set, an index_size_err exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete appl...
Animation() - Web APIs
syntax var animation = new animation([effect][, timeline]); parameters effect optional the target effect, as an object based on the animationeffectreadonly interface, to assign to the animation. although in the future other effects such as sequenceeffects or groupeffects might be possible, the only kind of effect currently available is keyframeeffect. this can be null (which is the default) to indicate that there should be no effect applied. timeline optional specifies the timeline with which to associate the animation, as an object of a type based on the animationtimeline interface. ...
Animation.cancel() - Web APIs
the web animations api's cancel() method of the animation interface clears all keyframeeffects caused by this animation and aborts its playback. when an animation is cancelled, its starttime and currenttime are set to null. syntax animation.cancel(); parameters none. re
turn value none. exceptions this method doesn't directly throw exceptions; however, if the animation's playstate is anything but "idle" when cancelled, the current finished promise is rejected with a domexception named aborterror. specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. working draft editor's draft. ...
Animation.commitStyles() - Web APIs
the commitstyles() method of the web animations api's animation interface commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. syntax animation.commitstyles(); parameters none. re
turn value none. examples const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); }); specifications specification status comment web animationsthe definition of 'commit...
Animation.currentTime - Web APIs
syntax var currenttime = animation.currenttime; animation.currenttime = newtime; value a number representing the current time in milliseconds, or null to deactivate the animation. examples in the drink me/eat me game, alice's height is animated so it can go from small to large or large to small. ...
Animation.id - Web APIs
syntax var animationsid = animation.id; animation.id = newidstring; value a domstring which can be used to identify the animation, or null if the animation has no id. ...
Animation.pause() - Web APIs
exceptions invalidstateerror the animation's currenttime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity. throws an invalidstateerror if the animation's currenttime is unresolved (perhaps it hasn't started playing yet) and the end time of the animation is positive infinity. ...
Animation.persist() - Web APIs
the persist() method of the web animations api's animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. syntax animation.persist(); parameters none. re
turn value none. examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <d...
Animation.play() - Web APIs
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 it from the beginning. syntax animation.play(); parameters none. re
turn value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation. two animation.play()s, one eventlistener: // the cake has its own animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicecha...
Animation.playState - Web APIs
this property is read-only for css animations and transitions. syntax var currentplaystate = animation.playstate; animation.playstate = newstate; value idle 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. ...
Animation.playbackRate - Web APIs
animations have a playback rate that provides a scaling factor from the rate of change of the animation's timeline time values to the animation’s current time. the playback rate is initially 1. syntax var currentplaybackrate = animation.playbackrate; animation.playbackrate = newrate; value takes a number that can be 0, negative, or positive. negative values reverse the animation. the value is a scaling factor, so for example a value of 2 would double the playback rate. setting an animation’s playbackrate to 0 effectively pauses the animation (however, its playstate does not necessarily become paused). ...
Animation.ready - Web APIs
a new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is ready to be started again. since the same promise is used for both pending play and pending pause requests, authors are advised to check the state of the animation when the promise is resolved. syntax var readypromise = animation.ready; value a promise which resolves when the animation is ready to be played. ...
Animation.replaceState - Web APIs
this will be active if the animation has been removed, or persisted if animation.persist() has been invoked on it. syntax let myreplacestate = animation.replacestate; value a string that represents the replace state of the anmation. the value can be one of: active: the initial value of the animation's replace state; when the animation has been removed by the browser's automatically removing filling animations behavior. persisted: the animation has been explicitly persisted by invoking animation.persist() on it. removed: the animation has been explicitly removed. ...
Animation.reverse() - Web APIs
the animation.reverse() method of the animation interface reverses the playback direction, meaning the animation ends at its beginning. if called on an unplayed animation, the whole animation is played backwards. if called on a paused animation, the animation will continue in reverse. syntax animation.reverse(); parameters none. re
turn value undefined example in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to play backwards, causing her to get smaller. it is done by setting alicechange's animation.playbackrate to -1 like so: var shrinkalice = function() { // play alice's animation in reverse alicechange.playbackrate = -1; alicechange.play(); // play the bottle's animation drinking.play()...
Animation.startTime - Web APIs
ifferent time. examples in the running on web animations api example, the we can sync all new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes new cats. ...
Animation.timeline - Web APIs
a timeline is a source of time values for synchronization purposes, and is an animationtimeline-based object. by default, the animation's timeline and the document's timeline are the same. syntax var animationstimeline = animation.timeline; animation.timeline = newtimeline; value a timeline object to use as the timing source for the animation, or null to use the default, which is the document's timeline. ...
Animation.updatePlaybackRate() - Web APIs
ybackrate() 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 playbackrate the new speed to set. this may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). re
turn value none. examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification stat...
AnimationEffect.getTiming() - Web APIs
the animationeffect.gettiming() method of the animationeffect interface re
turns an effecttiming object containing the timing properties for the animation effect. syntax animationtiming = animation.gettiming(); re
turns an effecttiming object. specifications specification status comment web animationsthe definition of 'animationeffect.gettiming()' in that specification. working draft editor's draft. ...
AnimationEffect.updateTiming() - Web APIs
the updatetiming() method of the animationeffect interface updates the specified timing properties for an animation effect. syntax animation.updatetiming(timing); parameters timing an optionaleffecttiming object containing the timing properties to update. re
turn value none. specifications specification status comment web animationsthe definition of 'animationeffect.updatetiming()' in that specification. working draft editor's draft. ...
AnimationEffect - Web APIs
the animationeffect interface of the web animations api defines current and future animation effects like keyframeeffect, which can be passed to animation objects for playing, and keyframeeffectreadonly (which is used by css animations and transitions). methods animationeffect.gettiming() re
turns the effecttiming object associated with the animation containing all the animation's timing values. animationeffect.getcomputedtiming() re
turns the calculated timing properties for this animationeffect. animationeffect.updatetiming() updates the specified timing properties of this animationeffect. specifications specification status comment web animationsthe definition of 'animationeffect' in that specification. working draft editor's draft. ...
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
syntax var animationplaybackevent = new animationplaybackevent(type, eventinitdict); parameters type a domstring representing the name of the event. eventinitdict optional an optional eventinit dictionary object containing the following fields: bubbles optional defaults to false, of type boolean, indicating if the event bubbles or not. cancelable optional defaults to false, of type boolean, indicating if the event can be canceled or not. detail optional defaults to null, of type any — an event-dependent value associated with the event. ...
AnimationTimeline.currentTime - Web APIs
syntax var currenttime = animationtimeline.currenttime; value a number representing the timeline's current time in milliseconds, or null if the timeline is inactive. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of animationtimeline.currenttime might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. ...
AnimationTimeline - Web APIs
line interface of the web animations api represents the timeline of an animation. this interface exists to define timeline features (inherited by documenttimeline and future timeline types) and is not itself directly used by developers. anywhere you see animationtimeline, you should use documenttimeline or any other timeline type instead. properties animationtimeline.currenttime read only re
turns the time value in milliseconds for this timeline or null if this timeline is inactive. specifications specification status comment web animationsthe definition of 'animationtimeline' in that specification. working draft editor's draft. ...
Attr.namespaceURI - Web APIs
the attr.namespaceuri read-only property re
turns the namespace uri of the attribute, or null if the element is not in a namespace. before dom4 this api was defined within the node interface. syntax namespace = attribute.namespaceuri example in this snippet, an attribute is being examined for its localname and its namespaceuri. if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>. if (attribute.localname == "value" && attribute.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul value } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of an att...
Attr.prefix - Web APIs
before dom4 this api was defined within the node interface. syntax string = attribute.prefix examples the following logs "x" to the console. <div x:id="example" onclick="console.log(this.attributes[0].prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. specifications specification status comment domthe definition of 'attr: prefix' in that specification. ...
AudioBuffer() - Web APIs
least 32 channels. samplerate: the sample rate in hz for the buffer. the default is the sample rate of the context used in constructing this object. user agents are required to support sample rates from 8,000 hz to 96,000 hz (but are allowed to go farther outside this range). deprecated parameters context a reference to an audiocontext. this parameter was removed from the spec. re
turn value a new audiobuffer object instance. exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. specifications specification status comment web au...
AudioBuffer.copyFromChannel() - Web APIs
elnumber, startinchannel); parameters destination a float32array to copy the channel's samples to. channelnumber the channel number of the current audiobuffer to copy the channel data from. startinchannel optional an optional offset into the source channel's buffer from which to begin copying samples. if not specified, a value of 0 (the beginning of the buffer) is assumed by default. re
turn value undefined. exceptions indexsizeerror one of the input parameters has a value that is outside the accepted range: the value of channelnumber specifies a channel number which doesn't exist (that is, it's greater than or equal to the value of numberofchannels on the channel). the value of startinchannel is outside the current range of samples that already exist in the source buffer...
AudioBuffer.duration - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.duration; value a double. ...
AudioBuffer.getChannelData() - Web APIs
the getchanneldata() method of the audiobuffer interface re
turns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel). syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for. an index value of 0 represents the first channel. if the channel index value is greater than of equal to audiobuffer.numberofchannels, an index_size_err exception will be thrown. re
turn value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffe...
AudioBuffer.length - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.length; value an integer. ...
AudioBuffer.sampleRate - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.samplerate; value a floating-point value indicating the current sample rate of the buffers data, in samples per second. ...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
ple frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. thus, its behavior is independent of the value of the playbackrate parameter. playbackrate: the speed at which to render the audio stream. its default value is 1. this parameter is k-rate. this is a compound parameter with detune. its nominal range is (-∞ to +∞). re
turn value a new audiobuffersourcenode object instance. specifications specification status comment web audio apithe definition of 'audiobuffersourcenode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check ...
AudioBufferSourceNode.detune - Web APIs
he detune property of the audiobuffersourcenode interface is a k-rate audioparam representing detuning of oscillation in cents. for example, values of +100 and -100 detune the source up or down by one semitone, while +1200 and -1200 detune it up or down by one octave. syntax var source = audioctx.createbuffersource(); source.detune.value = 100; // value in cents note: though the audioparam re
turned is read-only, the value it represents is not. value a k-rate audioparam whose value indicates the detuning of oscillation in cents. example const audioctx = new audiocontext(); const channelcount = 2; const framecount = audioctx.samplerate * 2.0; // 2 seconds const myarraybuffer = audioctx.createbuffer(channelcount, framecount, audioctx.samplerate); for (let channel = 0; channel < chann...
AudioBufferSourceNode.loopEnd - Web APIs
offset into playing the audiobuffer playback should loop back to the time indicated by the loopstart property. this is only used if the loop property is true. syntax audiobuffersourcenode.loopend = endoffsetinseconds; var endoffsetinseconds = audiobuffersourcenode.loopend; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop re
turn to the beginning of the loop (that is, the current play time gets reset to audiobuffersourcenode.loopstart). this property is only used if the loop property is true. the default value is 0. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and ...
AudioBufferSourceNode.start() - Web APIs
peed, the midway point through a 10-second audio buffer is still 5. duration optional the duration of the sound to be played, specified in seconds. if this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop() method. using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration). re
turn value undefined. exceptions typeerror a negative value was specified for one or more of the three time parameters. please don't attempt to tamper with the laws of temporal physics. invalidstateerror start() has already been called. you can only call this function once during the lifetime of an audiobuffersourcenode. examples the most simple example just starts the audio buffer playing ...
AudioBufferSourceNode - Web APIs
etime after the sound has finished playing. multiple calls to stop() are allowed. the most recent call replaces the previous one, if the audiobuffersourcenode has not already reached the end of the buffer. number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and re
turns a new audiobuffersourcenode object. an audiobuffersourcenode can be instantiated using the audiocontext.createbuffersource() method. properties inherits properties from its parent, audionode. audiobuffersourcenode.buffer an audiobuffer that defines the audio asset to be played, or when set to the value null, defines a single channel of silence (in which every sample is 0.0). audiobuffers...
AudioContext() - Web APIs
y or may not choose to meet this request; check the value of audiocontext.baselatency to determine the true latency after creating the context. samplerate optional the samplerate to be used by the audiocontext, specified in samples per second. the value may be any value supported by audiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. re
turn value the newly constructed audiocontext instance. exceptions notsupportederror the specified samplerate isn't supported by the context. usage notes the specification doesn't go into a lot of detail about things like how many audio contexts a user agent should support, or minimum or maximum latency requirements (if any), so these details can vary from browser to browser. be sure to check...
AudioContext.baseLatency - Web APIs
the end of the audio graph — into the host system's audio subsystem ready for playing. note: you can request a certain latency during construction time with the latencyhint option, but the browser may ignore the option. syntax var baselatency = audioctx.baselatency; value a double representing the base latency in seconds. ...
AudioContext.close() - Web APIs
de audio data, create buffers, etc. this function does not automatically release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. the re
turned promise resolves when all audiocontext-creation-blocking resources have been released. this method throws an invalid_state_err exception if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.close().then(function() { ... }); await audioctx.close(); re
turns a promise that resolves with void. example the following snippet is taken from our audiocontext sta...
AudioContext.createMediaElementSource() - Web APIs
om which can then be played and manipulated. for more details about media element audio source nodes, check out the mediaelementaudiosourcenode reference page. syntax var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); parameters mymediaelement an htmlmediaelement object that you want to feed into an audio processing graph to manipulate. re
turns a mediaelementaudiosourcenode. example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback. when the mouse pointer is moved, the updatepage() function is invoked, which calculates the current gain as a ratio of mouse y position divided by overall win...
AudioContext.createMediaStreamDestination() - Web APIs
be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method. for more details about media stream destination nodes, check out the mediastreamaudiodestinationnode reference page. syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); re
turns a mediastreamaudiodestinationnode. examples in the following simple example, we create a mediastreamaudiodestinationnode, an oscillatornode and a mediarecorder (the example will therefore only work in firefox and chrome at this time.) the mediarecorder is set up to record information from the mediastreamdestinationnode. when the button is clicked, the oscillator starts, and the mediarecorder...
AudioContext.createMediaStreamSource() - Web APIs
ermedia instance), the audio from which can then be played and manipulated. for more details about media stream audio source nodes, check out the mediastreamaudiosourcenode reference page. syntax audiosourcenode = audiocontext.createmediastreamsource(stream); parameters stream a mediastream to serve as an audio source to be fed into an audio processing graph for use and manipulation. re
turn value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream. example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode. next, we feed this source audio into a l...
AudioContext.suspend() - Web APIs
udio hardware access and reducing cpu/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while. this method will cause an invalid_state_err exception to be thrown if called on an offlineaudiocontext. syntax var audioctx = new audiocontext(); audioctx.suspend().then(function() { ... }); re
turns a promise that resolves with void. the promise is rejected if the context has already been closed. example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called. in each case, the text label of the butt...
AudioListener.setOrientation() - Web APIs
three unitless parameters xup, yup and zup, describes the direction of the top of the listener's head. the up vector's default value is (0, 1, 0). the two vectors must be separated by an angle of 90° — in linear analysis terms, they must be perpendicular to each other. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setorientation(0,0,-1,0,1,0); re
turns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a char...
AudioListener.setPosition() - Web APIs
ters x, y and z are unitless and describe the listener's position in 3d space according to the right-hand cartesian coordinate system. pannernode objects use this position relative to individual audio sources for spatialisation. the default value of the position vector is (0, 0, 0). syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setposition(1,1,1); re
turns void. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be moving a char...
AudioNode.context - Web APIs
syntax var acontext = anaudionode.context; value the audiocontext or offlineaudiocontext object that was used to construct this audionode. ...
AudioNode.disconnect() - Web APIs
the disconnect() method of the audionode interface lets you disconnect one or more nodes from the node on which the method is called. syntax audionode.disconnect(); audionode.disconnect(output); audionode.disconnect(destination); audionode.disconnect(destination, output); audionode.disconnect(destination, output, input); re
turn value undefined parameters there are several versions of the disconnect() method, which accept different combinations of parameters to control which nodes to disconnect from. if no parameters are provided, all outgoing connections are disconnected. destination optional an audionode or audioparam specifying the node or nodes to disconnect from. if this value is an audionode, a single node is disconnected from, with any other, optional, parameters (outpu...
AudioNode.numberOfInputs - Web APIs
source nodes are defined as nodes having a numberofinputs property with a value of 0. syntax var numinputs = audionode.numberofinputs; value an integer ≥ 0. ...
AudioNode.numberOfOutputs - Web APIs
destination nodes — like audiodestinationnode — have a value of 0 for this attribute. syntax var numoutputs = audionode.numberofoutputs; value an integer ≥ 0. ...
AudioNode - Web APIs
: the first version of the web audio spec only defined the factory methods. after a design review in october 2013, it was decided to add constructors because they have numerous benefits over factory methods. the constructors were added to the spec from august to october 2016. factory methods continue to be included in the spec and are not deprecated. properties audionode.context read only re
turns the associated baseaudiocontext, that is the object representing the processing graph the node is participating in. audionode.numberofinputs read only re
turns the number of inputs feeding the node. source nodes are defined as nodes having a numberofinputs property with a value of 0. audionode.numberofoutputs read only re
turns the number of outputs coming out of the node. destination ...
AudioParam.cancelAndHoldAtTime() - Web APIs
dioparam interface cancels all scheduled future changes to the audioparam but holds its value at a given time until further changes are made using other methods. syntax var audioparam = audioparam.cancelandholdattime(canceltime) parameters canceltime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled. re
turn value a reference to the audioparam it was called on. specifications specification status comment web audio apithe definition of 'cancelandholdattime()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check...
AudioParam.cancelScheduledValues() - Web APIs
the cancelscheduledvalues() method of the audioparam interface cancels all scheduled future changes to the audioparam. syntax var audioparam = audioparam.cancelscheduledvalues(starttime) parameters starttime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled. re
turns a reference to this audioparam object. in some older implementations this method re
turns void. examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currenttime); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that...
AudioParam.exponentialRampToValueAtTime() - Web APIs
yback rates than linear ramps because of the way the human ear works. syntax var audioparam = audioparam.exponentialramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. endtime a double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. re
turns a reference to this audioparam object. in some browsers older implementations of this interface re
turn void. examples in this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. this...
AudioParam.linearRampToValueAtTime() - Web APIs
ter, and reaches the new value at the time given in the endtime parameter. syntax var audioparam = audioparam.linearramptovalueattime(value, endtime) parameters value a floating point number representing the value the audioparam will ramp to by the given time. endtime a double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. re
turns a reference to this audioparam object. in some browsers older implementations of this interface re
turn void. example in this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, linearramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. this is...
AudioParam.setTargetAtTime() - Web APIs
rttime the time that the exponential transition will begin, in the same time coordinate system as audiocontext.currenttime. if it is less than or equal to audiocontext.currenttime, the parameter will start changing immediately. timeconstant the time-constant value, given in seconds, of an exponential approach to the target value. the larger this value is, the slower the transition will be. re
turns a reference to this audioparam object. some older browser implementations of this interface re
turn void. description the change starts at the time specified in starttime and exponentially moves towards the value given by the target parameter. the decay rate as defined by the timeconstant parameter is exponential; therefore the value will never reach target completely, but after each timestep ...
AudioParam.setValueAtTime() - Web APIs
in the value parameter. syntax var audioparam = audioparam.setvalueattime(value, starttime) parameters value a floating point number representing the value the audioparam will change to at the given time. starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen. a typeerror is thrown if this value is negative. re
turns a reference to this audioparam object. in some browsers older implementations of this interface re
turn void. examples this simple example features a media element source with two control buttons (see our webaudio-examples repo for the source code, or view the example live). when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method...
AudioParam.setValueCurveAtTime() - Web APIs
representing the time (in seconds) after the audiocontext was first created that the change in value will happen. if this value is lower than audiocontext.currenttime, it is clamped to currenttime. duration a double representing the total time (in seconds) over which the parameter's value will change following the specified curve. the specified values are spaced equally along this duration. re
turn value a reference to this audioparam object. some older browser implementations of this interface re
turn undefined. exceptions invalidstateerror the specified array of values has fewer than 2 items in it. rangeerror the specified starttime is either negative or a non-finite value, or duration is not a finite, strictly positive number. typeerror one or more of the values in the values ar...
AudioScheduledSourceNode.stop() - Web APIs
to play. syntax audioscheduledsourcenode.stop([when]); parameters when optional the time, in seconds, at which the sound should stop playing. this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute. omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately. re
turn value undefined exceptions invalidstatenode the node has not been started by calling start(). rangeerror the value specified for when is negative. example this example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. the stop time is determined by taking the audio context's current time from audiocontext.currenttime and add...
AudioTrackList.getTrackById() - Web APIs
the audiotracklist method gettrackbyid() re
turns the first audiotrack object from the track list whose id matches the specified string. this lets you find a specified track if you know its id string. syntax var thetrack = audiotracklist.gettrackbyid(id); paramters id a domstring indicating the id of the track to locate within the track list. re
turn value an audiotrack object indicating the first track found within the audiotracklist whose id matches the specified string. if no match is found, this method re
turns null. the tracks are searched in their natural order; that is, in the order defined by the media resource itself, or, if the resource doesn't define an order, the relative order in which the tracks are declared by the media resource. example this example suggests a hypoth...
AudioTrackList.length - Web APIs
a value of 0 indicates that there are no audio tracks in the media. syntax var trackcount = audiotracklist.length; value a number indicating how many audio tracks are included in the audiotracklist. each track can be accessed by treating the audiotracklist as an array of objects of type audiotrack. example this snippet gets the number of audio tracks in the first <video> element found in the dom by queryselector(). ...
AudioTrackList - Web APIs
e called when the change event occurs. this occurs when one or more tracks have been enabled or disabled by their enabled flag being changed. onremovetrack an event handler to call when the removetrack event is sent, indicating that an audio track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() re
turns the audiotrack found within the audiotracklist whose id matches the specified string. if no match is found, null is re
turned. events addtrack fired when a new audio track has been added to the media element. also available via the onaddtrack property. change fired when a track has been enabled or disabled. also available via the onchange property. removetrack fired when a new audio t...
AudioWorkletNode() - Web APIs
the array length must match numberofoutputs. parameterdata optional an object containing the initial values of custom audioparam objects on this node (in its parameters property), with key being the name of a custom parameter and value being its initial value. processoroptions optional any additional data that can be used for custom initialization of the underlying audioworkletprocessor. re
turn value the newly constructed audioworkletnode instance. exceptions notsupportederror the specified options.outputchannelcount is 0 or larger than the current implementation supports. indexsizeerror the length of options.outputchannelcount array does not match options.numberofoutputs. example for a complete example demonstrating user-defined audio processing, see the audioworkletnode pag...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
syntax var authnrdata = authenticatorassertionresponse.authenticatordata; value an arraybuffer that has a arraybuffer.bytelength of at least 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser. ...
AuthenticatorAssertionResponse - Web APIs
this interface inherites from authenticatorresponse. note: this interface is restricted to top-level contexts. use from within an <iframe> element will not have any effect. properties authenticatorassertionresponse.clientdatajson secure contextread only the client data for the authentication, such as origin and challenge. the clientdatajson property is inherited from the authenticatorresponse. ...
AuthenticatorAttestationResponse.attestationObject - Web APIs
as part of the credentialscontainer.create() call, an authenticator will create a new keypair as well as an attestationobject for that keypair. the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations). ...
AuthenticatorResponse.clientDataJSON - Web APIs
cates the client support token binding but did not negotiate with the relying party or "present" when token binding was used already id: a domstring which is the base64url encoding of the token binding id which was used for the communication. should this property be absent, it would indicate that the client does not support token binding. ...
BaseAudioContext.audioWorklet - Web APIs
syntax baseaudiocontextinstance.audioworklet; value an audioworklet instance. examples for a complete example demonstrating user-defined audio processing, see the audioworkletnode page. ...
BaseAudioContext.createAnalyser() - Web APIs
the createanalyser() method of the baseaudiocontext interface creates an analysernode, which can be used to expose audio time and frequency data and create data visualisations. note: for more on using this node, see the analysernode page. syntax var analysernode = baseaudiocontext.createanalyser(); re
turns an analysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.
BaseAudioContext.createBiquadFilter() - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). ...
BaseAudioContext.createBuffer() - Web APIs
e size of the buffer in sample-frames (where each sample-frame is the size of a sample in bytes multiplied by numofchannels). to determine the length to use for a specific number of seconds of audio, use numseconds * samplerate. samplerate the sample rate of the linear audio data in sample-frames per second. all browsers must support sample rates in at least the range 8,000 hz to 96,000 hz. re
turns an audiobuffer configured based on the specified options. exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. examples first, a couple of simple trivial examples, to ...
BaseAudioContext.createBufferSource() - Web APIs
the createbuffersource() method of the baseaudiocontext interface is used to create a new audiobuffersourcenode, which can be used to play audio data contained within an audiobuffer object. audiobuffers are created using baseaudiocontext.createbuffer or re
turned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track. syntax var source = baseaudiocontext.createbuffersource(); re
turns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('but...
BaseAudioContext.createChannelMerger() - Web APIs
merger() method of the baseaudiocontext interface creates a channelmergernode, which combines channels from multiple audio streams into a single audio stream. syntax baseaudiocontext.createchannelmerger(numberofinputs); parameters numberofinputs the number of channels in the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified. re
turns a channelmergernode. example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
BaseAudioContext.createChannelSplitter() - Web APIs
udiocontext interface is used to create a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately. syntax baseaudiocontext.createchannelsplitter(numberofoutputs); parameters numberofoutputs the number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified. re
turns a channelsplitternode. example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect t...
BaseAudioContext.createConstantSource() - Web APIs
the createconstantsource() property of the baseaudiocontext interface creates a constantsourcenode object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value. syntax var constantsourcenode = audiocontext.createconstantsource() parameters none. re
turns a constantsourcenode instance. specifications specification status comment web audio apithe definition of 'createconstantsource()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechr...
BaseAudioContext.createDelay() - Web APIs
f the baseaudiocontext interface is used to create a delaynode, which is used to delay the incoming audio signal by a certain amount of time. syntax var delaynode = audioctx.createdelay(maxdelaytime); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by. must be less than 180 seconds, and defaults to 1 second if not specified. re
turns a delaynode. the default delaynode.delaytime is 0 seconds. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, s...
BaseAudioContext.createDynamicsCompressor() - Web APIs
nal and raises the volume of the softest parts. overall, a louder, richer, and fuller sound can be achieved. it is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. syntax baseaudioctx.createdynamicscompressor(); re
turns a dynamicscompressornode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compr...
BaseAudioContext.createGain() - Web APIs
the creategain() method of the baseaudiocontext interface creates a gainnode, which can be used to control the overall gain (or volume) of the audio graph. syntax var gainnode = audiocontext.creategain(); re
turn value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> <...
BaseAudioContext.createIIRFilter() - Web APIs
es specifying the feedforward (numerator) coefficients for the transfer function of the iir filter. the maximum length of this array is 20, and at least one value must be nonzero. feedback an array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the iir filter. this array may have up to 20 members, the first of which must not be zero. re
turn value an iirfilternode implementing the filter with the specified feedback and feedforward coefficient arrays. exceptions invalidstateerror all of the feedforward coefficients are 0, and/or the first feedback coefficient is 0. notsupportederror one or both of the input arrays exceeds 20 members. specifications specification status comment web audio apithe defini...
BaseAudioContext.createOscillator() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. ...
BaseAudioContext.createPanner() - Web APIs
method of the baseaudiocontext interface is used to create a new pannernode, which is used to spatialize an incoming audio stream in 3d space. the panner node is spatialized in relation to the audiocontext's audiolistener (defined by the audiocontext.listener attribute), which represents the position and orientation of the person listening to the audio. syntax baseaudioctx.createpanner(); re
turns a pannernode. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. you might be movin...
BiquadFilterNode.frequency - Web APIs
-rate audioparam, a double representing a frequency in the current filtering algorithm measured in hertz (hz). frequency's default value is 350 with a nominal range of 10 to the nyquist frequency — that is, half of the sample rate. syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam re
turned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use f...
BiquadFilterNode.gain - Web APIs
ng the gain used in the current filtering algorithm. when it takes a positive value it is a real gain, when negative it is an attenuation. it is expressed in db, has a default value of 0 and can take a value in a nominal range of -40 to 40. syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam re
turned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use f...
BiquadFilterNode.getFrequencyResponse() - Web APIs
alue in this array is nan. these are unitless values. phaseresponseoutput a float32array to receive the computed phase response values in radians for each frequency value in the input frequencyarray. for any frequency in frequencyarray whose value is outside the range 0.0 to samplerate/2 (where samplerate is the sample rate of the audiocontext), the corresponding value in this array is nan. re
turn value undefined exceptions invalidaccesserror the three arrays provided are not all of the same length. example in the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies. we first create the...
BiquadFilterNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a new instance of a biquadfilternode object. properties inherits properties from its parent, audionode. note: though the audioparam objects re
turned are read-only, the values they represent are not. biquadfilternode.frequency read only is an a-rate audioparam, a double representing a frequency in the current filtering algorithm measured in hertz (hz). biquadfilternode.detune read only is an a-rate audioparam representing detuning of the frequency in cents. biquadfilternode.q read only is an a-rate audioparam, a double representin...
Blob.size - Web APIs
syntax var sizeinbytes = blob.size value the number of bytes of data contained within the blob (or blob-based object, such as a file). example this example uses an <input> element of type file to ask the user for a group of files, then iterates over those files outputting their names and lengths in bytes. ...
Blob.text() - Web APIs
the text() method in the blob interface re
turns a promise that resolves with a string containing the contents of the blob, interpreted as utf-8. syntax var textpromise = blob.text(); blob.text().then(text => /* do something with the text */); var text = await blob.text(); parameters none. re
turns a promise that resolves with a usvstring which contains the blob's data as a text string. the data is always presumed to be in utf-8 format. usage notes the filereader method readastext() is an older method that performs a similar function. it works on both blob and file objects. there are two key differences: blob.text() re
turns a promise, whereas filereader.readastext() is an event based api. blob.text() always uses utf-8 as encoding, while filereader.readastext() can use a differ...
Blob.type - Web APIs
syntax var mimetype = blob.type value a domstring containing the file's mime type, or an empty string if the type could not be determined. example this example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types. ...
BlobEvent.BlobEvent() - Web APIs
syntax blobevent = new blobevent({data: aspecificblob}[, timecode]); arguments the blobevent() constructor also inherits arguments from event(). data is a blob associated with the event. timecode optional a domhighrestimestamp to be used in initializing the blob event. specifications specification status comment mediastream recordingthe definition of 'blobevent: blobevent' in that specification. ...
Bluetooth.getAvailability() - Web APIs
the getavailability() method of bluetooth interface of web bluetooth api interface exposes the bluetooth capabilities of the current device. for a re
turns a boolean which is true if the deveice has a bluetooth adapter and false otherwise (unless user configured user agent not to expose a real value). note: user might not allow use of web bluetooth api, even if getavailability() re
turned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice). also, user can configure user agent to re
turn a fixed value instead of a real one. syntax var readerpromise = bluetooth.getavailability(); parameters none. re
turn value a promise that resolves with boolean. exceptions this method doesn't throw any exceptions. examples the following snippet prints out a message...
Bluetooth.getDevices() - Web APIs
the getdevices() method of bluetooth interface of web bluetooth api exposes the bluetooth devices this origin is allowed to access. this method does not display any permission prompts. note: this method re
turns a bluetoothdevice for each device the origin is currently allowed to access, even the ones that are out of range or powered off. the program can detect when a device comes online or into range by watching for bluetooth advertisements by calling bluetoothdevice.watchadvertisements() on that device. syntax var readerpromise = bluetooth.getdevices(); parameters none. re
turn value a promise that resolves with an array of bluetoothdevices. exceptions this method doesn't throw any exceptions. specifications specification status comment web bluetoothth...
Bluetooth.referringDevice - Web APIs
syntax bluetooth.referringdevice value a bluetoothdevice, if the document was opened in response to an instruction sent by this device and null otherwise. ...
Bluetooth.requestDevice() - Web APIs
parameters options optional an object that sets options for the device request. the available options are: filters[]: an array of bluetoothscanfilters. this filter consists of an array of bluetoothserviceuuids, a name parameter, and a nameprefix parameter. optionalservices[]: an array of bluetoothserviceuuids. ...
BroadcastChannel - Web APIs
naco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">broadcastchannel</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor broadcastchannel() creates an object linking to the named channel. properties this interface also inherits properties from its parent, eventtarget. broadcastchannel.name read only re
turns a domstring, the name of the channel. event handlers broadcastchannel.onmessage an eventhandler property that specifies the function to execute when a message event is fired on this object. broadcastchannel.onmessageerror an eventhandler called when a messageevent of type messageerror is fired—that is, when it receives a message that cannot be deserialized. methods this interface a...
BudgetService - Web APIs
the budgetservice interface of the web budget api provides a programmatic interface to the user agent’s budget service. it is available in both document and worker environments. properties none. methods budgetservice.getcost() re
turns a promise that resolves to a double, indicating the worst-case background operation cost of the provided background operation. budgetservice.getbudget() re
turns a promise that resolves to an array of budgetstate objects, indicating the expected state of the budget at times in the future. budgetservice.reserve() re
turns a promise that resolves to a boolean, indicating whether the requested budget operation can be reserved. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute ...
BudgetState.budgetAt - Web APIs
syntax var budget = budgetstate.budgetat value a double. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
BudgetState.time - Web APIs
syntax var time = budgetstate.time value a timestamp. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
ByteLengthQueuingStrategy - Web APIs
the bytelengthqueuingstrategy interface of the the streams api provides a built-in byte length queuing strategy that can be used when constructing streams. constructor bytelengthqueuingstrategy() creates a new bytelengthqueuingstrategy object instance. properties none. methods bytelengthqueuingstrategy.size() re
turns the given chunk’s bytelength property. examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queueingstrategy); var size = queueingstrategy.size(chunk); specifications specification status comment streamsthe definition of 'bytel...
ByteString - Web APIs
bytestring is a utf-8 string that corresponds to the set of all possible sequences of bytes. bytestring maps to a string when re
turned in javascript; generally, it's only used when interfacing with protocols that use bytes and strings interchangably, such as http. specifications specification status comment web idlthe definition of 'bytestring' in that specification. candidate recommendation initial definition. ...
CSS.registerProperty() - Web APIs
name a domstring indicating the name of the property being defined. syntax optional a domstring representing the expected syntax of the defined property. defaults to "*". inherits a boolean value defining whether the defined property should be inherited (true), or not (false). defaults to false. initialvalue optional a domstring representing the initial value of the defined property. re
turn value undefined. exceptions invalidmodificationerror the given name has already been registered. syntaxerror the given name isn't a valid custom property name (starts with two dashes, e.g. --foo). typeerror the required name and/or inherits dictionary members were not provided. examples the following will register a custom property, --my-color, using registerproperty(), as a color...
CSS.supports() - Web APIs
the css.supports() method re
turns a boolean value indicating if the browser supports a given css feature, or not. syntax css.supports(propertyname, value); css.supports(supportcondition); parameters there are two distinct sets of parameters. the first one allows to test the support of a pair property-value: propertyname a domstring containing the name of the css property to check. value a domstring containing the value of the css property to check. the second syntax takes one parameter matching the condition of @supports: supportcondition a domstring containing the condition to check. re
turn value true if the browser supports the rule, otherwise false. examples result = css.supports("text-decoration-style", "blink"); result = css.supports("display: flex"); result = css.s...
CSS - Web APIs
all the classes related to painting. methods the css interface is a utility interface and no object of this type can be created: only static methods are defined on it. static methods no inherited static methods. css.registerproperty() registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. css.supports() re
turns a boolean indicating if the pair property-value, or the condition, given in parameter is supported. css.escape() can be used to escape a string mostly for use as part of a css selector. css factory functions can be used to re
turn a new cssunitvalue with a value of the parameter number of the units of the name of the factory function method used. css.em(3) // cssunitvalue {value: 3, unit: ...
CSSGroupingRule - Web APIs
ace cssgroupingrule : cssrule { readonly attribute cssrulelist cssrules; unsigned long insertrule (domstring rule, unsigned long index); void deleterule (unsigned long index); } properties common to all cssgroupingrule instances the cssgroupingrule derives from cssrule and inherits all properties of this class. it has one specific property: cssgroupingrule.cssrules read only re
turns a cssrulelist of the css rules in the media rule. methods common to all cssgroupingrule instances the cssgroupingrule derives from cssrule and inherits all methods of this class. it has two specific methods: cssgroupingrule.deleterule deletes a rule from the style sheet. cssgroupingrule.insertrule inserts a new style rule into the current style sheet. specification specifica...
CSSImageValue - Web APIs
100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map. we then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button.computedstylemap(); // re
turn the cssimagevalue example console.log( allcomputedstyles.get('background-image') ); console.log( allcomputedstyles.get('background-image').tostring() ); specifications specification status comment css typed om level 1the definition of 'cssimagevalue' in that specification. working draft initial definition. ...
CSSKeyframeRule - Web APIs
s at-rule. it implements the cssrule interface with a type value of 8 (cssrule.keyframe_rule). properties as a cssrule, csskeyframerule also implements the properties of these interfaces. it has two specific properties: csskeyframe.keytext represents the key of the keyframe, like '10%', '75%'. the from keyword maps to '0%' and the to keyword maps to '100%'. csskeyframe.style read only re
turns a cssstyledeclaration of the css style associated with the keyframe. methods as a cssrule, csskeyframerule also implements the methods of that interface. it has no specific methods. specification specification status comment css animationsthe definition of 'csskeyframerule' in that specification. working draft initial definition ...
CSSKeywordValue.CSSKeywordValue() - Web APIs
examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. ...
CSSKeywordValue.value - Web APIs
syntax var val = csskeywordvalue.value csskeywordvalue.value = val value a usvstring. examples the following example resets the css display property to its defaults. ...
CSSNumericValue.type - Web APIs
the type() method of the cssnumericvalue interface re
turns the type of cssnumericvalue, one of angle, flex, frequency, length, resolution, percent, percenthint, or time. syntax var cssnumerictype = cssnumericvalue.type(); parameters none. re
turn value a cssnumerictype object. exceptions none. examples let mathsum = css.px("23").sub(css.percent("4")).sub(css.cm("3")).sub(css.in("9")); // re
turns an object with the structure: {length: 1, percenthint: "length"} let cssnumerictype = mathsum.type(); specifications specification status comment css typed om level 1the definition of 'type' in that specification. working draft initial definition. ...
CSSNumericValue - Web APIs
w csstranslate cssunitvalue properties none. event handlers no methods cssnumericvalue.add adds a supplied number to the cssnumericvalue. cssnumericvalue.sub subtracts a supplied number from the cssnumericvalue. cssnumericvalue.mul multiplies the cssnumericvalue by the supplied value. cssnumericvalue.div divides the cssnumericvalue by the supplied value. cssnumericvalue.min re
turns the minimum value passed cssnumericvalue.max re
turns the maximum value passed cssnumericvalue.equals true if all the values are the exact same type and value, in the same order. otherwise, false. cssnumericvalue.to converts value into another one with the specified unit. cssnumericvalue.tosum tbd cssnumericvalue.type tbd cssnumericvalue.parse allows a cssnumericvalue to be constructe...
CSSPageRule - Web APIs
ebidl format. interface csspagerule : cssrule { attribute domstring selectortext; readonly attribute cssstyledeclaration style; }; properties as a cssrule, csspagerule also implements the properties of this interface. it has the following specific properties: csspagerule.selectortext represents the text of the page selector associated with the at-rule. csspagerule.style read only re
turns the declaration block associated with the at-rule. methods as a cssrule, csspagerule also implements the methods of that interface. it has no specific methods. specifications specification status comment css object model (cssom)the definition of 'csspagerule' in that specification. working draft no changes from document object model (dom) level 2 style spec...
CSSPositionValue.x - Web APIs
syntax var x = csspositionvalue.x value a cssnumericvalue. example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. ...
CSSPositionValue.y - Web APIs
syntax var y = csspositionvalue.y value a cssnumericvalue. example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. ...
CSSPrimitiveValue.getCounterValue() - Web APIs
the getcountervalue() method of the cssprimitivevalue interface is used to get the counter value. if this css value doesn't contain a counter value, a domexception is raised. modification to the corresponding style property can be achieved using the counter interface. syntax var countervalue = cssprimitivevalue.getcountervalue(); re
turn value a counter object representing the counter value. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a counter value (e.g. this is not css_counter). specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getcountervalue' in that specification. obsolete ...
CSSPrimitiveValue.getRGBColorValue() - Web APIs
the getrgbcolorvalue() method of the cssprimitivevalue interface is used to get an rgb color value. if this css value doesn't contain a rgb color value, a domexception is raised. modification to the corresponding style property can be achieved using the rgbcolor interface. syntax var rgbcolorvalue = cssprimitivevalue.getrgbcolorvalue(); re
turn value an rgbcolor object representing the color value. exceptions type description domexception an invalid_access_err is raised if the attached property can't re
turn an rgb color value (i.e. this is not css_rgbcolor). example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("color"); console.log(cssvalue.getrgbcolorvalue()); specifications specification status ...
CSSPrimitiveValue.getRectValue() - Web APIs
the getrectvalue() method of the cssprimitivevalue interface is used to get a rect value. if this css value doesn't contain a rect value, a domexception is raised. modification to the corresponding style property can be achieved using the rect interface. syntax var rectvalue = cssprimitivevalue.getrectvalue(); re
turn value a rect object representing the rect value. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a rect value. (i.e. this is not css_rect). example var cs = window.getcomputedstyle(document.getelementbyid("clippeddiv")); var cssvalue = cs.getpropertycssvalue("clip"); console.log(cssvalue.getrectvalue()); specifications specification status comment document...
CSSPrimitiveValue.setStringValue() - Web APIs
an unsigned short representing the type of the value. possible values are: constant description css_attr the value is an attr() function. css_ident the value is an identifier. css_string the value is a <string>. css_uri the value is a <uri>. stringvalue a domstring representing the new string value. re
turn value void. exceptions type description domexception an invalid_access_err is raised if the css value doesn't contain a string value or if the string value can't be converted into the specified unit. an no_modification_allowed_err is raised if this property is read-only. specifications specification status comment document object ...
CSSPseudoElement.type - Web APIs
the type read-only property of the csspseudoelement interface re
turns the type of the pseudo-element as a string, represented in the form of a css selector. syntax var typeofpseudoelement = csspseudoelement.type; value a cssomstring containing one of the following values: "::before" "::after" "::marker" examples the example below demonstrates the relationship between csspseudoelement.type and element.pseudo(): const myelement = document.queryselector('q'); const myselector = '::after'; const csspseudoelement = myelement.pseudo(myselector); const typeofpseudoelement = csspseudoelement.type; console.log(myselector === typeofpseudoelement); // outputs true specifications specification status comment css pseudo-elements level 4the definition of 'type' i...
CSSPseudoElement - Web APIs
the csspseudoelement interface represents a pseudo-element that may be the target of an event or animated using the web animations api. instances of this interface may be obtained by calling element.pseudo(). properties csspseudoelement.element read only re
turns the originating/parent element of the pseudo-element. csspseudoelement.type read only re
turns the pseudo-element selector as a cssomstring. methods csspseudoelement extends eventtarget, so it inherits the following methods: eventtarget.addeventlistener() registers an event handler of a specific event type on the pseudo-element. eventtarget.dispatchevent() dispatches an event to this pseudo-element. eventtarget.removeeventlistener() removes an event listener from the pseudo-element. examples basic example u...
CSSRule.cssText - Web APIs
note: do not confuse this property with element-style cssstyledeclaration.csstext. be aware that this property can no longer be set directly, as it is now specified to be functionally modify-only, and silently so. in other words, attempting to set it does absolutely nothing, and doesn't even omit a warning or error. furthermore, it has no settable sub-properties. therefore, to modify it, use the stylesheet's cssrules[index] properties .selectortext and .style (or its sub-properties). see using dynamic styling information for details. ...
CSSRule - Web APIs
looking at a cssstylesheet's cssrules list. properties common to all cssrule instances cssrule.csstext represents the textual representation of the rule, e.g. "h1,h2 { font-size: 16pt }" or "@import 'url'". to access or modify parts of the rule (e.g. the value of "font-size" in the example) use the properties on the specialized interface for the rule's type. cssrule.parentrule read only re
turns the containing rule, otherwise null. e.g. if this rule is a style rule inside an @media block, the parent rule would be that cssmediarule. cssrule.parentstylesheet read only re
turns the cssstylesheet object for the style sheet that contains this rule cssrule.type read only one of the type constants indicating the type of css rule. constants type constants the cssrule interface specifie...
CSSRuleList - Web APIs
stylesheet.cssrules is read-only), but it must unfortunately be inserted into one, rule by rule, and unless combining lists, after any existing list therein is deleted, rule by rule. example // get the first style sheet’s first rule var first_rule = document.stylesheets[0].cssrules[0]; see also cssrule cssrulelist implementations there are multiple properties in the cssom that will re
turn a cssrulelist. they are: cssstylesheet property cssrules cssmediarule property cssrules csskeyframesrule property cssrules cssmozdocumentrule property cssrules specifications specification status comment css object model (cssom)the definition of 'cssrulelist' in that specification. working draft ...
CSSStyleDeclaration.cssText - Web APIs
to be able to set a stylesheet rule dynamically, see using dynamic styling information. not to be confused with stylesheet style-rule cssrule.csstext. ...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
the cssstyledeclaration.getpropertycssvalue() method interface re
turns a cssvalue containing the css value for a property. note that it re
turns null if the property name is a shorthand property. you should use cssstyledeclaration.getpropertyvalue() instead. syntax var value = style.getpropertycssvalue(property); parameters property is a domstring representing the property name to be retrieved. re
turn value value is a cssvalue containing the css value for a property. if none exists, re
turns null. example the following javascript code gets an object containing the computed rgb values of the color css property: var style = window.getcomputedstyle(elem, null); var rgbobj = style.getpropertycssvalue('color').getrgbcolorvalue(); specifications specification status ...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
the cssstyledeclaration.getpropertypriority() method interface re
turns a domstring that provides all explicitly set priorities on the css property. syntax var priority = style.getpropertypriority(property); parameters property is a domstring representing the property name to be checked. re
turn value priority is a domstring that represents the priority (e.g. "important") if one exists. if none exists, re
turns the empty string. example the following javascript code checks whether margin is marked as important in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition...
CSSStyleDeclaration.getPropertyValue() - Web APIs
the cssstyledeclaration.getpropertyvalue() method interface re
turns a domstring containing the value of a specified css property. syntax var value = style.getpropertyvalue(property); parameters property is a domstring representing the property name to be checked. re
turn value value is a domstring containing the value of the property. if not set, re
turns the empty string. example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification. w...
CSSStyleDeclaration.length - Web APIs
syntax var num = styles.length; value an integer that provides the number of styles explictly set on the parent of the instance. example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification. ...
CSSStyleDeclaration.parentRule - Web APIs
a cssstylerule representing the style for a css selector. syntax var rule = styles.parentrule; value the css rule that contains this declaration block or null if this cssstyledeclaration is not attached to a cssrule. example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification. ...
CSSStyleDeclaration.removeProperty() - Web APIs
the cssstyledeclaration.removeproperty() method interface removes a property from a css style declaration object. syntax var oldvalue = style.removeproperty(property); parameters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. re
turn value oldvalue is a domstring equal to the value of the css property before it was removed. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specifica...
CSSStyleRule - Web APIs
cssstylerule represents a single css style rule. it implements the cssrule interface with a type value of 1 (cssrule.style_rule). properties cssstylerule.selectortext re
turns the textual representation of the selector for this rule, e.g. "h1,h2". cssstylerule.style read only re
turns the cssstyledeclaration object for the rule. cssstylerule.stylemap read only re
turns a stylepropertymap object which provides access to the rule's property-value pairs. specifications specification status comment css object model (cssom)the definition of 'cssstylerule' in that specification. working draft no changes document object model (dom) level 2 style specificationthe definition of 'cssrule' in that specification. obsolete ...
CSSStyleSheet.addRule() - Web APIs
ng undefined. styleblock a domstring indicating the style block to apply to elements matching the selector. the default is the string undefined. index optional an optional index into the stylesheet's cssrulelist at which to insert the new rule. if index is not specified, the next index after the last item currently in the list is used (that is, the value of cssstylesheet.cssrules.length). re
turn value always re
turns -1. note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. see insertrule() for more information. usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method. therefore, ...
CSSStyleSheet.cssRules - Web APIs
each item in the list is a cssrule defining a single rule. syntax var rules = cssstylesheet.cssrules; value a live-updating cssrulelist containing each of the css rules making up the stylesheet. each entry in the rule list is a cssrule object describing one rule making up the stylesheet. ...
CSSStyleSheet.deleteRule() - Web APIs
the cssstylesheet method deleterule() removes a rule from the stylesheet object. syntax cssstylesheet.deleterule(index) parameters index the index into the stylesheet's cssrulelist indicating the rule to be removed. re
turn value undefined example this example removes the first rule from the stylesheet mystyles. mystyles.deleterule(0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.deleterule()' in that specification. working draft ...
CSSStyleSheet.removeRule() - Web APIs
overule() removes a rule from the stylesheet object. it is functionally identical to the standard, preferred method deleterule(). note: this is a legacy method which has been replaced by the standard method deleterule(). you should use that instead. syntax cssstylesheet.removerule(index) parameters index the index into the stylesheet's cssrulelist indicating the rule to be removed. re
turn value undefined example this example removes the first rule from the stylesheet mystyles. mystyles.removerule(0); you can rewrite this to use the standard deleterule() method very easily: mystyles.deleterule(0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.removerule()' in that specification. working draf...
CSSStyleValue.parse() - Web APIs
the parse() method of the cssstylevalue interface sets a specific css property to the specified values and re
turns the first value as a cssstylevalue object. syntax cssstylevalue.parse(property, csstext) parameters property a css property to set. csstext a comma-separated string containing one or more values to apply to the provided property. re
turn value a cssstylevalue object containing the first supplied value. example the code below parses a set of declarations for the transform property. the second code block shows the structure of the re
turned object as it would be rendered in a developer tools console. const css = cssstylevalue.parse( 'transform', 'translate3d(10px,10px,0) scale(0.5)'); csstransformvalue {0: csstranslate, 1: cssscale, length: 2, is2d: false} spec...
CSSStyleValue.parseAll() - Web APIs
the parseall() method of the cssstylevalue interface sets all occurences of a specific css property to the specified value and re
turns an array of cssstylevalue objects, each containing one of the supplied values. syntax cssstylevalue.parseall(property, value) parameters property a css property to set. csstext a comma-separated string containing one or more values that apply to the provided property. re
turn value an array of cssstylevalue objects, each containing one of the supplied values. specifications specification status comment css typed om level 1the definition of 'parseall()' in that specification. working draft initial definition. ...
CSSStyleValue - Web APIs
rough the typed om api. an instance of this class may be used anywhere a string is expected. interfaces based on cssstylevalue below is a list of interfaces based on the cssstylevalue interface. cssimagevalue csskeywordvalue cssnumericvalue csspositionvalue csstransformvalue cssunparsedvalue methods cssstylevalue.parse() sets a specific css property to the specified values and re
turns the first value as a cssstylevalue object. cssstylevalue.parseall() sets all occurences of a specific css property to the specified valueand re
turns an array of cssstylevalue objects, each containing one of the supplied values. specifications specification status comment css typed om level 1the definition of 'cssstylevalue' in that specification. working draft ...
CSSUnitValue.unit - Web APIs
syntax var astring = cssunitvalue.unit; value a usvstring. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit. ...
CSSUnitValue.value - Web APIs
syntax var cssunitvalue = cssunitvalue.value; cssunitvalue.value = cssunitvalue; value a double. examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value. ...
CSSUnparsedValue.forEach() - Web APIs
eters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed. indexoptional the index of the current element being processed. arrayoptional the cssunparsedvalue that foreach() is being called on. thisarg optional value to use as this (i.e the reference object) when executing callback. re
turn value undefined. specifications specification status comment css typed om level 1the definition of 'foreach()' in that specification. working draft initial definition. ...
CSSValueList.item() - Web APIs
the item() method of the cssvaluelist interface is used to retrieve a cssvalue by ordinal index. the order in this collection represents the order of the values in the css style property. if the index is greater than or equal to the number of values in the list, this method re
turns null. syntax var cssvalue = cssvaluelist.item(index); parameters index an unsigned long representing the index of the css value within the collection. re
turn value a cssvalue object at the index position in the cssvaluelist, or null if that is not a valid index. specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssvaluelist.item' in that specification. obsolete initial definition ...
CSSValueList - Web APIs
perties from its parent, cssvalue. cssvaluelist.lengthread only an unsigned long representing the number of cssvalues in the list. methods cssvaluelist.item() this method is used to retrieve a cssvalue by ordinal index. the order in this collection represents the order of the values in the css style property. if index is greater than or equal to the number of values in the list, this re
turns null. specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssvalueslist' in that specification. obsolete initial definition ...
CSSVariableReferenceValue - Web APIs
del api allows you to create a custom name for a built-in css value. this object functionality is sometimes called a "css variable" and serves the same purpose as the var() function. the custom name must begin with two dashes. constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a new cssvariablereferencevalue object. properties cssvariablereferencevalue.variable re
turns the custom name passed to the constructor. cssvariablereferencevalue.fallback read only re
turns the built-in css value for the custom name. methods none. specifications specification status comment css typed om level 1the definition of 'cssvariablereferencevalue' in that specification. working draft initial definition. ...
CanvasCaptureMediaStreamTrack.canvas - Web APIs
syntax var elt = stream.canvas; value an htmlcanvaselement indicating the canvas which is the source of the frames being captured. example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream ... ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
t to the stream. applications that need to carefully control the timing of rendering and frame capture can use requestframe() to directly specify when it's time to capture a frame. to prevent automatic capture of frames, so that frames are only captured when requestframe() is called, specify a value of 0 for the capturestream() method when creating the stream. syntax stream.requestframe(); re
turn value undefined usage notes there is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. this may change in the future, so it would be wise to plan ahead and watch for exceptions such as securityerror (although the specific error that might be thrown is not mentioned in the spec, this is a likely candi...
CanvasCaptureMediaStreamTrack - Web APIs
the canvascapturemediastreamtrack interface represents the video track contained in a mediastream being generated from a <canvas> following a call to htmlcanvaselement.capturestream(). part of the media capture and streams api. properties this interface inherits the properties of its parent, mediastreamtrack. canvascapturemediastreamtrack.canvas read only re
turns the htmlcanvaselement object whose surface is captured in real-time. methods this interface inherits the methods of its parent, mediastreamtrack. canvascapturemediastreamtrack.requestframe() manually forces a frame to be captured and sent to the stream. this lets applications that wish to specify the frame capture times directly do so, if they specified a framerate of 0 when calling capturestream(). specifications ...
CanvasGradient - Web APIs
it can be used as a fillstyle or strokestyle. properties as an opaque object, there is no exposed property. methods there is no inherited method. canvasgradient.addcolorstop() adds a new stop, defined by an offset and a color, to the gradient. if the offset is not between 0 and 1, inclusive, an index_size_err is raised; if the color can't be parsed as a css <color>, a syntax_err is raised. ...
CanvasRenderingContext2D.clip() - Web APIs
it replaces any previous clipping region. in the image below, the red outline represents a clipping region shaped like a star. only those parts of the checkerboard pattern that are within the clipping region get drawn. note: be aware that the clipping region is only constructed from shapes added to the path. it doesn't work with shape primitives drawn directly to the canvas, such as fillrect(). instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). ...
CanvasRenderingContext2D.createImageData() - Web APIs
ctx.createimagedata(imagedata); parameters width the width to give the new imagedata object. a negative value flips the rectangle around the vertical axis. height the height to give the new imagedata object. a negative value flips the rectangle around the horizontal axis. imagedata an existing imagedata object from which to copy the width and height. the image itself is not copied. re
turn value a new imagedata object with the specified width and height. the new object is filled with transparent black pixels. errors thrown indexsizeerror thrown if either of the width or height arguments is zero. examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method. html <canvas id="canvas"></canvas> javascript the...
CanvasRenderingContext2D.currentTransform - Web APIs
syntax ctx.currenttransform [= value]; value a dommatrix or svgmatrix object to use as the current transformation matrix. examples manually changing the matrix this example uses the currenttransform property to set a transformation matrix. a rectangle is then drawn using that transformation. ...
CanvasRenderingContext2D.fillText() - Web APIs
e maximum number of pixels wide the text may be once rendered. if not specified, there is no limit to the width of the text. however, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. re
turn value undefined. examples drawing filled text this example writes the words "hello world" using the filltext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'...
CanvasRenderingContext2D.getLineDash() - Web APIs
if the number, when setting the elements, is odd, the elements of the array get copied and concatenated. for example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. examples getting the current line dash setting this example demonstrates the getlinedash() method. ...
CanvasRenderingContext2D.getTransform() - Web APIs
the canvasrenderingcontext2d.gettransform() method of the canvas 2d api retrieves the current transformation matrix being applied to the context. syntax let storedtransform = ctx.gettransform(); parameters none. re
turn value a dommatrix object. the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] note: the re
turned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already re
turned dommatrix. examples in the following example, we have two <canvas> elements. we apply a transform to the first one's context using canvasrenderingcontext2d.settransform() and draw a square on it, then retrieve the matrix ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
. y the y-axis coordinate of the point to check, unaffected by the current transformation of the context. fillrule the algorithm by which to determine if a point is inside or outside the path. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to check against. if unspecified, the current path is used. re
turn value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false. examples checking a point in the current path this example uses the ispointinpath() method to check if a point is within the current path. html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.gete...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
oke() method of the canvas 2d api reports whether or not the specified point is inside the area contained by the stroking of a path. syntax ctx.ispointinstroke(x, y); ctx.ispointinstroke(path, x, y); parameters x the x-axis coordinate of the point to check. y the y-axis coordinate of the point to check. path a path2d path to check against. if unspecified, the current path is used. re
turn value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. examples checking a point in the current path this example uses the ispointinstroke() method to check if a point is within the area of the current path's stroke. html <canvas id="canvas"></canvas> <p>in stroke: <code id="result">false</code></p> javascript cons...
CanvasRenderingContext2D.lineTo() - Web APIs
h by connecting the sub-path's last point to the specified (x, y) coordinates. like other methods that modify the current path, this method does not directly render anything. to draw the path onto a canvas, you can use the fill() or stroke() methods. syntax ctx.lineto(x, y); parameters x the x-axis coordinate of the line's end point. y the y-axis coordinate of the line's end point. re
turn value undefined. examples drawing a straight line this example draws a straight line using the lineto() method. html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100). const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); // start a new path ctx.moveto(30, 50); // move the pen to (30, 5...
CanvasRenderingContext2D.putImageData() - Web APIs
javascript const canvas = document.createelement("canvas"); canvas.width = 1; canvas.height = 1; const context = canvas.getcontext("2d"); const imgdata = context.getimagedata(0, 0, canvas.width, canvas.height); const pixels = imgdata.data; pixels[0 + 0] = 1; pixels[0 + 1] = 127; pixels[0 + 2] = 255; pixels[0 + 3] = 1; console.log("before:"...
CanvasRenderingContext2D.setLineDash() - Web APIs
the setlinedash() method of the canvas 2d api's canvasrenderingcontext2d interface sets the line dash pattern used when stroking lines. it uses an array of values that specify alternating lengths of lines and gaps which describe the pattern. note: to re
turn to using solid lines, set the line dash list to an empty array. syntax ctx.setlinedash(segments); parameters segments an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). if the number of elements in the array is odd, the elements of the array get copied and concatenated. for example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. if the array is empty, the line dash list is cleared and line strokes re
turn to being solid. re
turn value undefined. examples basic example...
CanvasRenderingContext2D.strokeText() - Web APIs
dth optional the maximum width the text may be once rendered. if not specified, there is no limit to the width of the text. however, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. re
turn value undefined. examples drawing text outlines this example writes the words "hello world" using the stroketext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('ca...
Compositing and clipping - Web APIs
t differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding new shapes. this makes clipping paths ideal for drawing multiple shapes in a restricted area. in the chapter about drawing shapes i only mentioned the stroke() and fill() methods, but there's a third method we can use with paths, called clip(). clip()
turns the path currently being built into the current clipping path. you use clip() instead of closepath() to close a path and
turn it into a clipping path instead of stroking or filling the path. by default the <canvas> element has a clipping path that's the exact same size as the canvas itself. in other words, no clipping occurs. a clip example in this example, we'll use a circular clipping pat...
Drawing shapes with canvas - Web APIs
n the last example, there can be a series of paths and drawing commands to draw objects onto your canvas. to simplify the code and to improve performance, the path2d object, available in recent versions of browsers, lets you cache or record these drawing commands. you are able to play back your paths quickly. let's see how we can construct a path2d object: path2d() the path2d() constructor re
turns a newly instantiated path2d object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of svg path data. new path2d(); // empty path object new path2d(path); // copy from another path2d object new path2d(d); // path from svg path data all path methods like moveto, rect, arc or quadraticcurveto, etc., which we got to know above, are avai...
Drawing text - Web APIs
ntlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); advanced text measurements in the case you need to obtain more details about the text, the following method allows you to measure it. measuretext() re
turns a textmetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style. the following code snippet shows how you can measure a text and get its width. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); var text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; } gecko-specific notes in g...
Optimizing canvas - Web APIs
cale the canvas, or have a smaller canvas and scale up rather than a bigger canvas and scale down. var scalex = window.innerwidth / canvas.width; var scaley = window.innerheight / canvas.height; var scaletofit = math.min(scalex, scaley); var scaletocover = math.max(scalex, scaley); stage.style.transformorigin = '0 0'; //scale from top left stage.style.transform = 'scale(' + scaletofit + ')';
turn off transparency if your application uses canvas and doesn’t need a transparent backdrop, set the alpha option to false when creating a drawing context with htmlcanvaselement.getcontext(). this information can be used internally by the browser to optimize rendering. var ctx = canvas.getcontext('2d', { alpha: false }); more tips batch canvas calls together. for example, draw a polyline ins...
Using images - Web APIs
ded url can become quite long. using frames from a video you can also use frames from a video being presented by a <video> element (even if the video is not visible). for example, if you have a <video> element with the id "myvideo", you can do this: function getmyvideo() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); re
turn document.getelementbyid('myvideo'); } } this re
turns the htmlvideoelement object for the video, which, as covered earlier, is one of the objects that can be used as a canvasimagesource. drawing images once we have a reference to our source image object we can use the drawimage() method to render it to the canvas. as we will see later the drawimage() method is overloaded and has several vari...
CaretPosition - Web APIs
the caretposition interface represents the caret position, an indicator for the text insertion point. you can get a caretposition using the document.caretpositionfrompoint method. properties this interface doesn't inherit any properties. caretposition.offsetnode read only re
turns a node containing the found node at the caret's position. caretposition.offset read only re
turns a long representing the character offset in the caret position node. methods caretposition.getclientrect specification specification status comment css object model (cssom) view modulethe definition of 'caretposition' in that specification. working draft ...
ChannelMergerNode() - Web APIs
ing the audio context you want the node to be associated with. options optional a channelmergeroptions dictionary object defining the properties you want the channelmergernode to have (also inherits parameters from the audionodeoptions dictionary): numberofinputs: a number defining the number of inputs the channelmergernode should have. if not specified, the default value used is 6. re
turn value a new channelmergernode object instance. exceptions invalidstateerror an option such as channelcount or channelcountmode has been given an invalid value. example var ac = new audiocontext(); var options = { numberofinputs : 2 } var mymerger = new channelmergernode(ac, options); specifications specification status comment web audio apithe definition of ...
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
text you want the node to be associated with. options optional a channelsplitteroptions dictionary object defining the properties you want the channelsplitternode to have (it also inherits the options defined in the audionodeoptions dictionary): numberofoutputs: a number defining the number of inputs the channelsplitternode should have. if not specified, the default value used is 6. re
turn value a new channelsplitternode object instance. example var ac = new audiocontext(); var options = { numberofoutputs : 2 } var mysplitter = new channelsplitternode(ac, options); specifications specification status comment web audio apithe definition of 'channelsplitternode' in that specification. working draft ...
Using channel messaging - Web APIs
a list item and insert it in the unordered list, setting the textcontent of the list item equal to the event's data attribute (this contains the actual message). next, we post a confirmation message back to the main page via the message channel by calling messageport.postmessage on messagechannel.port2 that was initially transferred to the iframe. receiving the confirmation in the main page re
turning to the main page, let's now look at the onmessage handler function. // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } when a message is received back from the iframe confirming that the original message was received successfully, this simply outputs the confirmation to a paragraph and empties the text input ready for the next mess...
Channel Messaging API - Web APIs
y, passing messages between one another through two-way channels (or pipes) with a port at each end. note: this feature is available in web workers. channel messaging concepts and usage a message channel is created using the messagechannel() constructor. ...
Client.id - Web APIs
the id read-only property of the client interface re
turns the universally unique identifier of the client object. syntax var clientid = client.id; example tbd specifications specification status comment service workersthe definition of 'id' in that specification. working draft initial definition. ...
Client.type - Web APIs
the type read-only property of the client interface indicates the type of client the service worker is controlling. syntax var myclienttype = client.type; value a string, representing the client type. the value can be one of "window" "worker" "sharedworker" example // service worker client (e.g. ...
Clients.claim() - Web APIs
controlled by this service worker. when a service worker is initially registered, pages won't use it until they next load. the claim() method causes those pages to be controlled immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. re
turn value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addeventlistener('activate', event => { event.waituntil(clients.claim()); }); specifications specification stat...
Clients.get() - Web APIs
the get() method of the clients interface gets a service worker client matching a given id and re
turns it in a promise. syntax self.clients.get(id).then(function(client) { // do something with your re
turned client }); parameters id a domstring representing the id of the client you want to get. re
turn value a promise that resolves to a client object or undefined. examples self.clients.get(id).then(function(client) { self.clients.openwindow(client.url); }); specifications specification status comment service workersthe definition of 'get()' in that specification. working draft initial definition ...
Clients.openWindow() - Web APIs
b app previously added to the user's home screen. as of recently, this also works on chrome for windows. syntax self.clients.openwindow(url).then(function(windowclient) { // do something with your windowclient }); parameters url a usvstring representing the url of the client you want to open in the window. generally this value must be a url from the same origin as the calling script. re
turn value a promise that resolves to a windowclient object if the url is from the same origin as the service worker or a null value otherwise. examples // send notification to os if applicable if (self.notification.permission === 'granted') { const notificationobject = { body: 'click here to view your messages.', data: { url: self.location.origin + '/some/path' }, // data: { url: ...
Clipboard.read() - Web APIs
the read() method of the clipboard interface requests a copy of the clipboard's contents, delivering the data to the re
turned promise when the promise is resolved. unlike readtext(), the read() method can re
turn arbitrary data, such as images. this method can also re
turn 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. re
turn value a promise that resolves with a datatransfer object containing the clipboard's contents. th...
Clipboard.write() - Web APIs
e 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.write(data) parameters data an array of clipboarditem objects containing data to be written to the clipboard. re
turn value a promise which is resolved when the data has been written to the clipboard. the promise is rejected if the clipboard is unable to complete the clipboard access. example this example function replaces the current contents of the clipboard with a specified string. function setclipboard(text) { let data = [new clipboarditem({ "text/plain": text })]; navigator.clipboard.write(data).th...
Clipboard.writeText() - Web APIs
ages 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. re
turn 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 to write to the clipboard. example this example sets the clipboard's contents to the string "<empty clipboard>". navigator.clipboard.writetext("<empty clipboard>").then(function() { /* clipboard successfully set */ }, function() { /* clipboar...
ClipboardEvent() - Web APIs
syntax var clipboardevent = new clipboardevent(type[, options]); parameters the clipboardevent() constructor also inherits arguments from event(). type is a domstring representing the name of the type of the clipboardevent. it is case-sensitive and can be: 'copy', 'cut', or 'paste'. options optional options are as follows: clipboarddata: a datatransfer containing the data concerned by the clipboard event. datatype : a domstring containing the mime-type of the data contained in the data argument. ...
ClipboardItem() - Web APIs
ty table for the clipboard interface. syntax var clipboarditem = new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. 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. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ ...
ClipboardItem.getType() - Web APIs
the gettype() method of the clipboarditem interface re
turns a promise that resolves with a blob of the requested mime type or an error if the mime type is not found. syntax var blob = clipboarditem.gettype(type); parameters type a valid mime type. re
turn value a promise that resolves with a blob 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 re
turning all items on the clipboard via the clipboard.read() method. then utilizing the clipboarditem.types property to set the gettype() argument and re
turn the corresponding blob object. async function getclipboardcontents() { try { const clipboarditems = await navig...
ClipboardItem.types - Web APIs
the read-only types property of the clipboarditem interface re
turns an array of mime types available within the clipboarditem syntax var types = clipboarditem.types; value an array of available mime types. examples in the below example, we're re
turning 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 re
turn the blob object. if no clipboards contents is found for the specified type, an error is re
turned. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(ty...
Clipboard API - Web APIs
of creating a clipboard object through instantiation, you access the system clipboard through the navigator.clipboard global: navigator.clipboard.readtext().then( cliptext => document.queryselector(".editor").innertext += cliptext); this snippet fetches the text from the clipboard and appends it to the first element found with the class editor. since readtext() (and read(), for that matter) re
turns 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 ...
Comment() - Web APIs
syntax comment1 = new comment(); // create an empty comment comment2 = new comment("this is a comment"); example var comment = new comment("test"); specifications specification status comment domthe definition of 'comment: comment' in that specification. ...
Comment - Web APIs
.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">comment</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no specific property, but inherits those of its parent, characterdata, and indirectly those of node. constructor comment() re
turns a comment object with the parameter as its textual content. methods this interface has no specific method, but inherits those of its parent, characterdata, and indirectly those of node. specifications specification status comment domthe definition of 'comment' in that specification. living standard added the constructor. document object model (dom) lev...
CompositionEvent.data - Web APIs
syntax mydata = compositionevent.data value a domstring representing the event data: for compositionstart events, this is the currently selected text that will be replaced by the string being composed. this value doesn't change even if content changes the selection range; rather, it indicates the string that was selected when composition started. for compositionupdate, this is the string as it stands currently as editing is ongoing. ...
CompositionEvent.initCompositionEvent() - Web APIs
sitionstart, compositionupdate, or compositionend. canbubblearg a boolean specifying whether or not the event can bubble. cancelablearg a boolean shether or not the event can be canceled. viewarg the window object from which the event was generated. dataarg a domstring representing the value of the data attribute. localearg a domstring representing the value of the locale attribute. re
turn value void. specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'initcompositionevent()' in that specification. obsolete initial definition. ...
CompositionEvent - Web APIs
pace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">compositionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor compositionevent() creates a new compositionevent object instance. properties this interface also inherits properties of its parent, uievent, and its ancestor — event. compositionevent.data read only re
turns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the compositionevent object. compositionevent.locale read only re
turns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime). methods this interface also inherits methods of its parent, uievent, and i...
Console.timeLog() - Web APIs
logs the current value of a timer that was previously started by calling console.time() to the console. see timers in the documentation for details and examples. note: this feature is available in web workers. syntax console.timelog(label); parameters label the name of the timer to log to the console. re
turn if no label parameter included: default: 1042ms if an existing label is included: timer name: 1242ms exceptions if there is no running timer, timelog() re
turns the warning: timer “default” doesn’t exist. if a label parameter is included, but there is no corresponding timer: timer “timer name” doesn’t exist. examples console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.ti...
ConstantSourceNode - Web APIs
value of its offset or by connecting another node to it; see controlling multiple parameters with constantsourcenode. a constantsourcenode has no inputs and exactly one monaural (one-channel) output. the output's value is always the same as the value of the offset parameter. number of inputs 0 number of outputs 1 constructor constantsourcenode() creates and re
turns a new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties. you can also create a constantsourcenode whose properties are initialized to their default values by calling audiocontext.createconstantsource(). properties inherits properties from its parent interface, audioscheduledsourcenode, and adds the following properties: ...
ContentIndexEvent - Web APIs
to represent the contentdelete event. this event is sent to the global scope of a serviceworker. it contains the id of the indexed content to be removed. the contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface. it is not fired when the contentindex.delete method is called. constructor contentindexevent() creates and re
turns a new contentindexevent object whose type and other options are configured as specified. properties in addition to the properties listed below, this interface inherits the properties of its parent interface, extendableevent. id read only a string which identifies the deleted content index via it's id. methods while contentindexevent offers no methods of its own, it inherits any sp...
ConvolverNode() - Web APIs
context. options optional options are as follows: audiobuffer: a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect. disablenormalization: a boolean controlling whether the impulse response from the buffer will be scaled by an equal-power normalization, or not. the default is 'false'. re
turn value a new convolvernode object instance. exceptions exception explanation notsupportederror the referenced audiobuffer does not have the correct number of channels, or it has a different sample rate to the associated audiocontext. specifications specification status comment web audio apithe definition of 'convolvernode()' in that sp...
ConvolverNode - Web APIs
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); re
turn convolver; } ... let reverb = await createreverb(); // someotheraudionode -> reverb -> destination someotheraudionode.connect(reverb); reverb.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'convolvernode' in that specification. working draft ...
CountQueuingStrategy - Web APIs
the countqueuingstrategy interface of the the streams api provides a built-in chunk counting queuing strategy that can be used when constructing streams. constructor countqueuingstrategy() creates a new countqueuingstrategy object instance. properties none. methods countqueuingstrategy.size() re
turns 1. examples const queueingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink error:", err); } }, queueingstrategy); var size = queueingstrategy.size(); specifications specification status comment streamsthe definition of 'countqueuingstrategy' in that specification. living standar...
CrashReportBody - Web APIs
a crash report is generated when a document becomes unusable due to the browser (or one of its processes) crashing. for security reasons, no details of the crash are communicated in the body except for a general crash reason. properties reason a string representing the reason for the crash. current possible reasons are: oom: the browser ran out of memory. unresponsive: the page was killed due to being unresponsive. examples crash reports are generally only retrievable via endpoints set up using the report-to header. ...
Credential.id - Web APIs
this might be any one of a guid, username, or email address. syntax var id = credential.id; value a a domstring containing the credential's identifier. ...
Credential.name - Web APIs
it should be a human-readable, public name. syntax var credname = credential.name; value a domstring containing the credential's given name. ...
Credential.type - Web APIs
valid values are password, federated and public-key. syntax var credtype = credential.type; value a domstring contains a credential's given name. ...
CredentialsContainer.store() - Web APIs
the store() method of the credentialscontainer stores a set of credentials for the user inside a credential instance, re
turning this in a promise. this method is restricted to top-level contexts. calls to it within an <iframe> element will resolve without effect. syntax credentialscontainer.store(credential).then(function(credential) { ... } ) parameters credentials a valid credential instance. re
turns a promise, resolving to the passed credential instance. example // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
Crypto.getRandomValues() - Web APIs
py source. getrandomvalues() is the only member of the crypto interface which can be used from an insecure context. syntax typedarray = cryptoobj.getrandomvalues(typedarray); parameters typedarray an integer-based typedarray, that is an int8array, a uint8array, an int16array, a uint16array, an int32array, or a uint32array. all elements in the array are overwritten with random numbers. re
turn value the same array passed as typedarray but with its contents replaced with the newly generated random numbers. note that typedarray is modified in-place, and no copy is made. exceptions this method can throw an exception under error conditions. domexception (name: quotaexceedederror) the requested length exceeds 65,536 bytes. usage notes don't use getrandomvalues() to generate encryp...
Crypto.subtle - Web APIs
syntax var crypto = crypto.subtle; value a subtlecrypto object you can use to interact with the web crypto api's low-level cryptography features. specifications specification status comment web cryptography apithe definition of 'crypto.subtle' in that specification. ...
Crypto - Web APIs
ailable in the current context. it allows access to a cryptographically strong random number generator and to cryptographic primitives. note: this feature is available in web workers. the web crypto api is accessed through the window.crypto property, which is a crypto object. properties this interface implements properties defined on randomsource. crypto.subtle read only secure context re
turns a subtlecrypto object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption. methods this interface implements methods defined on randomsource. crypto.getrandomvalues() fills the passed typedarray with cryptographically sound random values. usage notes you should avoid using the web crypto api on insecure contexts, even though the crypto ...
CustomElementRegistry.upgrade() - Web APIs
grade() method of the customelementregistry interface upgrades all shadow-containing custom elements in a node subtree, even before they are connected to the main document. syntax customelements.upgrade(root); parameters root a node instance with shadow-containing descendant elements that are to be upgraded. if there are no descendant elements that can be upgraded, no error is thrown. re
turn value void. examples taken from the html spec: const el = document.createelement("spider-man"); class spiderman extends htmlelement {} customelements.define("spider-man", spiderman); console.assert(!(el instanceof spiderman)); // not yet upgraded customelements.upgrade(el); console.assert(el instanceof spiderman); // upgraded! specifications specification status commen...
CustomElementRegistry.whenDefined() - Web APIs
if the custom element is already defined, the promise is resolved immediately. exceptions exception description syntaxerror if the provided name is not a valid custom element name, the promise rejects with a syntaxerror. examples this example uses whendefined() to detect when the custom elements that make up a menu are defined. ...
CustomEvent() - Web APIs
ypearg, customeventinit); parameters typearg a domstring representing the name of the event. customeventinit optional a customeventinit dictionary, having the following fields: "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event. the customeventinit dictionary also accepts fields from the eventinit dictionary. re
turn value a new customevent object of the specified type, with any other properties configured according to the customeventinit dictionary (if one was provided). example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatch...
CustomEvent.detail - Web APIs
the detail readonly property of the customevent interface re
turns any data passed when initializing the event. note: this feature is available in web workers. syntax let mydetail = customeventinstance.detail; re
turn value whatever data the event was initialized with. example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); // will re
turn an object contaning the hazcheeseburger property let mydetail = event.detail; specifications specification status comment domthe definition of 'detail' in that specification. living standard initial definition. ...
DOMConfiguration - Web APIs
nts", "datatype-normalization", "element-content-whitespace", "entities", "error-handler", "infoset", "namespaces", "namespace-declarations", "normalize-characters","schema-location", "schema-type", "split-cdata-sections", "validate", "validate-if-schema", "well-formed" properties domconfiguration.parameternames read only is a domstringlist methods domconfiguration.cansetparameter() re
turns a boolean domconfiguration.getparameter() re
turns a domuserdata domconfiguration.setparameter() sets a parameter specification http://www.w3.org/tr/dom-level-3-cor...mconfiguration ...
DOMError - Web APIs
error types type description indexsizeerror the index is not in the allowed range (e.g. thrown in a range object). hierarchyrequesterror the node tree hierarchy is not correct. wrongdocumenterror the object is in the wrong document. ...
DOMException.code - Web APIs
this field is used for historical reasons. new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. syntax var domexceptioncode = domexceptioninstance.code; value a short number. specifications specification status comment web idlthe definition of 'code' in that specification. candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. ...
DOMException.message - Web APIs
syntax var domexceptionmessage = domexceptioninstance.message; value a domstring. specifications specification status comment web idlthe definition of 'message' in that specification. candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
DOMImplementation.createDocumentType() - Web APIs
syntax var doctype = document.implementation.createdocumenttype(qualifiednamestr, publicid, systemid); parameters qualifiednamestr is a domstring containing the qualified name, like svg:svg. publicid is a domstring containing the public identifier. systemid is a domstring containing the system identifiers. ...
DOMImplementation.createHTMLDocument() - Web APIs
handle inserting the new paragraph into the new document. line 16 pulls the contentdocument of the frame; this is the document into which we'll be injecting the new content. the next two lines handle importing the contents of our new document into the new document's context. finally, line 20 actually replaces the contents of the frame with the new document's contents. view live examples the re
turned document is pre-constructed with the following html: <!doctype html> <html> <head> <title>title</title> </head> <body> </body> </html> specifications specification status comment domthe definition of 'domimplementation.createhtmldocument' in that specification. living standard initial definition. ...
DOMMatrixReadOnly.scale() - Web APIs
for the origin of the transformation. if no origin is supplied, this defaults to 0. originy optional a y-coordinate for the origin of the transformation. if no origin is supplied, this defaults to 0. originz optional a z-coordinate for the origin of the transformation. if no origin is supplied, this defaults to 0. if this value is anything other than 0, the resulting matrix will be 3d. re
turn value re
turns a dommatrix containing a new matrix being the result of the matrix x and y dimensions being scaled by the given factor, centered on the origin given. the original matrix is not modified. if a scale is applied about the z-axis, the resulting matrix will be a 4x4 3d matrix. note: at time of writing, firefox still supports an older version of the specification that accepts either o...
DOMMatrixReadOnly.translate() - Web APIs
slatez]) parameters translatex a number representing the abscissa (x-coordinate) of the translating vector. translatey a number representing the ordinate (y-coordinate) of the translating vector. translatez optional a number representing the z component of the translating vector. if not supplied, this defaults to 0. if this is anything other than 0, the resulting matrix will be 3d. re
turn value re
turns a dommatrix containing a new matrix being the result of the matrix being translated by the given vector. the original matrix is not modified. if a translation is applied about the z-axis, the resulting matrix will be a 4x4 3d matrix. examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 5...
DOMParser() - Web APIs
the domparser() constructor creates a new domparser object. syntax var parser = new domparser(); parameters none. re
turn value a new domparser object. this object can be used to parse the text of a document using the parsefromstring() method. ...
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and re
turns a new mutable dompoint object given a source point. the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a new dompoint object using the new dompoint() constructor. although this interface is based on dompointreadonly, it is not read-only; the properties within may be changed at will. syntax var point = dompoint.frompoint(sourcepoint); properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties. re
turn value a new dompoint object whose coordinate and perspective values are identical to those in the source point. the point's properties...
DOMPoint.DOMPoint() - Web APIs
you can also create a dompoint by calling the dompoint.frompoint() static function. that function accepts as input a dompointinit compatible object, including a dompoint or dompointreadonly. syntax point = new dompoint(x, y, z, w); parameters x optional the x coordinate for the new dompoint. y optional the y coordinate for the new dompoint. z optional the z coordinate for the new dompoint. w optional the perspective value of the new dompoint. ...
DOMPoint - Web APIs
well as an optional perspective value. dompoint is based on dompointreadonly but allows its properties' values to be changed. in general, a positive x component represents a position to the right of the origin, a positive y component is downward from the origin, and a positive z component extends outward from the screen (in other words, toward the user). constructor dompoint() creates and re
turns a new dompoint object given the values of zero or more of its coordinate components and optionally the w perspective value. you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a new point by calling the dompoint.frompoint() static method. methods dompoint inherits methods from its parent, dompointreadonly. static methods dompoint.frompoint(...
DOMPointInit.w - Web APIs
lue may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). this value is assumed to be 1 by default if not included in the dompointinit object passed into frompoint(). specifications specification status comment geometry interfaces module level 1the definition of 'w' in that specificat...
DOMPointInit.x - Web APIs
g the point's x coordinate. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 by default. dompointinit is used as an input when calling either dompointreadonly.frompoint() or dompoint.frompoint(), and is re
turned by the dompointreadonly.tojson() and dompoint.tojson() methods. specifications specification status comment geometry interfaces module level 1the definition of 'x' in that specification. candidate recommendation initial definition ...
DOMPointInit.y - Web APIs
is assumed to be 0 by default. there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). specifications specification status comment geometry interfaces module level 1the definition of 'y' in that specification. candidate recommendation initial definition ...
DOMPointInit.z - Web APIs
lue may be nan or ±infinity). there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created. this method is, by inheritance, also available as dompoint.frompoint(). the dompointreadonly.tojson() method re
turns a dompointinit object that describes the same point as the original point. by inheritance, this method is also available as dompoint.tojson(). if this property is missing when the dompointinit object is passed into frompoint(), the value is assumed to be 0 by default. specifications specification status comment geometry interfaces module level 1the definition of 'z' i...
DOMPointInit - Web APIs
properties dompointinit.x an unrestricted floating-point value indicating the x-coordinate of the point in space. this is generally the horizontal coordinate, with positive values being to the right and negative values to the left. ...
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and re
turns a new dompointreadonly object given a source point. the source point is specified as a dompointinit-compatible object, which includes both dompoint and dompointreadonly. you can also create a new dompointreadonly object using the new dompointreadonly() constructor. syntax const point = dompointreadonly.frompoint(sourcepoint) properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties. re
turn value a new dompointreadonly object (which is identical to the source point). examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y. the z an...
DOMPointReadOnly.toJSON() - Web APIs
example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json. var topleft = new dompoint(window.screenx, window.screeny); var pointjson = topleft.tojson(); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly.tojson()' in that specification. ...
DOMPointReadOnly - Web APIs
coordinate, z. dompointreadonly.w read only the point's perspective value, w. static methods dompointreadonly.frompoint() a static method that creates a new dompointreadonly object given the coordinates provided in the specified dompointinit object. methods matrixtransform() applies a matrix transform specified as a dommatrixinit object to the dompointreadonly object. tojson() re
turns a json representation of the dompointreadonly object. specifications specification status comment geometry interfaces module level 1the definition of 'dompoint' in that specification. candidate recommendation latest spec version is an ed. ...
DOMRect.DOMRect() - Web APIs
syntax var mydomrect = new domrect(x, y, width, height); parameters x the x coordinate of the domrect's origin. y the y coordinate of the domrect's origin. width the width of the domrect. height the height of the domrect. examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then re
turn // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly() - Web APIs
, height) parameters x the x coordinate of the domrectreadonly's origin. y the y coordinate of the domrectreadonly's origin. width the width of the domrectreadonly. height the height of the domrectreadonly. examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then re
turn // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly.bottom - Web APIs
(has the same value as y + height, or y if height is negative.) syntax var recbottom = domrect.bottom; value a double. specifications specification status comment geometry interfaces module level 1the definition of 'bottom' in that specification. ...
DOMRectReadOnly.fromRect() - Web APIs
ax var domrect = domrectreadonly.fromrect(rectangle) parameters rectangle optional an object specifying the location and dimensions of a rectangle. all properties default to 0. the properties are: x: the coordinate of the left side of the rectangle. y: the coordinate of the top side of the rectangle. width: the width of the rectangle. height: the height of the rectangle. re
turn value an instance of domrect. specifications specification status comment geometry interfaces module level 1the definition of 'fromrect()' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check ou...
DOMRectReadOnly.left - Web APIs
(has the same value as x, or x + width if width is negative.) syntax var recleft = domrect.left; value a double. specifications specification status comment geometry interfaces module level 1the definition of 'left' in that specification. ...
DOMRectReadOnly.right - Web APIs
(has the same value as x + width, or x if width is negative.) syntax var recright = domrect.right; value a double. specifications specification status comment geometry interfaces module level 1the definition of 'right' in that specification. ...
DOMRectReadOnly.top - Web APIs
(has the same value as y, or y + height if height is negative.) syntax var rectop = domrect.top; value a double. specifications specification status comment geometry interfaces module level 1the definition of 'top' in that specification. ...
DOMStringList - Web APIs
a type re
turned by some apis which contains a list of domstring (strings). properties domstringlist.length read only re
turns the length of the list. methods domstringlist.item() re
turns a domstring. domstringlist.contains() re
turns boolean indicating if the given string is in the list specifications specification status comment html living standardthe definition of 'domstringlist' in that specification. living standard initial specification ...
DOMTokenList.entries() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent. ...
DOMTokenList.forEach() - Web APIs
llback [, thisarg]); parameters callback function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array. currentindex the index of the current element being processed in the array. listobj the array that foreach() is being applied to. thisarg optional value to use as this when executing callback. re
turn value undefined. example in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using foreach(), writing each one to the <span>'s node.textcontent inside the foreach() inner function. html <span class="a b c"></span> javascript let span = document.queryselector("span"); l...
DOMTokenList.keys() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
DOMTokenList.remove() - Web APIs
the remove() method of the domtokenlist interface removes the specified tokens from the list. syntax tokenlist.remove(token1[, token2[, ...tokenn]]); parameters tokenn a domstring representing the token you want to remove from the list. if the string is not in the list, no error is thrown, and nothing happens. re
turn value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then remove a token from the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; classes.remove("c"); span.textcontent = classes; the output looks like this: to rem...
DOMTokenList.supports() - Web APIs
the supports() method of the domtokenlist interface re
turns true if a given token is in the associated attribute's supported tokens. this method is intended to support feature detection. syntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for. re
turns a boolean indicating whether the token was found. example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment c...
DOMTokenList.toggle() - Web APIs
the toggle() method of the domtokenlist interface removes a given token from the list and re
turns false. if token doesn't exist it's added and the function re
turns true. syntax tokenlist.toggle(token [, force]); parameters token a domstring representing the token you want to toggle. force optional a boolean that, if included,
turns the toggle into a one way-only operation. if set to false, then token will only be removed, but not added. if set to true, then token will only be added, but not removed. re
turn value a boolean indicating whether token is in the list after the call. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'...
DOMTokenList.value - Web APIs
syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent. ...
DOMTokenList.values() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s node.textcontent. ...
DataTransfer.addElement() - Web APIs
the datatransfer.addelement() method sets the drag source to the given element. this element will be the element to which drag and dragend events are fired, and not the defaut target (the node that was dragged). note: this method is gecko-specific. syntax void datatransfer.addelement(el); arguments el the element to set as the drag source. re
turn value void example this example shows the use of the addelement() method function change_drag_node(event, node) { var dt = event.datatransfer; dt.addelement(node); } specifications this method is not defined in any web standard. ...
DataTransfer.dropEffect - Web APIs
r.dropeffect property controls the feedback (typically visual) the user is given during a drag and drop operation. it will affect which cursor is displayed while dragging. for example, when the user hovers over a target drop element, the browser's cursor may indicate which type of operation will occur. when the datatransfer object is created, dropeffect is set to a string value. on getting, it re
turns its current value. on setting, if the new value is one of the values listed below, then the property's current value will be set to the new value and other values will be ignored. for the dragenter and dragover events, dropeffect will be initialized based on what action the user is requesting. how this is determined is platform specific, but typically the user can press modifier keys such as th...
DataTransfer.getData() - Web APIs
the datatransfer.getdata() method retrieves drag data (as a domstring) for the specified type. if the drag operation does not include data, this method re
turns an empty string. example data types are text/plain and text/uri-list. syntax datatransfer.getdata(format); arguments format a domstring representing the type of data to retrieve. re
turn value domstring a domstring representing the drag data for the specified format. if the drag operation has no data or the operation has no data for the specified format, this method re
turns an empty string. caveats data availability the html5 drag and drop specification dictates a drag data store mode. this may result in unexpected behavior, being datatransfer.getdata() not re
turning an expected value. example this example shows ...
DataTransfer.mozClearDataAt() - Web APIs
ast format for a particular index removes that item entirely, shifting the remaining items down and changing their indices. note: this method is gecko-specific. syntax void datatransfer.mozcleardataat([type], index); arguments type a string representing the type of the drag data to remove from the drag data object. index a unsigned long representing the index of the data to remove. re
turn value void example this example shows the use of the mozcleardataat() method in a dragend event handler. function dragend_handler(event) { var dt = event.datatransfer; // remove a text/html item dt.mozcleardataat("text/html", 1); } specifications this method is not defined in any web standard. ...
DataTransfer.mozGetDataAt() - Web APIs
the datatransfer.mozgetdataat() method is used to retrieve an item in the drag event's data transfer object, based on a given format and index. this method re
turns null if the specified item does not exist or if the index is not in the range from zero to the number of items minus one. note: this method is gecko-specific. syntax nsivariant datatransfer.mozgetdataat([type], index); arguments type a string representing the type of the drag data to retrieve from the drag data object. index a unsigned long representing the index of the data to retrieve. re
turn value nsivariant the data item requested. if the specified item does not exist, null is re
turned. example this example shows the use of the mozgetdataat() method in a drop event handler. function drop_handler(event) {...
DataTransfer.mozSetDataAt() - Web APIs
h will be converted into a string) or an nsisupports. note: this method is gecko-specific. syntax void datatransfer.mozsetdataat([type], data, index); arguments type a string representing the type of the drag data to add to the drag data object. data a nsivariant representing the data to add to the drag data object. index a unsigned long representing the index of the data to add. re
turn value void example this example shows the use of the mozsetdataat() method in a dragstart handler. function dragstart_handler(event) { var dt = event.datatransfer; var idx = dt.mozitemcount; // add two new items to the drag transfer if (idx >= 0) { dt.mozsetdataat("text/uri-list","http://www.example.com/", idx); dt.mozsetdataat("text/html", "hello world", idx+1); } } ...
DataTransfer.mozSourceNode - Web APIs
the datatransfer.mozsourcenode property is used to determine the node over which the mouse cursor was located when the the drag operation was initiated (for example, when a <button> was clicked). for external drags or if the calling function cannot reach the node, null is re
turned. note: this property is gecko-specific. this property is read only . syntax datatransfer.mozsourcenode; re
turn value a node representing node where the drag originated. re
turns null for external drags or if the node cannot be accessed. example this example shows the use of the mozsourcenode property in the dragend event handler. function dragend_handler(event) { var dragdata = event.datatransfer; var node = dragdata.mozsourcenode; if (node != null) console.log("mozsourcenode = " + dragdata.mozs...
DataTransfer.setData() - Web APIs
s replaced in the same position. that is, the order of the types list is not changed when replacing data of the same type. example data types are text/plain and text/uri-list. syntax void datatransfer.setdata(format, data); arguments format a domstring representing the type of the drag data to add to the drag object. data a domstring representing the data to add to the drag object. re
turn value void example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata() methods. <!doctype html> <html lang=en> <title>examples of datatransfer's setdata(), getdata() and cleardata()</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #targe...
DataTransfer.setDragImage() - Web APIs
element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). xoffset a long indicating the horizontal offset within the image. yoffset a long indicating the vertical offset within the image. re
turn value void example this example shows how to use the setdragimage() method. note the example refers to an image file named example.gif. if that file is present, it will be used as the drag image and if that file is not present, the browser will use its default drag image. demo <!doctype html> <html lang=en> <title>example of datatransfer.setdragimage()</title> <meta name="viewport" cont...
DataTransferItem.getAsString() - Web APIs
the datatransferitem.getasstring() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a plain unicode string (i.e. kind is string). syntax datatransferitem.getasstring(callback); parameters callback a callback function that has access to the data transfer item's string data. see callback below for details. re
turn value undefined callback the callback parameter is a callback function which accepts one parameter: domstring the drag data item's string data. the callback re
turn value is undefined. example this example shows the use of the getasstring() method as an inline function in a drop event handler. function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; for (...
DataTransferItem.kind - Web APIs
it must be one of the following values: 'file' if the drag data item is a file. 'string' if the kind of drag data item is a plain unicode string. example this example shows the use of the kind property. ...
DataTransferItem - Web APIs
n, each drag event has a datatransfer property which contains a list of drag data items. each item in the list is a datatransferitem object. this interface has no constructor. properties datatransferitem.kind read only the kind of drag data item, string or file. datatransferitem.type read only the drag data item's type, typically a mime type. methods datatransferitem.getasfile() re
turns the file object associated with the drag data item (or null if the drag item is not a file). datatransferitem.getasstring() invokes the specified callback with the drag data item string as its argument. datatransferitem.webkitgetasentry() re
turns an object based on filesystementry representing the selected file's entry in its file system. this will generally be either a filesystemfileentry...
DataTransferItemList.DataTransferItem() - Web APIs
the datatransferitem() getter method implements support for accessing items in the datatransferitemlist using array-style syntax (that is datatransferitem[index]). syntax dataitem = datatransferitem[index]; parameters index the zero-based index of the item in the drag data list to re
turn. re
turn value the datatransferitem object at the specified index in the item list. if the index is less than zero or greater than or equal to the number of items in the list (as indicated by the list's length property, undefined is re
turned. the re
turned value is never null. example this example shows how to use drag and drop. javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to...
DataTransferItemList.clear() - Web APIs
ist method clear() removes all datatransferitem objects from the drag data items list, leaving the list empty. the drag data store in which this list is kept is only writable while handling the dragstart event. while handling drop, the drag data store is in read-only mode, and this method silently does nothing. no exception is thrown. syntax datatransferitemlist.clear(); parameters none. re
turn value undefined example this example shows the use of the clear() method. html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(even...
DataTransferItemList.length - Web APIs
syntax length = datatransferitemlist.length; value the number of drag data items in the list, or 0 if the list is empty or disabled. the drag item list is considered to be disabled if the item list's datatransfer object is not associated with a drag data store. example this example shows the use of the length property. ...
DataTransferItemList.remove() - Web APIs
feritem at the specified index from the list. if the index is less than zero or greater than one less than the length of the list, the list will not be changed. syntax datatransferitemlist.remove(index); parameters index the zero-based index number of the item in the drag data list to remove. if the index doesn't correspond to an existing item in the list, the list is left unchanged. re
turn value undefined. exceptions invalidstateerror the drag data store is not in read/write mode, so the item can't be removed. example this example shows the use of the remove() method. javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev...
DataTransferItemList - Web APIs
being dragged. during a drag operation, each dragevent has a datatransfer property and that property is a datatransferitemlist. this interface has no constructor. properties datatransferitemlist.length read only an unsigned long that is the number of drag items in the list. methods datatransferitemlist.add() adds an item (either a file object or a string) to the drag item list and re
turns a datatransferitem object for the new item. datatransferitemlist.remove() removes the drag item from the list at the given index. datatransferitemlist.clear() removes all of the drag items from the list. datatransferitemlist.datatransferitem() getter that re
turns a datatransferitem at the given index. example each of this interface's methods and properties has a reference page, and each...
DedicatedWorkerGlobalScope.name - Web APIs
the name read-only property of the dedicatedworkerglobalscope interface re
turns the name that the worker was (optionally) given when it was created. this is the name that the worker() constructor can pass to get a reference to the dedicatedworkerglobalscope. syntax var nameobj = self.name; value a domstring. example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", re
turnable by running self.name from inside the worker. specifications specification status comment html living standardthe definition of 'name' in that specification. living standard ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
the structured clone algorithm, which includes cyclical references. transferlist optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the main thread it was sent to. only messageport and arraybuffer objects can be transferred. re
turns void. example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script. inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'r...
DelayNode() - Web APIs
ters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext or offlineaudiocontext. options optional an object specifying the delay node options. can contain the following members: delaytime: the initial delay time for the node, in seconds. the default is 0. maxdelaytime: the maximum delay time for the node, in seconds. defaults to 1. re
turn value a new delaynode object instance. example const audioctx = new audiocontext(); const delaynode = new delaynode(audioctx, { delaytime: 0.5, maxdelaytime: 2, }); specifications specification status comment web audio apithe definition of 'delaynode()' in that specification. working draft initial definition. browser compatibility the compatibility ...
DelayNode.delayTime - Web APIs
ce is an a-rate audioparam representing the amount of delay to apply. delaytime is expressed in seconds, its minimal value is 0, and its maximum value is defined by the maxdelaytime argument of the audiocontext.createdelay() method that created it. syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam re
turned is read-only, the value it represents is not. value an audioparam. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be in...
DeprecationReportBody - Web APIs
the deprecationreportbody interface of the reporting api represents the body of a deprecation report (the re
turn value of its report.body property). a deprecation report is generated when a deprecated feature (e.g. a deprecated api method) is used on a document being observed by a reportingobserver. properties id a string representing the deprecated feature that generated the report, for example navigatorgetusermedia. this can be used to group reports by deprecated feature. anticipatedremoval a date object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. if the date is not known, this property will re
turn null. message a string containing a human-readable description of the deprecation, including information ...
Using light sensors - Web APIs
im environment 100 ~ 1000 lux : normal > 10000 lux : bright it uses the addeventlistener method of the window object. window.addeventlistener("devicelight", function (event) { // read out the lux value var luminosity = event.value; alert(luminosity); }); example: window.addeventlistener('devicelight', function(event) { var bodybg= document.body.style; //event.value is the lux value re
turned by the sensor on the device if (event.value < 100) { alert('hey, you! you are working in a dark environment'); bodybg.backgroundcolor="lightgrey"; } else { bodybg.backgroundcolor="#fff"; } }); this example shows how the api can actually be used in the wild. if your app contains a lot of white in the ui, it is usually beneficial to the user to change the ui to a darker color in a darker e...
DeviceMotionEvent.acceleration - Web APIs
note: if the hardware doesn't know how to remove gravity from the acceleration data, this value may not be present in the devicemotionevent. in this situation, you'll need to use devicemotionevent.accelerationincludinggravity instead. syntax var acceleration = devicemotionevent.acceleration; value the acceleration property is an object providing information about acceleration on three axis. ...
DeviceMotionEvent.accelerationIncludingGravity - Web APIs
unlike devicemotionevent.acceleration which compensates for the influence of gravity, its value is the sum of the acceleration of the device as induced by the user and the acceleration caused by gravity. this value is not typically as useful as devicemotionevent.acceleration, but may be the only value available on devices that aren't able of removing gravity from the acceleration data, such as on devices that don't have a gyroscope. ...
DeviceMotionEvent.interval - Web APIs
you can use this to determine the granularity of motion events. syntax var interval = devicemotionevent.interval; specifications specification status comment deviceorientation event specification editor's draft initial definition. ...
DeviceMotionEvent.rotationRate - Web APIs
syntax var rotationrate = devicemotionevent.rotationrate; value the rotationrate property is a read only object describing the rotation rates of the device around each of its axes: alpha the rate at which the device is rotating about its z axis; that is, being twisted about a line perpendicular to the screen. beta the rate at which the device is rotating about its x axis; that is, front to back. gamma the rate at which the device is rotating about its y axis; that is, side to side. ...
Document.importNode() - Web APIs
h it's still an optional argument, you should always provide the deep argument for backward and forward compatibility. with gecko 28.0 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3), the console warns developers not to omit the argument. starting with gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)), a shallow clone is defaulted instead of a deep clone. re
turn value the copied importednode in the scope of the importing document. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container")...
Document: keydown event - Web APIs
bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { re
turn; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key. <p>focus the iframe first (e.g. by clicking in it), then try pressing some keys.</p> <p id="log"></p> document.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent document.onkey...
Document: keyup event - Web APIs
rs (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { re
turn; } // do something }); examples this example logs the keyboardevent.code value whenever you release a key. addeventlistener keyup example <p>focus the iframe first (e.g. by clicking in it), then try pressing some keys.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } ...
Document.links - Web APIs
syntax nodelist = document.links value an htmlcollection. example var links = document.links; for(var i = 0; i < links.length; i++) { var linkhref = document.createtextnode(links[i].href); var linebreak = document.createelement("br"); document.body.appendchild(linkhref); document.body.appendchild(linebreak); } specifications specification status comment html living standardthe definition of 'document.links' in that specification. ...
Document.location - Web APIs
the document.location read-only property re
turns a location object, which contains information about the url of the document and provides methods for changing that url and loading another url. though document.location is a read-only location object, you can also assign a domstring to it. this means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. to retrieve just the url as a string, the read-only document.url property can also be used. if the current document is not in a browsing context, the re
turned value is null. syntax locationobj = document.location document.location = 'http://www.mozilla.org' // equivalent to document.location.href = 'http:/...
Document.mozSyntheticDocument - Web APIs
the document.mozsyntheticdocument property indicates whether or not the document is a synthetic one; that is, a document representing a standalone image, video, audio, or the like. syntax var issynthetic = document.mozsyntheticdocument; on re
turn, issynthetic is true if the document is a synthetic one; otherwise it's false. example this can be useful if you have a contextual menu item you only want to display for synthetic documents (or, conversely, for documents that aren't synthetic). var issynthetic = document.mozsyntheticdocument; if (issynthetic) { /* insert your menu item here */ } specifications not part of any specification. ...
Document.ononline - Web APIs
the document.online event is fired on the <body> of each page when the browser switches between online and offline mode. additionally, the events bubble up from document.body, to document, ending at window. both events are non-cancellable (you can't prevent the user from coming online, or going offline). window.navigator.online re
turns boolean true if the browser is online and false if it is definitely offline (disconnected from the network). the online and offline events are fired when the value of this attribute changes. it is important to note that this event and attribute are inherently unreliable. a computer can be connected to a network without having internet access. you can register listeners for these events in a few familiar ways: using addeventlistener on the window, docume...
Document.open() - Web APIs
the document.open() method opens a document for writing. this does come with some side effects. for example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed. all existing nodes are removed from the document. syntax document.open(); parameters none. re
turn value a document object instance. examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years ...
Document.plugins - Web APIs
for a list of installed plugins, use navigatorplugins.plugins instead. syntax embedarrayobj = document.plugins value an htmlcollection, or null if there are no embeds in the document. ...
Document.preferredStyleSheetSet - Web APIs
the preferredstylesheetset property re
turns the preferred style sheet set as set by the page author. syntax preferredstylesheetset = document.preferredstylesheetset on re
turn, preferredstylesheetset indicates the author's preferred style sheet set. this is determined from the order of style sheet declarations and the default-style http header. if there isn't a preferred style sheet set defined by the author, the empty string ("") is re
turned. example if (document.preferredstylesheetset) { console.log("the preferred style sheet set is: " + document.preferredstylesheetset); } else { console.log("there is no preferred style sheet."); } ...
Document.queryCommandEnabled() - Web APIs
the document.querycommandenabled() method reports whether or not the specified editor command is enabled by the browser. syntax isenabled = document.querycommandenabled(command); parameters command the command for which to determine support. re
turn value re
turns a boolean which is true if the command is enabled and false if the command isn't. notes for 'cut' and 'copy' commands the method only re
turns true when called from a user-initiated thread. the 'paste' command re
turn false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action. example var flg = document.querycommandenabled("selectall"); if(flg) { document.execcommand("selectall", false, null); // command is enabled, run it } specificatio...
Document.queryCommandState() - Web APIs
the querycommandstate() method will tell you if the current selection has a certain document.execcommand() command applied. syntax querycommandstate(string command) parameters command is a command from document.execcommand() re
turn value querycommandstate() can re
turn a boolean value or null if the state is unknown. example html <div contenteditable="true">select a part of this text!</div> <button onclick="makebold();">test the state of the 'bold' command</button> javascript function makebold() { var state = document.querycommandstate("bold"); switch (state) { case true: alert("the bold formatting will be removed from the selected text."); break; case false: alert("the selected text will be displayed in bold."); break; case null: al...
Document.registerElement() - Web APIs
note: this is an experimental technology. the browser you use it in must support web components. see enabling web components in firefox. syntax var constructor = document.registerelement(tag-name, options); parameters tag-name the name of the custom element. the name must contain a dash (-), for example my-tag. ...
Document.rootElement - Web APIs
syntax const element = document.rootelement notes if the document is a non-empty svg document, then the rootelement will be an svgsvgelement, identical to the documentelement. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgdocument.rootelement' in that specification. candidate recommendation deprecated scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgdocument.rootelement' in that specification. ...
Document.scripts - Web APIs
syntax var scriptlist = document.scripts; value an htmlcollection. you can use this just like an array to get all the elements in the list. example this example looks to see if the page has any <script> elements. ...
Document.scrollingElement - Web APIs
the scrollingelement read-only property of the document interface re
turns a reference to the element that scrolls the document. in standards mode, this is the root element of the document, document.documentelement. when in quirks mode, the scrollingelement attribute re
turns the html body element if it exists and is not potentially scrollable, otherwise it re
turns null. syntax var element = document.scrollingelement; example var scrollelm = document.scrollingelement; scrollelm.scrolltop = 0; specifications specification status comment css object model (cssom) view modulethe definition of 'scrollingelement' in that specification. working draft initial definition ...
Document.selectedStyleSheetSet - Web APIs
you can also set the current style sheet set using this property. setting the value of this property is equivalent to calling document.enablestylesheetsforset() with the value of currentstylesheetset, then setting the value of laststylesheetset to that value as well. ...
Document.styleSheetSets - Web APIs
the stylesheetsets read-only property re
turns a live list of all of the currently-available style sheet sets. syntax var sets = document.stylesheetsets; on re
turn, sets is a list of style sheet sets that are available. example given an <ul> (list) element with the id "sheetlist", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getelementbyid('sheetlist'); let sheets = document.stylesheetsets; list.innerhtml = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createelement('li'); item.innerhtml = sheets[i]; list.appendchild(item); } notes the list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in...
Document.visibilityState - Web APIs
it is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering. possible values are: 'visible' the page content may be at least partially visible. in practice this means that the page is the foreground tab of a non-minimized window. 'hidden' the page content is not visible to the user. in practice this means that the document is either a background tab or part of a minimized window, or the os screen lock is active. 'prerender' the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). ...
Document.xmlEncoding - Web APIs
should be null if unspecified or unknown. warning: do not use this attribute; it has been removed from the dom level 4 specification and is no longer supported in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7). ...
DocumentFragment() - Web APIs
syntax fragment = new documentfragment() example let fragment = new documentfragment(); specification specification status comment domthe definition of 'documentfragment()' in that specification. ...
DocumentOrShadowRoot.activeElement - Web APIs
if so, you can get more detail by using the object's selectionstart and selectionend properties. other times the focused element might be a <select> element (menu) or an <input> element, of type "button", "checkbox", or "radio". typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate one (that is, to press a button or toggle a radio button). ...
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
the elementsfrompoint() method of the documentorshadowroot interface re
turns an array of all elements at the specified coordinates (relative to the viewport). it operates in a similar way to the elementfrompoint() method. syntax const elements = document.elementsfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. re
turn value an array of element objects. example html <div> <p>some text</p> </div> <p>elements at point 30, 20:</p> <div id="output"></div> javascript let output = document.getelementbyid("output"); if (document.elementsfrompoint) { let elements = document.elementsfrompoint(30, 20); for (var i = 0; i < elements.length; i++) { output.textcontent += elements[i].localname; if (i < elements...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
the nodefrompoint() property of the documentorshadowroot interface re
turns the topmost node at the specified coordinates (relative to the viewport). currently this method is only implemented in firefox, and only available to chrome code. syntax var node = document.nodefrompoint(x, y); parameters x a double representing the horizontal coordinate of a point. y a double representing the vertical coordinate of a point. re
turns a node object. examples html content <div> <p>some text</p> </div> <p>top node at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodefrompoint) { var node = document.nodefrompoint(30, 20); output.textcontent += node.localname; } else { output.innerhtml = "<span ...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
the nodesfrompoint() property of the documentorshadowroot interface re
turns an array of all nodes at the specified coordinates (relative to the viewport). currently this method is only implemented in firefox, and only available to chrome code. syntax var nodes = document.nodesfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. re
turns an array of node objects. example html content <div> <p>some text</p> </div> <p>nodes at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodesfrompoint) { var nodes = document.nodesfrompoint(30, 20); for(var i = 0; i < nodes.length; i++) { output.textcontent += nodes[i].localname; if (i < nodes...
DocumentOrShadowRoot.pointerLockElement - Web APIs
the pointerlockelement property of the document and shadowroot interfaces provides the element set as the target for mouse events while the pointer is locked. it is null if lock is pending, pointer is unlocked, or the target is in another document. syntax var element = document.pointerlockelement; re
turn value an element or null. specifications specification status comment pointer lockthe definition of 'pointerlockelement' in that specification. candidate recommendation extend the document interface ...
DocumentTimeline - Web APIs
the the web animations api represents animation timelines, including the default document timeline (accessed via document.timeline). constructor documenttimeline() creates a new documenttimeline object associated with the active document of the current browsing context. properties this interface inherits its property from its parent, animationtimeline. animationtimeline.currenttime re
turns the time value in milliseconds for this timeline or null if it is inactive. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. this bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.queryselectorall('.sharedtimelinecat');...
Example - Web APIs
<html> <head> <title>my document</title> <script type="text/javascript"> function change() { // document.getelementsbytagname("h1") re
turns a nodelist of the h1 // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createele...
Using the W3C DOM Level 1 Core - Web APIs
l 1 spec. a simple example suppose the author wants to change the header of the above document and write two paragraphs instead of one. the following script would do the job: html content <body> <input type="button" value="change this document." onclick="change()"> <h2>header</h2> <p>paragraph</p> </body> javascript content function change() { // document.getelementsbytagname("h2") re
turns a nodelist of the <h2> // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h2").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document". var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the fi...
DragEvent.dataTransfer - Web APIs
example this example illustrates accessing the drag and drop data within the dragend event handler. function processdata(d) { // process the data ... ...
DynamicsCompressorNode.attack - Web APIs
of time, in seconds, required to reduce the gain by 10 db. it defines how quickly the signal is adapted when its volume is increased. the attack property's default value is 0.003 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.attack.value = 0; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio...
DynamicsCompressorNode.knee - Web APIs
ram containing a decibel value representing the range above the threshold where the curve smoothly transitions to the compressed portion. the knee property's default value is 30 and it can be set between 0 and 40. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.knee.value = 40; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio...
DynamicsCompressorNode.ratio - Web APIs
sornode interface is a k-rate audioparam representing the amount of change, in db, needed in the input for a 1 db change in the output. the ratio property's default value is 12 and it can be set between 1 and 20. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.ratio.value = 12; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio...
DynamicsCompressorNode.release - Web APIs
f time, in seconds, required to increase the gain by 10 db. it defines how quick the signal is adapted when its volume is reduced. the release property's default value is 0.25 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.release.value = 0.25; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio...
DynamicsCompressorNode.threshold - Web APIs
rnode interface is a k-rate audioparam representing the decibel value above which the compression will start taking effect. the threshold property's default value is -24 and it can be set between -100 and 0. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.threshold.value = -50; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio...
EXT_disjoint_timer_query.beginQueryEXT() - Web APIs
the ext_disjoint_timer_query.beginqueryext() method of the webgl api starts a timer query. syntax void ext.beginqueryext(target, query); parameters target a glenum specifying the target of the time query. must be ext.time_elapsed_ext. query a webglquery object for which to start the time querying. re
turn value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ... specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. working draft initial definition. ...
EXT_disjoint_timer_query.createQueryEXT() - Web APIs
the ext_disjoint_timer_query.createqueryext() method of the webgl api creates and initializes webglquery objects, which track the time needed to fully complete a set of gl commands. syntax webgltimerqueryext ext.createqueryext(); parameters none. re
turn value a webglquery object. examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. working draft initial definition. ...
EXT_disjoint_timer_query.queryCounterEXT() - Web APIs
the ext_disjoint_timer_query.querycounterext() method of the webgl api records the current time into the corresponding query object. syntax void ext.querycounterext(query, target); parameters query a webglquery object for which to record the current time. target a glenum specifying the target of the time query. must be ext.timestamp_ext. re
turn value none. examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); var endquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); // ... ext.querycounterext(endquery, ext.timestamp_ext); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification. working draf...
EXT_sRGB - Web APIs
onstants, which can be used in the teximage2d(), texsubimage2d(), renderbufferstorage() and getframebufferattachmentparameter() methods. ext.srgb_ext unsized srgb format that leaves the precision up to the driver. ext.srgb_alpha_ext unsized srgb format with unsized alpha component. ext.srgb8_alpha8_ext sized (8-bit) srgb and alpha formats. ext.framebuffer_attachment_color_encoding_ext re
turns the framebuffer color encoding (gl.linear or ext.srgb_ext). examples var ext = gl.getextension('ext_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, ext.srgb_ext, 512, 512, 0, ext.srgb_ext, gl.unsigned_byte, image); specifications specification status comment ext_srgbthe definition of '...
EXT_texture_compression_bptc - Web APIs
data. see also bc7 format. ext.compressed_srgb_alpha_bptc_unorm_ext compresses 8-bit fixed-point data. each 4x4 block of texels consists of 128 bits of srgb_alpha or image data. see also bc7 format. ext.compressed_rgb_bptc_signed_float_ext compresses high dynamic range signed floating point values. each 4x4 block of texels consists of 128 bits of rgb data. it only contains rgb data, so the re
turned alpha value is 1.0. see also bc6h format. ext.compressed_rgb_bptc_unsigned_float_ext compresses high dynamic range unsigned floating point values. each 4x4 block of texels consists of 128 bits of rgb data. it only contains rgb data, so the re
turned alpha value is 1.0. see also bc6h format. examples var ext = gl.getextension('ext_texture_compression_bptc'); var texture = gl.createtexture()...
EXT_texture_filter_anisotropic - Web APIs
ookups have a tendency to average to grey. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. constants ext.max_texture_max_anisotropy_ext this is the pname argument to the gl.getparameter() call, and it re
turns the maximum available anisotropy. ext.texture_max_anisotropy_ext this is the pname argument to the gl.gettexparameter() and gl.texparameterf() / gl.texparameteri() calls and sets the desired maximum anisotropy for a texture. examples var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); var ext = ( gl.getextension('ext_texture_filter_anisotropic') || gl.getextension(...
EffectTiming.direction - Web APIs
tions api dictionary effecttiming indicates an animation's playback direction along its timeline, as well as its behavior when it reaches the end of an iteration element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including direction. the value of direction corresponds directly to animationeffecttimingreadonly.direction in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { direction: "normal" | "reverse" | "alternate" | "alternate-reverse" }; timingproperties.direction = "normal" | "reverse" | "alternate" | "alternate-reverse"; value a domstring which specifies the direction in which the animation should play as well as what to do when the playback rea...
EffectTiming.easing - Web APIs
ty in the web animations api specifies the timing function used to scale the time to produce easing effects, where easing is the rate of the animation's change over time. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including easing. the value of easing corresponds directly to animationeffecttimingreadonly.easing in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { easing: single-transition-timing-function } timingproperties.easing = single-transition-timing-function value a string defining the timing function to use for easing transitions during the animation process. accepts several pre-defined domstring values, a steps() timing function like...
EffectTiming.endDelay - Web APIs
t will benefit most from this property have not been defined in the specification yet. for now, its main purpose is to represent the value of the svg min attribute. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including enddelay. the value of enddelay corresponds directly to animationeffecttimingreadonly.enddelay in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { enddelay: delayinmilliseconds } timingproperties.enddelay = delayinmilliseconds; value a number representing the end delay, specified in milliseconds. the default value is 0. specifications specification status comment web animationsthe definition of 'enddel...
EffectTiming.fill - Web APIs
ast rendered frame. note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely. see the alternatives to fill modes section below for approaches that are simpler and more performant. element.animate(), and keyframeeffect() accept an object of timing properties including fill. the value of fill corresponds directly to fill in effecttiming objects re
turned by gettiming() in animationeffect and keyframeeffect. syntax var timingproperties = { fill: "none" | "forwards" | "backwards" | "both" | "auto" } value a domstring indicating the fill type to use in order to properly render an affected element when outside the animation's active interval (that is, when it's not actively animating). the default is "auto". "none" the animation's effec...
EffectTiming.iterationStart - Web APIs
operty specifies the repetition number which repetition the animation begins at and its progress through it. element.animate(), keyframeeffectreadonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an object of timing properties including iterationstart. the value of iterationstart corresponds directly to animationeffecttimingreadonly.iterationstart in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { iterationstart = iterationnumber }; timingproperties.iterationstart = iterationnumber; value a floating-point value whose value is at least 0 and is not +infinity, indicating the offset into the number of iterations the animation sequence is to run at which to start animating. iterat...
EffectTiming.iterations - Web APIs
but you can set it to any floating-point value (including positive infinity defaults to 1, and can also take a value of infinity to make it loop infinitely. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including iterations. the value of iterations corresponds directly to animationeffecttimingreadonly.iterations in timing objects re
turned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { iterations: numberofiterations }; timingproperties.iterations = numberofiterations; value a floating-point value specifying the number of times the animation sequence will play through. any value from 0 (don't play the animation at all) to positive infinity (run the animation indefin...
Element.attributes - Web APIs
it is a namednodemap, not an array, so it has no array methods and the attr nodes' indexes may differ among browsers. to be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute. syntax var attr = element.attributes; example basic examples // get the first <p> element in the document var para = document.getelementsbytagname("p")[0]; var atts = para.attributes; enumerating elements attributes numerical indexing is useful for going through all of an element's attributes. ...
Element.className - Web APIs
ad of class because of conflicts with the "class" keyword in many languages which are used to manipulate the dom. classname can also be an instance of svganimatedstring if the element is an svgelement. it is better to get/set the classname of an element using element.getattribute and element.setattribute if you are dealing with svg elements. however, take into account that element.getattribute re
turns null instead of "" if the element has an empty class attribute. elm.setattribute('class', elm.getattribute('class')) the class is an html attribute, while the classname is a dom property. specifications specification status comment domthe definition of 'element.classname' in that specification. living standard dom4the definition of 'element.classnam...
Element.clientHeight - Web APIs
ght of an element in pixels. it includes padding but excludes borders, margins, and horizontal scrollbars (if present). clientheight can be calculated as: css height + css padding - height of horizontal scrollbar (if present). when clientheight is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is re
turned. this is a special case of clientheight. note: this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var intelemclientheight = element.clientheight; intelemclientheight is an integer corresponding to the clientheight of element in pixels. the clientheight property is read–only. example specification s...
Element.clientLeft - Web APIs
only. when layout.scrollbar.side preference is set to 1 or to 3 and when the text-direction is set to rtl, then the vertical scrollbar is positioned on the left and this impacts the way clientleft is computed. note: this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). note: when an element has display: inline, clientleft re
turns 0 regardless of the element's border. syntax var left = element.clientleft; example padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit e...
Element.clientWidth - Web APIs
element.clientwidth property is zero for inline elements and elements with no css; otherwise, it's the inner width of an element in pixels. it includes padding but excludes borders, margins, and vertical scrollbars (if present). when clientwidth is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's width (excluding any scrollbar) is re
turned. this is a special case of clientwidth. note: this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax var intelemclientwidth = element.clientwidth; intelemclientwidth is an integer corresponding to the clientwidth of element in pixels. the clientwidth property is read–only. example specification specific...
Element.computedStyleMap() - Web APIs
the computedstylemap() method of the element interface re
turns a stylepropertymapreadonly interface which provides a read-only representation of a css declaration block that is an alternative to cssstyledeclaration. syntax var stylepropertymapreadonly = element.computedstylemap() parameters none. re
turn value a stylepropertymapreadonly interface. examples we start with some simple html: a paragraph with a link, and a definition list to which we will add all the css property / value pairs. <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and re
turn back a definition list of all the css property values using computedstylemap(). // get the el...
Element.createShadowRoot() - Web APIs
use element.createshadowroot to create an instance of shadow dom. when shadow dom is created, it is always attached to an existing element. after the shadow dom is created, the element that it is attached to is called the shadow root. this method has been deprecated in favor of attachshadow(). syntax var shadowroot = element.createshadowroot(); parameters no parameters. result value re
turns a shadowroot. specifications this feature is no longer defined by any specifications. ...
Element.currentStyle - Web APIs
element.currentstyle is a proprietary property which is similar to the standardized window.getcomputedstyle() method. it is available in old versions of microsoft internet explorer. however, it re
turns the units set in css while window.getcomputedstyle() re
turns the values in pixels. polyfill this polyfill re
turns the values in pixels and is likely to be rather slow, as it has to call window.getcomputedstyle() every time its value is read. /* any copyright is dedicated to the public domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ if (!("currentstyle" in element.prototype)) { object.defineproperty(element.prototype, "currentstyle", { get: function() { re
turn window.getcomputedstyle(this); } }); } specification not part of any specification. microso...
Element.getAttributeNode() - Web APIs
syntax var attrnode = element.getattributenode(attrname); attrnode is an attr node for the attribute. attrname is a string containing the name of the attribute. example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding. the attr node inherits from node, but is not considered a part of the document tree. common node attributes like parentnode, previoussibling, and nextsibling are null for an attr node. ...
Element.getAttributeNodeNS() - Web APIs
syntax attributenode = element.getattributenodens(namespace, nodename) attributenode is the node for specified attribute. namespace is a string specifying the namespace of the attribute. nodename is a string specifying the name of the attribute. == example == tbd the example needs to be fixed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace. the corresponding setter method is setattributenodens. ...
Element.hasAttributeNS() - Web APIs
syntax result = element.hasattributens(namespace,localname) result is the boolean value true or false. namespace is a string specifying the namespace of the attribute. localname is the name of the attribute. ...
Element.hasAttributes() - Web APIs
the hasattributes() method of the element interface re
turns a boolean indicating whether the current element has any attributes or not. syntax var result = element.hasattributes(); re
turn value result holds the re
turn value true or false. examples let foo = document.getelementbyid('foo'); if (foo.hasattributes()) { // do something with 'foo.attributes' } polyfill ;(function(prototype) { prototype.hasattributes = prototype.hasattributes || function() { re
turn (this.attributes.length > 0); } })(element.prototype); specifications specification status comment domthe definition of 'element.hasattributes()' in that specification. living standard moved from the node interface to the more specialized element interface. document obje...
Element.hasPointerCapture() - Web APIs
the haspointercapture() method of the element interface sets whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer id. syntax targetelement.haspointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. re
turn value a boolean value — true if the element does have pointer capture, false if it doesn't. examples <html> <script> function downhandler(ev) { const el = document.getelementbyid("target"); // element 'target' will receive/capture further events el.setpointercapture(ev.pointerid); /* ... */ // check whether element still has pointer capture let pointercap = el.haspointercapture(ev.pointerid); if(pointercap) { // we've still got poin...
Element.insertAdjacentElement() - Web APIs
position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself. 'afterbegin': just inside the targetelement, before its first child. 'beforeend': just inside the targetelement, after its last child. 'afterend': after the targetelement itself. element the element to be inserted into the tree. re
turn value the element that was inserted, or null, if the insertion failed. exceptions exception explanation syntaxerror the position specified is not a recognised value. typeerror the element specified is not a valid element. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -...
Element.insertAdjacentText() - Web APIs
on a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. element a domstring representing the text to be inserted into the tree. re
turn value void. exceptions exception explanation syntaxerror the position specified is not a recognised value. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in a tree and has an element parent. example before...
Element: keydown event - Web APIs
bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { re
turn; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element. <input placeholder="click here, then press down a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keydown', logkey); ...
Element: keyup event - Web APIs
rs (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { re
turn; } // do something }); examples addeventlistener keyup example this example logs the keyboardevent.code value whenever you release a key inside the <input> element. <input placeholder="click here, then press and release a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keyup', logkey); ...
Element: mousedown event - Web APIs
drawing begins when the mousedown event fires. first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true. as the mouse moves over the page, the mousemove event fires. if isdrawing is true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location. when the drawline() function re
turns, we adjust the coordinates and then save them in x and y. the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false. html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mo...
Element: mousemove event - Web APIs
drawing begins when the mousedown event fires. first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true. as the mouse moves over the page, the mousemove event fires. if isdrawing is true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location. when the drawline() function re
turns, we adjust the coordinates and then save them in x and y. the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false. html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mo...
Element: mouseup event - Web APIs
drawing begins when the mousedown event fires. first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true. as the mouse moves over the page, the mousemove event fires. if isdrawing is true, the event handler calls the drawline function to draw a line from the stored x and y values to the current location. when the drawline() function re
turns, we adjust the coordinates and then save them in x and y. the mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isdrawing to false. html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mo...
Element.msZoomTo() - Web APIs
not zoomable. animate[in]: the type of animation to use. default: uses the default animation. none: no animation is used. this method has no scrolling effect on non-scrollable elements and no zooming effect on non-zoomable elements (e.g., elements with "-ms-content-zooming: none"). this method has no effect if called from a parent document to scroll or zoom content hosted in an iframe. re
turn value this method does not re
turn a value. example /* zooming in on an element while still keeping it centered in the viewport */ var args = { contentx: target.offsetleft + target.offsetwidth/2; contenty: target.offsettop + target.offsetheight/2; scalefactor: 2.0; } zoomer.mszoomto(args); see also microsoft api extensions ...
Element.name - Web APIs
, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>. note: the name property doesn't exist for other elements; unlike tagname and nodename, it is not a property of the node, element or htmlelement interfaces. name can be used in the document.getelementsbyname() method, a form and with the form elements collection. when used with a form or elements collection, it may re
turn a single element or a collection. syntax htmlelement.name = string let elname = htmlelement.name let fcontrol = htmlformelement.elementname let controlcollection = htmlformelement.elements.elementname example <form action="" name="forma"> <input type="text" value="foo"> </form> <script type="text/javascript"> // get a reference to the first element in the form let formelement = docu...
Element.namespaceURI - Web APIs
the element.namespaceuri read-only property re
turns the namespace uri of the element, or null if the element is not in a namespace. before dom4 this api was defined within the node interface. syntax namespace = element.namespaceuri example in this snippet, an element is being examined for its localname and its namespaceuri. if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>. if (element.localname == "browser" && element.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of a node is...
Element.part - Web APIs
these can be used to style parts of a shadow dom, via the ::part pseudo-element. syntax let elementpartlist = element.part examples the following excerpt is from our shadow-part example. here the part attribute is used to find the shadow parts, and the part property is then used to change the part identifiers of each tab so the correct styling is applied to the active tab when tabs are clicked. ...
Element: paste event - Web APIs
solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const target = document.queryselector('div.target'); target.addeventlistener('paste', (event) => { let paste = (event.clipboarddata || window.clipboarddata).getdata('text'); paste = paste.touppercase(); const selection = window.getselection(); if (!selection.rangecount) re
turn false; selection.deletefromdocument(); selection.getrangeat(0).insertnode(document.createtextnode(paste)); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Element.prefix - Web APIs
before dom4 this api was defined within the node interface. syntax string = element.prefix examples the following logs "x" to the console. <x:div onclick="console.log(this.prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. ...
Element.releasePointerCapture() - Web APIs
sepointercapture() method of the element interface releases (stops) pointer capture that was previously set for a specific (pointerevent) pointer. see the element.setpointercapture() method for a description of pointer capture and how to set it for a particular element. syntax targetelement.releasepointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. re
turn value this method re
turns undefined. exceptions exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. html <div id="slider">slide me</div> ...
Element.removeAttribute() - Web APIs
the element method removeattribute() removes the attribute with the specified name from the element. syntax element.removeattribute(attrname); parameters attrname a domstring specifying the name of the attribute to remove from the element. if the specified attribute does not exist, removeattribute() re
turns without generating an error. re
turn value undefined. usage notes you should use removeattribute() instead of setting the attribute value to null either directly or using setattribute(). many attributes will not behave as expected if you set them to null. dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 names...
Element.scrollLeftMax - Web APIs
syntax var pxl = element.scrollleftmax; specifications this property is not part of any specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Element.scrollTop - Web APIs
rty gets or sets the number of pixels that an element's content is scrolled vertically. an element's scrolltop value is a measurement of the distance from the element's top to its topmost visible content. when an element's content does not generate a vertical scrollbar, then its scrolltop value is 0. when scrolltop is used on the root element (the <html> element), the scrolly of the window is re
turned. this is a special case of scrolltop. on systems using display scaling, scrolltop may give you a decimal value. syntax // get the number of pixels scrolled. var intelemscrolltop = someelement.scrolltop; after running this code, intelemscrolltop is an integer corresponding to the number of pixels that the element's content has been scrolled upwards. // set the number of pixels scrolled. ...
Element.scrollTopMax - Web APIs
the element.scrolltopmax read-only property re
turns a number representing the maximum top scroll offset possible for the element. syntax var pxl = elt.scrolltopmax; specifications this property is not part of any specification. ...
Element.scrollWidth - Web APIs
<button id="anotherbutton"> check for overflow </button> </body> <script> var buttonone = document.getelementbyid('abutton'), buttontwo = document.getelementbyid('anotherbutton'), divone = document.getelementbyid('adiv'), divtwo = document.getelementbyid('anotherdiv'); //check to determine if an overflow is happening function isoverflowing(element) { re
turn (element.scrollwidth > element.offsetwidth); } function alertoverflow(element) { if (isoverflowing(element)) { alert('contents are overflowing the container.'); } else { alert('no overflows!'); } } buttonone.addeventlistener('click', function() { alertoverflow(divone); }); buttontwo.addeventlistener('click', functi...
Element.setAttribute() - Web APIs
te's name; this works but is non-standard). see the example below for a practical demonstration. since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". if you wish to remove an attribute, call removeattribute(). re
turn value undefined. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, setattribute() is used to set attributes on a <button>. html <button>hello world</button> javascript var b = document.queryselector("button"); b.setattribute("name", "hellobutton"); b.setattribute("di...
Element.setAttributeNode() - Web APIs
the setattributenode() method adds a new attr node to the specified element. syntax var replacedattr = element.setattributenode(attribute); attribute is the attr node to set on the element. replacedattr is the replaced attribute node, if any, re
turned by this function. example this example copies the align attribute from one element to another. html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // re
turns: 'left' alert(d2.attributes[1].value); notes if the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is re
turned. this method...
Element.setPointerCapture() - Web APIs
e-targeted to a particular element instead of the normal (or hit test) target at a pointer's location. this can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (such as by scrolling or panning). syntax targetelement.setpointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object. re
turn value this method re
turns undefined. exceptions exception explanation invalidpointerid pointerid does not match any of the active pointers. example this example sets pointer capture on a <div> when you press down on it. this lets you slide the element horizontally, even when you pointer moves outside of its boundaries. html <div id="slider">slide me</div> ...
Element.slot - Web APIs
a slot is a placeholder inside a web component that users can fill with their own markup (see using templates and slots for more information). syntax var astring = element.slot element.slot = astring value a domstring. examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text. when <my-paragraph> is used in the document, the slot is populated by a slotable element by including it inside the element with a slot attribute with the value my-text. ...
Element.tabStop - Web APIs
if the specified element is a shadow host tab navigation is delegated to its children. this property was proposed to add tab functionality for custom elements. while with the existing tabindex property, it is required to specify an order for the element to become tabbable. the tabstop property would decouple the tabbable property from the tab index. after feedback, this property was removed from the design doc and replaced by shadowroot.delegatesfocus. ...
Element.tagName - Web APIs
the tagname read-only property of the element interface re
turns the tag name of the element on which it's called. for example, if the element is an <img>, its tagname property is "img" (for html documents; it may be cased differently for xml/xhtml documents). syntax elementname = element.tagname; value a string indicating the element's tag name. this string's capitalization depends on the document type: for dom trees which represent html documents, the re
turned tag name is always in the canonical upper-case form. for example, tagname called on a <div> element re
turns "div". the tag names of elements in an xml dom tree are re
turned in the same case in which they're written in the original xml file. if an xml document includes a tag "<sometag>", then the tagname property's value is "so...
FileSystemDirectoryReader - Web APIs
ally filesystemfileentry or filesystemdirectoryentry) representing each entry in a directory. 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. methods readentries() re
turns an array containing some number of the directory's entries. each item in the array is an object based on filesystementry—typically either filesystemfileentry or filesystemdirectoryentry. specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or whatwg specification. browser...
FileSystemEntry.copyTo() - Web APIs
ry name. successcallback optional a function which is called when the copy operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the copied item's new details. errorcallback optional an optional callback which is executed if an error occurs while copying the items. there's a single parameter: a fileerror describing what went wrong. re
turn value undefined. errors fileerror.invalid_modification_err the requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. fileerror.quota_exceeded_err the operation exceeded the user's storage quota, or there isn't enough storage space left to complete th...
FileSystemEntry.getMetadata() - Web APIs
, errorcallback]); parameters successcallback a function which is called when the copy operation is succesfully completed. receives a single input parameter: a metadata object with information about the file. errorcallback optional an optional callback which is executed if an error occurs while looking up the metadata. there's a single parameter: a fileerror describing what went wrong. re
turn value undefined. errors fileerror.not_found_err the filesystementry refers to an item which doesn't exist. fileerror.security_err security restrictions prohibit obtaining the requested metadata. example this example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory. workingdirectory.getfile("tmp/log.txt", {}, functio...
FileSystemEntry.moveTo() - Web APIs
tory name. successcallback optional a function which is called when the move operation is succesfully completed. receives a single input parameter: a filesystementry based object providing the moved item's new details. errorcallback optional an optional callback which is executed if an error occurs while moving the items. there's a single parameter: a fileerror describing what went wrong. re
turn value undefined. errors fileerror.invalid_modification_err the requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. fileerror.quota_exceeded_err the operation exceeded the user's storage quota, or there isn't enough storage space left to complete th...
FileSystemEntry.name - Web APIs
the read-only name property of the filesystementry interface re
turns a usvstring specifying the entry's name; this is the entry within its parent directory (the last component of the path as indicated by the fullpath property). syntax var name = filesystementry.name; value a usvstring indicating the entry's name. example this example shows a function called isfilewithextension() which re
turns true if the specified filesystementry is both a file and the file's name ends with a given extension. function isfilewithextension(entry, extension) { re
turn (entry.isfile && entry.name.endswith("." + extension)); } specifications specification status comment file and directory entries apithe definition of 'name' in that specification. draft initial specific...
FileSystemEntry.remove() - Web APIs
rectory as well as all of its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. syntax filesystementry.remove(successcallback[, errorcallback]); parameters successcallback a function which is called once the file has been successfully removed. errorcallback optional an optional callback which is called if the attempt to remove the file fails. re
turn value undefined. errors fileerror.invalid_modification_err the specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. fileerror.invalid_state_err the file system's cached state is inconsistent with its state on disk, so the file could not be deleted for safety reasons. fileerror.no_modification_allowed_err the file system's state d...
FileSystemEntry - Web APIs
s not a file, this value is false. name read only a usvstring containing the name of the entry (the final part of the path, after the last "/" character). methods this interface defines the following methods. copyto() copies the file or directory to a new location on the file system. getmetadata() obtains metadata about the file, such as its modification date and size. getparent() re
turns a filesystemdirectoryentry representing the entry's parent directory. moveto() moves the file or directory to a new location on the file system, or renames the file or directory. remove() removes the specified file or directory. you can only remove directories which are empty. tourl() creates and re
turns a url which identifies the entry. this url uses the url scheme "filesystem:". specif...
FileSystemFileEntry.createWriter() - Web APIs
the filesystemfileentry interface's method createwriter() re
turns a filewriter object which can be used to write data into the file represented by the directory entry. syntax filesystemfileentry.createwriter(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the filewriter has been created successfully; the filewriter is passed into the callback as the only parameter. errorcallback optional if provided, this must be a method which is caled when an error occurs while trying to create the filewriter. this callback receives as input a fileerror object describing the error. re
turn value undefined. example this example establishes a method, writetofileentry(), which outputs a text string to the file corresponding to the passed-i...
FileSystemFileEntry.file() - Web APIs
the filesystemfileentry interface's method file() re
turns a file object which can be used to read data from the file represented by the directory entry. syntax filesystemfileentry.file(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the file has been created successfully; the file is passed into the callback as the only parameter. errorcallback optional if provided, this must be a method which is called when an error occurs while trying to create the file. this callback receives as input a fileerror object describing the error. editor's note: we need to find out what kinds of errors can occur and document them. re
turn value undefined. example this example establishes a method, readfile(), reads a text file and calls a s...
File and Directory Entries API support in Firefox - Web APIs
) 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 tre
turn an error. firefox doesn't support the "filesystem:" url scheme. ...
FocusEvent() - Web APIs
when the event has both a source and a destination, the relatedtarget value must be set to the other target. syntax var focusevent = new focusevent(typearg[, focuseventinit]); properties the focusevent() constructor also inherits arguments from uievent() and from event(). typearg is a domstring representing the name of the event. focuseventinit optional is a focuseventinit dictionary, having the following fields: "relatedtarget", optional and defaulting to null, is an eventtarget representing the secondary target of a focusevent. the focuseventinit dictionary also accepts fields from the uieventinit and eventinit dictionaries. ...
FontFace.loaded - Web APIs
syntax var apromise = fontface.loaded; value a promise that resolves with the current fontface object. ...
FontFaceSet.check() - Web APIs
the check() method of the fontfaceset re
turns whether all fonts in the given font list have been loaded and are available. syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); re
turns a boolean that is true if the font list is available parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples document.fonts.check("12px courier"); // re
turns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // re
turns true if the font 'myfont' has a ß character. specifications specification status comment ...
FontFaceSet - Web APIs
aceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. css-connected fonts are unaffected. fontfaceset.delete() removes a manually-added font from the font set. css-connected fonts are unaffected. fontfaceset.load() re
turns a promise which resolves to a list of font-faces for a requested font. specifications specification status comment css font loading module level 3the definition of 'fontfaceset' in that specification. editor's draft initial definition ...
FontFaceSetLoadEvent.fontfaces - Web APIs
syntax var fontface[] = fontfacesetloadevent.fontfaces value an array of fontface instance. specifications specification status comment css font loading module level 3the definition of 'fontfaces' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
FontFaceSetLoadEvent - Web APIs
specifications specification status comment css font loading module level 3the definition of 'fontfacesetloadevent' in that specification. working draft initial definition. ...
FormData.append() - Web APIs
to the server (a usvstring), when a blob or file is passed as the second parameter. the default filename for blob objects is "blob". the default filename for file objects is the file's filename. note: if you specify a blob as the data to append to the formdata object, the filename that will be reported to the server in the "content-disposition" header used to vary from browser to browser. re
turns void. example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name. for example (and being compatible wi...
FormData.delete() - Web APIs
the delete() method of the formdata interface deletes a key and its value(s) from a formdata object. note: this method is available in web workers. syntax formdata.delete(name); parameters name the name of the key you want to delete. re
turns void. example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification. living standard ...
FormData.entries() - Web APIs
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification. ...
FormData.keys() - Web APIs
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification. ...
FormData.values() - Web APIs
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification. ...
FormDataEntryValue - Web APIs
a string or file that represents a single value from a set of formdata key-value pairs. this type is re
turned by the formdata.get() and formdata.getall() methods. the formdata.get() method re
turns a single value while formdata.getall() re
turns an array of formdataentryvalues. note that the formdata.append() and formdata.set() methods allow passing a blob value, which is converted to a file in the process. ...
FormDataEvent.formData - Web APIs
the formdata read only property of the formdataevent interface contains the formdata object representing the data contained in the form when the event was fired. syntax formdata = formdataevent.formdata re
turns a formdata object. examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } ...
Frame Timing API - Web APIs
the set of performance events to observe - in this case, just the "frame" event type. when the browser adds a new frame to the performance timeline, the specified observer callback will be invoked. accessing frame data when a frame observer is invoked, frame performance entries can be retrieved by calling performanceobserverentrylist.getentriesbytype() with an argument of "frame". this method re
turns a list of "frame" performanceentry objects. each frame object's duration property re
turns the timestamp of two consecutive frames. if this value is greater than the time needed to provide a good user experience, further analysis might be warranted. ...
Guide to the Fullscreen API - Web APIs
hings your users want to know you'll want to be sure to let your users know that they can press the esc key (or f11) to exit fullscreen mode. in addition, navigating to another page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well. example in this example, a video is presented in a web page. pressing the re
turn or enter key lets the user toggle between windowed and fullscreen presentation of the video. view live examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key. document.addeventlistener("keydown", function(e) { if (e.keycode == 13) { togglefullscreen(); } }, false); toggling fullscreen mode this code is ca...
GainNode() - Web APIs
ly call audiocontext.creategain() to create a gain node. syntax var gainnode = new gainnode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: gain: the amount of gain to apply. this parameter is a-rate and it's nominal range is (-∞,+∞). the default is 1. re
turn value a new gainnode object instance. specifications specification status comment web audio apithe definition of 'gainnode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn...
GainNode.gain - Web APIs
the gain property of the gainnode interface is an a-rate audioparam representing the amount of gain to apply. syntax var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam. note: though the audioparam re
turned is read-only, the value it represents is not. example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value. the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var ...
Gamepad.axes - Web APIs
analog thumb sticks).- each entry in the array is a floating point value in the range -1.0 – 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). ...
Gyroscope - Web APIs
gyroscope' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor gyroscope.gyroscope() creates a new gyroscope object. properties gyroscope.x read only re
turns a double, containing the angular velocity of the device along the device's x axis. gyroscope.y read only re
turns a double, containing the angular velocity of the device along the device's y axis. gyroscope.z read only re
turns a double, containing the angular velocity of the device along the device's z axis. example the gyroscope is typically read in the sensor.onreading event callback. ...
HTMLAreaElement.relList - Web APIs
the htmlareaelement.rellist read-only property reflects the rel attribute. it is a live domtokenlist containing the set of link types indicating the relationship between the resource represented by the <area> element and the current document. the property itself is read-only, meaning you can't substitute the domtokenlist by another one, but the content of the re
turned list can be changed. syntax var relstr = areaelt.rellist; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { var list = areas[i].rellist; var listlength = list.length; console.log("new area found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment h...
Audio() - Web APIs
the audio() constructor creates and re
turns a new htmlaudioelement which can be either attached to a document for the user to interact with and/or listen to, or can be used offscreen to manage and play audio. syntax audioobj = new audio(url); parameters url optional an optional domstring containing the url of an audio file to be associated with the new audio element. re
turn 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 re
turning the new object. usage notes you can also use other element-creation...
HTMLButtonElement.labels - Web APIs
the htmlbuttonelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <button> element. syntax var labelelements = button.labels; re
turn value a nodelist containing the <label> elements associated with the <button> element. example html <label id="label1" for="test">label 1</label> <button id="test">button</button> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const button = document.getelementbyid("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specifi...
HTMLButtonElement - Web APIs
rol is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. htmlbuttonelement.validity read only is a validitystate representing the validity states that this button is in. htmlbuttonelement.value is a domstring representing the current form control value of the button. methods inherits methods from its parent, htmlelement name re
turn type description checkvalidity() boolean not supported for reset or button elements. reportvalidity() boolean not supported for reset or button elements. setcustomvalidity(in domstring error) void not supported for reset or button elements. with gecko-based browser, use the :-moz-submit-invalid pseudo-class to style submit buttons based o...
HTMLCanvasElement.captureStream() - Web APIs
the htmlcanvaselement capturestream() method re
turns a mediastream which includes a canvascapturemediastreamtrack containing a real-time video capture of the canvas's contents. syntax mediastream = canvas.capturestream(framerate); parameters framerate optional a double-precision floating-point value that indicates the rate of capture of each frame. if not set, a new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the re
turned track's requestframe() method is called. re
turn value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it. exceptions notsupportederror the value of framerate is negative. example // find the canvas element to ca...
HTMLCollection.item - Web APIs
the htmlcollection method item() re
turns the node located at the specified offset into the collection. note: because the contents of an htmlcollection are live, changes to the underlying dom can and will cause the position of individual nodes in the collection to change, so the index value will not necessarily remain constant for a given node. syntax var element = htmlcollection.item(index) parameters index the position of the node to be re
turned. elements appear in an htmlcollection in the same order in which they appear in the document's source. re
turn value the node at the specified index, or null if index is less than zero or greater than or equal to the length property. usage notes the item() method re
turns a numbered element from an htmlcollection. in javascript, it is ea...
HTMLContentElement.getDistributedNodes() - Web APIs
the htmlcontentelement.getdistributednodes() method re
turns a static nodelist of the distributed nodes associated with this <content> element. syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = mycontentobject.getdistributednodes(); specifications this feature is no longer defined by any specifications. ...
HTMLContentElement - Web APIs
shadow dom. properties this interface inherits the properties of htmlelement. htmlcontentelement.select is a domstring that reflects the select html attribute. the value is a comma-separated list of css selectors that select the content to insert in place of the <content> element. methods this interface inherits the methods of htmlelement. htmlcontentelement.getdistributednodes() re
turns a static nodelist of the distributed nodes associated with this <content> element. specifications this feature is no longer defined by any standards. ...
HTMLDataElement.value - Web APIs
syntax var avalue = htmldataelement.value htmldataelement.value = avalue value a domstring. specifications specification status comment html living standardthe definition of 'htmldataelement.value' in that specification. ...
HTMLDialogElement.open - Web APIs
l</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.re
turnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes ...
HTMLDocument - Web APIs
text { fill: #0095dd; pointer-events: all;} for the purposes of web development, you can generally think of htmldocument as an alias for document, upon which htmldocument is based. you can find documentation for the members of htmldocument under the document interface. specifications html living standardthe definition of 'htmldocument' in that specification. living standard
turn the htmldocument interface into a document extension. document object model (dom) level 2 html specificationthe definition of 'htmldocument' in that specification. obsolete supersedes dom 1 document object model (dom) level 1 specificationthe definition of 'htmldocument' in that specification. obsolete initial definition ...
accessKeyLabel - Web APIs
the htmlelement.accesskeylabel read-only property re
turns a string that represents the element's assigned access key (if any); otherwise it re
turns an empty string. syntax label = element.accesskeylabel example javascript var node = document.getelementbyid('btn1'); if (node.accesskeylabel) { node.title += ' [' + node.accesskeylabel + ']'; } else { node.title += ' [' + node.accesskey + ']'; } node.onclick = function () { var p = document.createelement('p'); p.textcontent = 'clicked!'; node.parentnode.appendchild(p); }; html <button accesskey="h" title="caption" id="btn1">hover me</button> result specifications specification status comment html living standardthe definition of 'htmlelement.accesskeylabel' in that specification. living sta...
HTMLElement: beforeinput event - Web APIs
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. ...
HTMLElement.innerText - Web APIs
are important differences between the two. basically, innertext is aware of the rendered appearance of text, while textcontent is not. syntax const renderedtext = htmlelement.innertext htmlelement.innertext = string value a domstring representing the rendered text content of an element. if the element itself is not being rendered (e.g detached from the document or is hidden from view), the re
turned value is the same as the node.textcontent property. example this example compares innertext with node.textcontent. note how innertext is aware of things like <br> elements, and ignores hidden elements. html <h3>source element:</h3> <p id="source"> <style>#source { color: red; } #text { text-transform: uppercase; }</style> <span id=text>take a look at<br>how this text<br>is interpreted ...
HTMLElement: input event - Web APIs
the input event fires when the value of an <input>, <select>, or <textarea> element has been changed. bubbles yes cancelable no interface inputevent event handler property globaleventhandlers.oninput the event also applies to elements with contenteditable enabled, and 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. for <input> elements with type=checkbox or type=radio, the input event should fire whenever a user toggles the control, per the html5 specification. however, historically this has not always been the case. check compatib...
HTMLElement.isContentEditable - Web APIs
the htmlelement.iscontenteditable read-only property re
turns a boolean that is true if the contents of the element are editable; otherwise it re
turns false. syntax editable = element.iscontenteditable example html <p id="mytext1">uneditable paragraph</p> <p id="mytext2" contenteditable="true">editable paragraph</p> <p id="infotext1">can edit the first paragraph? </p> <p id="infotext2">can edit the second paragraph? </p> javascript document.getelementbyid('infotext1').innerhtml += document.getelementbyid('mytext1').iscontenteditable; document.getelementbyid('infotext2').innerhtml += document.getelementbyid('mytext2').iscontenteditable; result specifications specification status comment html living standardthe definition of 'htmlelement.contenteditable'...
HTMLElement.lang - Web APIs
common examples include "en" for english, "ja" for japanese, "es" for spanish and so on. the default value of this attribute is unknown. note that this attribute, though valid at the individual element level described here, is most often specified for the root element of the document. this also only works with the lang attribute and not with xml:lang. ...
HTMLElement.offsetLeft - Web APIs
for block-level elements, offsettop, offsetleft, offsetwidth, and offsetheight describe the border box of an element relative to the offsetparent. however, for inline-level elements (such as span) that can wrap from one line to the next, offsettop and offsetleft describe the positions of the first border box (use element.getclientrects() to get its width and height), while offsetwidth and offsetheight describe the dimensions of the bounding border box (use element.getboundingclientrect() to get its position). ...
HTMLElement: transitionend event - Web APIs
if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. specifications specification status comment css transitionsthe definition o...
HTMLFieldSetElement - Web APIs
on (willvalidate is false), or it satisfies its constraints. htmlfieldsetelement.validity a validitystate representing the validity states that this element is in. htmlfieldsetelement.willvalidate a boolean false, because <fieldset> objects are never candidates for constraint validation. methods inherits methods from its parent, htmlelement. htmlfieldsetelement.checkvalidity() always re
turns true because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.reportvalidity() always re
turns true because <fieldset> objects are never candidates for constraint validation. htmlfieldsetelement.setcustomvalidity() sets a custom validity message for the field set. if this message is not the empty string, then the field set is suffering from a custom valid...
HTMLFormElement.requestSubmit() - Web APIs
submitted using a specific submit button. syntax htmlformelement.requestsubmit(submitter); parameters submitter optional the submit button whose attributes describe the method by which the form is to be submitted. this may be either an <input> or <button> element whose type attribute is submit. if you omit the submitter parameter, the form element itself is used as the submitter. re
turn value none. exceptions typeerror the specified submitter is not a submit button. notfounderror the specified submitter isn't a member of the form on which requestsubmit() was called. the submitter must be either a descendant of the form element or must have an form attribute referring to the form. usage notes the obvious question is: why does this method exist, when we've had the submi...
HTMLHtmlElement.version - Web APIs
this property has been declared as deprecated by the w3c technical recommendation for html 4.01 in favor of use of the dtd for obtaining version information for a document. re
turns version information about the document type definition (dtd) of a document. while this property is recognized by mozilla, the re
turn value for this property is always an empty string. ...
HTMLHyperlinkElementUtils.hash - Web APIs
the htmlhyperlinkelementutils.hash property re
turns a usvstring containing a '#' followed by the fragment identifier of the url. the fragment is not percent-decoded. if the url does not have a fragment identifier, this property contains an empty string, "". syntax string = object.hash; object.hash = string; examples <a id="myanchor" href="/docs/htmlhyperlinkelementutils.href#examples">examples</a> <script> var anchor = document.getelementbyid("myanchor"); console.log(anchor.hash); // re
turns '#examples' </script> specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.hash' in that specification. living standard initial definition ...
HTMLHyperlinkElementUtils.hostname - Web APIs
the htmlhyperlinkelementutils.hostname property is a usvstring containing the domain of the url. syntax string = object.hostname; object.hostname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.hostname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.hostname; // re
turns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.hostname' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.href - Web APIs
the htmlhyperlinkelementutils.href property is a stringifier that re
turns a usvstring containing the whole url, and allows the href to be updated. syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/htmlhyperlinkelementutils/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // re
turns: 'https://developer.mozilla.org/htmlhyperlinkelementutils/href' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.href' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.origin - Web APIs
lowed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:. e.g "blob:https://mozilla.org" will have "https://mozilla.org". note: this feature is available in web workers. syntax string = object.origin; examples // on this page, re
turns the origin var result = window.location.origin; // re
turns:'https://developer.mozilla.org' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.origin' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.password - Web APIs
efore the domain name. if it is set without first setting the username property, it silently fails. syntax string = object.password; object.password = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.password; // re
turns:'flabada' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.password' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.pathname - Web APIs
string containing an initial '/' followed by the path of the url (or the empty string if there is no path). syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // re
turns:'/docs/htmlhyperlinkelementutils.pathname' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.pathname' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.port - Web APIs
tring containing the port number of the url. if the url does not contain an explicit port number, it will be set to ''. syntax string = object.port; object.port = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org:443/docs/htmlhyperlinkelementutils.port"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.port; // re
turns:'443' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.port' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.protocol - Web APIs
mentutils.protocol property is a usvstring representing the protocol scheme of the url, including the final ':'. syntax string = object.protocol; object.protocol = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/htmlhyperlinkelementutils.protocol"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.protocol; // re
turns:'https:' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.protocol' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.search - Web APIs
ide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // re
turns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.search' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils.username - Web APIs
mentutils.username property is a usvstring containing the username specified before the domain name. syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // re
turns:'anonymous' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.username' in that specification. living standard initial definition. ...
HTMLIFrameElement.allowPaymentRequest - Web APIs
syntax var allow = htmliframeelement.allowpaymentrequest value a boolean. specifications specification status comment payment request apithe definition of 'allowpaymentrequest' in that specification. candidate recommendation adds allowpaymentrequest property. html living standardthe definition of 'htmliframeelement: allowpaymentrequest' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. ...
contentDocument - Web APIs
if the iframe and the iframe's parent document are same origin, re
turns a document (that is, the active document in the inline frame's nested browsing context), else re
turns null. example of contentdocument var iframedocument = document.getelementsbytagname("iframe")[0].contentdocument; iframedocument.body.style.backgroundcolor = "blue"; // this would
turn the iframe blue. specifications specification status comment html living standardthe definition of 'htmliframeelement: contentdocument' in that specification. living standard ...
HTMLIFrameElement.setNfcFocus() - Web APIs
the setnfcfocus() method of the htmliframeelement interface sets whether an <iframe> can receive an nfc event. syntax myiframe.setnfcfocus(true); re
turns void. parameters a boolean indicating whether the <iframe> can receive an nfc event. default is false; set to true to allow it to receive nfc events. specifications not part of any specification. ...
HTMLImageElement.complete - Web APIs
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) { re
turn 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() { if (lightboxelem.style.display === "...
HTMLImageElement.useMap - Web APIs
rticle add a hitmap on top of an image. usage notes the string value of usemap must be a valid anchor for a <map> element. in other words, this string should be the value of the appropriate <map>'s name attribute with a pound or hash symbol prepended to it. ...
HTMLImageElement.x - Web APIs
value indicating the distance in pixels from the left edge of the element's nearest root element and the left edge of the <img> element's border box. the nearest root element is the outermost <html> element that contains the image. if the image is in an <iframe>, its x is relative to that frame. in the diagram below, the left border edge is the left edge of the blue padding area. so the value re
turned by x would be the distance from that point to the left edge of the content area. note: the x property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a containing element or by being located within a column described by either <col> or <co...
HTMLImageElement.y - Web APIs
teger value indicating the distance in pixels from the top edge of the element's nearest root element to the top edge of the <img> element's border box. the nearest root element is the outermost <html> element that contains the image. if the image is in an <iframe>, its y is relative to that frame. in the diagram below, the top border edge is the top edge of the blue padding area. so the value re
turned by y would be the distance from that point to the top edge of the content area. note: the y property is only valid if the computed value of the image's display property is either table-column or table-column-group; in other words, either of those are set directly on the <img> or they're inherited from a containing element or by being located within a column described by either <col> or <col...
HTMLInputElement.labels - Web APIs
the htmlinputelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <input> element. syntax var labelelements = input.labels; re
turn value a nodelist containing the <label> elements associated with the <input> element. example html <label id="label1" for="test">label 1</label> <input id="test"/> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const input = document.getelementbyid("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living stan...
HTMLInputElement.stepDown() - Web APIs
sed, is 1. the method will not cause the value to go below the min value set or defy the constraints set by the step attribute. a negative value for n will increment the value, but will not increment beyond the max value. if the value before invoking the stepdown() method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepdown() method will re
turn a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, an invalidstateerror exception is thrown. htmlinputelement.stepdown() decrements the value by (step * n), where n defaults to 1 ...
HTMLInputElement.stepUp() - Web APIs
the constraints set on the form control. the default value for the parameter, if no value is passed, is 1. the method will not cause the value to exceed the set max value, or defy the constraints set by the step attribute. if the value before invoking the stepup() method is invalid—for example, if it doesn't match the constraints set by the step attribute—invoking the stepup() method will re
turn a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if the step value is set to any, an invalidstateerror exception is thrown. syntax element.stepup( [ stepincrement ] ); parameters stepincrement th...
HTMLKeygenElement - Web APIs
is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. validity read only is a validitystate representing the validity states that this element is in. willvalidate is a boolean that is always false because keygen objects are never candidates for constraint validation. methods name & arguments re
turn description checkvalidity() boolean always re
turns true because keygen objects are never candidates for constraint validation. setcustomvalidity(in domstring error) void sets a custom validity message for the element. if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. ...
HTMLLabelElement.control - Web APIs
syntax control = htmllabelelement.control value an htmlelement derived object representing the control with which the <label> is associated, or null if the label stands alone. if this property has a value and htmllabelelement.htmlfor has a value, the htmllabelelement.htmlfor property must refer to the same control. ...
HTMLLabelElement.form - Web APIs
the read-only htmllabelelement.form property re
turns an htmlformelement object which represents the form of which the label's associated control is a part, or null if there is either no associated control, or if that control isn't in a form. this property is just a shortcut for htmllabelelement.control.form. syntax form = htmllabelelement.form value an htmlformelement which represents the form with which the label's control is associated. if control is null (meaning the label isn't associated with a control), or if the control isn't part of a form, this property re
turns null. specifications specification status comment html living standardthe definition of 'form' in that specification. living standard initial definition ...
HTMLLegendElement - Web APIs
" text-anchor="middle" alignment-baseline="middle">htmllegendelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmllegendelement.form read only is a htmlformelement representing the form that this legend belongs to. if the legend has a fieldset element as its parent, then this attribute re
turns the same value as the form attribute on the parent fieldset element. otherwise, it re
turns null. htmllegendelement.accesskey is a domstring representing a single-character access key to give access to the element. htmllegendelement.align is a domstring representing the alignment relative to the form set methods no specific method; inherits methods from its parent, htmlelement. speci...
HTMLLinkElement.as - Web APIs
syntax var as = htmllinkelement.as htmllinkelement.as = as value a domstring. specifications specification status comment preloadthe definition of 'as' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
HTMLLinkElement.relList - Web APIs
the htmllinkelement.rellist read-only property reflects the rel attribute. it is a live domtokenlist containing the set of link types indicating the relationship between the resource represented by the <link> element and the current document. the property itself is read-only, meaning you can substitute the domtokenlist by another one, but the content of the re
turned list can be changed. syntax var relstr = linkelt.rellist; example var links = document.getelementsbytagname("link"); var length = links.length; for (var i = 0; i < length; i++) { var list = links[i].rellist; var listlength = list.length; console.log("new link found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html...
HTMLLinkElement - Web APIs
htmllinkelement.rel is a domstring representing the forward relationship of the linked resource from the document to the resource. htmllinkelement.rellist read only is a domtokenlist that reflects the rel html attribute, as a list of tokens. htmllinkelement.sizes read only is a domsettabletokenlist that reflects the sizes html attribute, as a list of tokens. linkstyle.sheet read only re
turns the stylesheet object associated with the given element, or null if there is none. htmllinkelement.type is a domstring representing the mime type of the linked resource. obsolete properties htmllinkelement.charset is a domstring representing the character encoding for the target resource. htmllinkelement.rev is a domstring representing the reverse relationship of the linked resourc...
HTMLMediaElement.buffered - Web APIs
note: this feature is not available in web workers. syntax var timerange = audioobject.buffered value a timeranges object. this object is normalized, which means that ranges are ordered, don't overlap, aren't empty, and don't touch (adjacent ranges are folded into one bigger range). ...
HTMLMediaElement.canPlayType() - Web APIs
the htmlmediaelement method canplaytype() reports how likely it is that the current browser will be able to play media of a given mime type. note: this feature is not available in web workers. syntax canplayresponse = audioorvideo.canplaytype(mediatype); parameters mediatype a domstring containing the mime type of the media. re
turn value a domstring indicating how likely it is that the media can be played. the string will be one of the following values: probably media of the type indicated by the mediatype parameter is probably playable on this device. maybe not enough information is available to determine for sure whether or not the media will play until playback is actually attempted. "" (empty string) media of the given type definitely can't be played on the current dev...
HTMLMediaElement.controlsList - Web APIs
the domtokenlist takes one or more of three possible values: nodownload, nofullscreen, and noremoteplayback. syntax var domtokenlist = htmlmediaelement.controlslist; value a domtokenlist. specifications specification status comment controls list api: solution outline browser compatibility the compatibility table on this page is generated from structured data. ...
HTMLMediaElement.currentTime - Web APIs
at 0 seconds cannot be seeked to a time before its timeline's earliest time. the length of the media in seconds can be determined using the duration property. example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value re
turned by currenttime. specifications specification status comment html living standardthe definition of 'htmlmediaelement.currenttime' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement.currenttime' in that specification. recommendation initial definition. ...
msClearEffects - Web APIs
er. there may also be large incompatibilities between implementations and the behavior may change in the future. the mscleareffects method of the htmlmediaelement, is a proprietary method specific to internet explorer and microsoft edge. mscleareffects clears all effects from the media pipeline. syntax htmlmediaelement.mscleareffects(); parameters this method has no parameters. re
turn value this method does not re
turn a value. see also touch api microsoft api extensions ...
HTMLObjectElement.validationMessage - Web APIs
this is the empty string if the control is not a candidate for constraint validation (willvalidate is false), or it satisfies its constraints. syntax var string = htmlobjectelement.validationmessage; value a domstring. ...
HTMLOptionElement - Web APIs
ing the position of the option within the list of options it belongs to, in tree-order. if the option is not part of a list of options, like when it is part of the <datalist> element, the value is 0. htmloptionelement.label read only is a domstring that reflects the value of the label html attribute, which provides a label for the option. if this attribute isn't specifically set, reading it re
turns the element's text content. htmloptionelement.selected is a boolean that indicates whether the option is currently selected. htmloptionelement.text is a domstring that contains the text content of the element. htmloptionelement.value is a domstring that reflects the value of the value html attribute, if it exists; otherwise reflects value of the node.textcontent property. methods inher...
HTMLOptionsCollection - Web APIs
the htmloptionscollection interface represents a collection of <option> html elements (in document order) and offers methods and properties for selecting from the list as well as optionally altering its items. this object is re
turned only by the options property of select. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/htmlcollection" target="_top"><rect x="1" y="1" width="140" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="71" y="30" font-size="12px" font-family="consolas,...
HTMLOrForeignElement.dataset - Web APIs
provides read/write access to all the custom data attributes (data-*) set on the element. this access is available both in html and within the dom. it is a map of domstrings (domstringmap) with one entry for each custom data attribute. note that the dataset property itself can be read, but not directly written. instead, all writes must be to the individual properties within the dataset, which in
turn represent the data attributes. note also that an html data-attribute and its corresponding dom dataset.property do not share the same name, but they are always similar: in html, the name of a custom data attribute begins with data-. it must contain only letters, numbers, and the following characters: dash (-), dot (.), colon (:), underscore (_)—but not any ascii capital letters (a to z). in...
HTMLOrForeignElement.nonce - Web APIs
the nonce property of the htmlorforeignelement interface re
turns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed. in later implementations, elements only expose their nonce attribute to scripts (and not to side-channels like css attribute selectors). examples retrieving a nonce value in the past, not all browsers supported the nonce idl attribute, so a workaround is to try to use getattribute as a fallback: let nonce = script['nonce'] || script.getattribute('nonce'); however, recent browsers version hide nonce values that are accessed this way (an empty string will be re
turned). the idl property (script['nonce']) will be the only way to access nonces. nonce hiding helps preventing that attackers ex...
HTMLOrForeignElement - Web APIs
nes listed below. note: htmlorforeignelement is a mixin and not an interface; you can't actually create an object of type htmlorforeignelement. ...
HTMLOutputElement.labels - Web APIs
the htmloutputelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <output> element. syntax var labelelements = output.labels; re
turn value a nodelist containing the <label> elements associated with the <output> element. example html <label id="label1" for="test">label 1</label> <output id="test">output</output> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const output = document.getelementbyid("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specifi...
HTMLOutputElement - Web APIs
lue a domstring representing the value of the contents of the elements. behaves like the node.textcontent property. htmloutputelement.willvalidateread only a boolean indicating whether the element is a candidate for constraint validation. methods this interface also inherits methods from its parent, htmlelement. htmloutputelement.checkvalidity() checks the validity of the element and re
turns a boolean holding the check result. htmloutputelement.reportvalidity() this method reports the problems with the constraints on the element, if any, to the user. if there are problems, fires an invalid event at the element, and re
turns false; if there are no problems, it re
turns true. when the problem is reported, the user agent may focus the element and change the scrolling position of the d...
HTMLProgressElement.labels - Web APIs
the htmlprogresselement.labels read-only property re
turns a nodelist of the <label> elements associated with the <progress> element. syntax var labelelements = progress.labels; re
turn value a nodelist containing the <label> elements associated with the <progress> element. example html <label id="label1" for="test">label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const progress = document.getelementbyid("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe de...
HTMLScriptElement - Web APIs
or <script> start and end tags in html, in foreign content, and in xml; the rules for the document.write() method; the handling of scripting; and so on. htmlscriptelement.crossorigin is a domstring reflecting the cors setting for the script element. for scripts from other origins, this controls if error information will be exposed. htmlscriptelement.text is a domstring that joins and re
turns the contents of all text nodes inside the <script> element (ignoring other nodes like comments) in tree order. on setting, it acts the same way as the textcontent idl attribute. note: when inserted using the document.write() method, <script> elements execute (typically synchronously), but when inserted using innerhtml or outerhtml, they do not execute at all. htmlscriptelement.nomodule i...
HTMLSelectElement.checkValidity() - Web APIs
syntax var result = selectelt.checkvalidity(); specifications specification status comment html living standardthe definition of 'htmlselectelement.checkvalidity()' in that specification. ...
HTMLSelectElement.labels - Web APIs
the htmlselectelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <select> element. syntax var labelelements = select.labels; re
turn value a nodelist containing the <label> elements associated with the <select> element. example html <label id="label1" for="test">label 1</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment ...
HTMLSelectElement.options - Web APIs
the htmlselectelement.options read-only property re
turns a htmloptionscollection of the <option> elements contained by the <select> element. syntax var options = select.options; re
turn value a htmloptionscollection containing the <option> elements contained by the <select> element. example html <label for="test">label</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "option 1" and "option 2" } }); specifications specification status comment html living standardthe definition ...
HTMLSelectElement.selectedOptions - Web APIs
value an htmlcollection which lists every currently selected htmloptionelement which is either a child of the htmlselectelement or of an htmloptgroupelement within the <select> element. in other words, any option contained within the <select> element may be part of the results, but option groups are not included in the list. if no options are currently selected, the collection is empty and re
turns a length of 0. example in this example, a <select> element with a number of options is used to let the user order various food items. html the html that creates the selection box and the <option> elements representing each of the food choices looks like this: <label for="foods">what do you want to eat?</label><br> <select id="foods" name="foods" size="7" multiple> <option value="1">burrit...
HTMLSelectElement.type - Web APIs
syntax var str = selectelt.type; the possible values are: "select-multiple" if multiple values can be selected. "select-one" if only one value can be selected. example switch (select.type) { case 'select-multiple': // multiple values may be selected break; case 'select-one': // only one value may be selected break; default: // non-standard value (or this isn't a select element) } specifications specification status comment html living standardthe definition of 'htmlselectelement' in that specification. living standard no change from html5, the latest snapshot. ...
HTMLShadowElement.getDistributedNodes() - Web APIs
the htmlshadowelement.getdistributednodes() method re
turns a static nodelist of the distributed nodes associated with this <shadow> element. syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = myshadowobject.getdistributednodes(); specifications this feature is no longer defined by any specifications. ...
HTMLSlotElement.assignedElements() - Web APIs
the assignedelements() property of the htmlslotelement interface re
turns a sequence of the elements assigned to this slot (and no other nodes). if the flatten option is set to true, it also re
turns the assigned elements of any other slots that are descendants of this slot. if no assigned nodes are found, it re
turns the slot's fallback content. syntax var assignedelements = htmlslotelement.assignedelements(options) parameters options optional an object that sets options for the nodes to be re
turned. the available options are: flatten: a boolean indicating whether to re
turn the assigned elements of any available child <slot> elements (true) or not (false). defaults to false. re
turn value an array of elements. examples let slots = this.shadowroot.queryselector('slot'); let el...
HTMLSlotElement.assignedNodes() - Web APIs
the assignednodes() property of the htmlslotelement interface re
turns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot. if no assigned nodes are found, it re
turns the slot's fallback content. syntax var assignednodes = htmlslotelement.assignednodes(options) parameters options optional an object that sets options for the nodes to be re
turned. the available options are: flatten: a boolean indicating whether to re
turn the assigned nodes of any available child <slot> elements (true) or not (false). defaults to false. re
turn value an array of nodes. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.que...
HTMLSlotElement.name - Web APIs
a slot is a placeholder inside a web component that users can fill with their own markup. syntax var name = htmlslotelement.name htmlslotelement.name = name value a domstring. examples the following snippet is taken from our slotchange example (see it live also). ...
HTMLStyleElement.type - Web APIs
the htmlstyleelement.type read-only property re
turns the type of the current style. for gecko, the type is most often given as "text/css." from the w3c spec on css: "the expectation is that binding-specific casting methods can be used to cast down from an instance of the cssrule interface to the specific derived interface implied by the type." syntax string = style.type; example if (newstyle.type != "text/css"){ // not supported! warncss(); } ...
HTMLStyleElement - Web APIs
ent, and implements linkstyle. htmlstyleelement.media is a domstring representing the intended destination medium for style information. htmlstyleelement.type is a domstring representing the type of style being applied by this statement. htmlstyleelement.disabled is a boolean value representing whether or not the stylesheet is disabled (true) or not (false). linkstyle.sheet read only re
turns the stylesheet object associated with the given element, or null if there is none htmlstyleelement.scoped is a boolean value indicating if the element applies to the whole document (false) or only to the parent's sub-tree (true). methods no specific method; inherits properties from its parent, htmlelement, and linkstyle. specifications specification status comment ...
HTMLTableCellElement - Web APIs
rter term for use by screen readers in particular, and is a valuable accessibility tool. usually the value of abbr is an abbreviation or acronym, but can be any text that's appropriate contextually. htmltablecellelement.cellindex read only a long integer representing the cell's position in the cells collection of the <tr> the cell is contained within. if the cell doesn't belong to a <tr>, it re
turns -1. htmltablecellelement.colspan an unsigned long integer indicating the number of columns this cell must span; this lets the cell occupy space across multiple columns of the table. it reflects the colspan attribute. htmltablecellelement.headers read only is a domsettabletokenlist describing a list of id of <th> elements that represents headers associated with the cell. it reflects the head...
HTMLTableElement.createCaption() - Web APIs
the htmltableelement.createcaption() method re
turns the <caption> element associated with a given <table>. if no <caption> element exists on the table, this method creates it, and then re
turns it. note: if no caption exists, createcaption() inserts a new caption directly into the table. the caption does not need to be added separately as would be the case if document.createelement() had been used to create the new <caption> element. syntax htmltableelement = table.createcaption(); re
turn value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> </table> javascript let table = docum...
HTMLTableElement.createTFoot() - Web APIs
the htmltableelement.createtfoot() method re
turns the <tfoot> element associated with a given <table>. if no footer exists in the table, this methods creates it, and then re
turns it. note: if no footer exists, createtfoot() inserts a new footer directly into the table. the footer does not need to be added separately as would be the case if document.createelement() had been used to create the new <tfoot> element. syntax htmltablesectionelement = table.createtfoot(); re
turn value htmltablesectionelement example let myfoot = mytable.createtfoot(); // now this should be true: myfoot == mytable.tfoot specifications specification status comment html living standardthe definition of 'htmltableelement: createtfoot' in that specification. living standard ...
HTMLTableElement.createTHead() - Web APIs
the htmltableelement.createthead() method re
turns the <thead> element associated with a given <table>. if no header exists in the table, this method creates it, and then re
turns it. note: if no header exists, createthead() inserts a new header directly into the table. the header does not need to be added separately as would be the case if document.createelement() had been used to create the new <thead> element. syntax htmltablesectionelement = table.createthead(); re
turn value htmltablesectionelement example let myhead = mytable.createthead(); // now this should be true: myhead == mytable.thead specifications specification status comment html living standardthe definition of 'htmltableelement: createthead' in that specification. living standard ...
HTMLTableElement.deleteRow() - Web APIs
the htmltableelement.deleterow() method removes a specific row (<tr>) from a given <table>. syntax htmltableelement.deleterow(index) parameters index index is an integer representing the row that should be deleted. however, the special index -1 can be used to remove the very last row of a table. re
turn value no re
turn value errors thrown if the number of the row to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception index_size_err is thrown. example this example uses javascript to delete a table's second row. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>...
HTMLTableElement.rows - Web APIs
syntax htmlcollectionobject = table.rows; value an htmlcollection providing a live-updating list of the htmltablerowelement objects representing all of the <tr> elements contained in the table. this provides quick access to all of the table rows, without having to manually search for them. ...
HTMLTableElement.tBodies - Web APIs
for example: <table> <tr> <td>cell one</td> </tr> </table> the html dom generated from the above html will have a <tbody> element even though the tags are not included in the source html. syntax htmlcollectionobject = table.tbodies example this snippet gets the number of bodies in a table. ...
HTMLTableRowElement.rowIndex - Web APIs
the htmltablerowelement.rowindex read-only property represents the position of a row in relation to the whole <table>. even when the <thead>, <tbody>, and <tfoot> elements are out of order in the html, browsers render the table in the right order. therefore the rows count from <thead> to <tbody>, from <tbody> to <tfoot>. syntax var index = htmltablerowelement.rowindex value re
turns the index of the row, or -1 if the row is not part of a table. example this example uses javascript to label all the row numbers in a table. html <table> <thead> <tr><th>item</th> <th>price</th></tr> </thead> <tbody> <tr><td>bananas</td> <td>$2</td></tr> <tr><td>oranges</td> <td>$8</td></tr> <tr><td>top sirloin</td> <td>$20</td></tr> </tbody> <tfoot> <tr><td>tot...
HTMLTableSectionElement - Web APIs
d; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmltablesectionelement.align is a domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of the element's contents with respect to the surrounding context. the possible values are "left", "right", and "center". htmltablesectionelement.rows read only re
turns a live htmlcollection containing the rows in the section. the htmlcollection is live and is automatically updated when rows are added or removed. htmltablesectionelement.ch is a domstring containing one single chararcter. this character is the one to align all the cell of a column on. it reflects the char and default to the decimal points associated with the language, e.g. '.' for english, o...
HTMLTemplateElement.content - Web APIs
syntax var documentfragment = templateelement.content example var templateelement = document.queryselector("#foo"); var documentfragment = templateelement.content.clonenode(true); specifications specification status comment html living standardthe definition of 'htmltemplateelement interface' in that specification. living standard html5the definition of 'htmltemplateelement interface' in that specification. ...
HTMLTextAreaElement.labels - Web APIs
the htmltextareaelement.labels read-only property re
turns a nodelist of the <label> elements associated with the <textarea> element. syntax var labelelements = textarea.labels; re
turn value a nodelist containing the <label> elements associated with the <textarea> element. example html <label id="label1" for="test">label 1</label> <textarea id="test">some text</textarea> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const textarea = document.getelementbyid("test"); for(var i = 0; i < textarea.labels.length; i++) { console.log(textarea.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'la...
HTMLVideoElement.msFrameStep() - Web APIs
e in the future. the htmlvideoelement.msframestep() method steps the video by one frame forward or one frame backward. this proprietary method is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msframestep(forward); parameters forward a boolean which if set to true steps the video forward by one frame, if false steps the video backwards by one frame. re
turn value this method does not re
turn a value. see also htmlmediaelement microsoft api extensions ...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
icrosoft edge. syntax str = htmlmediaelement.msinsertvideoeffect(activatableclassid: domstring, effectrequired: boolean, config); parameters activatableclassid a domstring defining the video effects class. effectrequired a boolean which if set to true requires a video effect to be defined. configoptional an optional object to help with defining any additional configuration needed. re
turn value this method does not re
turn a value. example var ovideo1 = document.getelementbyid("video1"); ovideo1.msinsertvideoeffect("windows.media.videoeffects.videostabilization", true, null); see also htmlvideoelement microsoft api extensions ...
msSetVideoRectangle - Web APIs
) method sets the dimensions of a sub-rectangle within a video. this proprietary method is specific to internet explorer and microsoft edge. syntax htmlvideoelement.mssetvideorectangle(); parameters left a number representing left-side position. top a number representing top position. right a number representing right-side position. bottom a number representing bottom position. re
turn value this method does not re
turn a value. example htmlvideoelement.mssetvideorectangle(left: 2, top: 0, right: 4, bottom: 4); see also htmlvideoelement microsoft api extensions ...
msStereo3DPackingMode - Web APIs
mpatibilities between implementations and the behavior may change in the future. msstereo3dpackingmode is a read/write property which gets or sets the frame-packing mode for stereo 3-d video content. this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msstereo3dpackingmode(topbottom, sidebyside, none); value the following values re
turn, or set, the stereo 3-d content packing as "topbottom", "sidebyside", or "none" for regular 2-d video. none (0): specifies regular 2-d video. topbottom (1): specifies stereo 3-d content packing and that the views are packed side-by-side in a single frame. sidebyside (2): specifies sidebyside stereo 3-d content packing and that the views are packed top-to-bottom in a single frame. see also ...
Dragging and Dropping Multiple Items - Web APIs
ransfer. the following example retrieves a set of files being dragged and adds them to an array. function ondrop(event) { var files = []; var dt = event.datatransfer; for (var i = 0; i < dt.mozitemcount; i++) files.push(dt.mozgetdataat("application/x-moz-file", i)); } you may also wish to check if the desired format exists using the moztypesat method. as with the types property, it re
turns a list of strings of the types for an item. types property is equivalent to retrieving the list of types for the item at index 0. var types = event.datatransfer.moztypesat(1); dragging non-string data the additional methods described above are also not restricted to string data; you can specify any type of data. for example, files are dragged using the application/x-moz-file type stored as ...
HashChangeEvent - Web APIs
hange', locationhashchanged); polyfill there are several fallback scripts listed on the modernizr github page. basically, those scripts check the location.hash at a regular interval. here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // exit if the browser implements that event if ( "onhashchange" in window.document.body ) { re
turn; } var location = window.location, oldurl = location.href, oldhash = location.hash; // check the location hash on a 100ms interval setinterval(function() { var newurl = location.href, newhash = location.hash; // if the hash has changed and a handler has been bound... if ( newhash != oldhash && typeof window.onhashchange === "function" ) { // execute ...
Headers.entries() - Web APIs
the headers.entries() method re
turns an iterator allowing to go through all key/value pairs contained in this object. the both the key and value of each pairs are bytestring objects. note: this method is available in web workers. syntax headers.entries(); re
turn value re
turns an iterator. example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the key/value pairs for (var pair of myheaders.entries()) { console.log(pair[0]+ ': '+ pair[1]); } the result is: content-type: text/xml vary: accept-language ...
Headers.keys() - Web APIs
the headers.keys() method re
turns an iterator allowing to go through all keys contained in this object. the keys are bytestring objects. note: this method is available in web workers. syntax headers.keys(); re
turn value re
turns an iterator. example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the keys for(var key of myheaders.keys()) { console.log(key); } the result is: content-type vary ...
Headers.values() - Web APIs
the headers.values() method re
turns an iterator allowing to go through all values contained in this object. the values are bytestring objects. note: this method is available in web workers. syntax headers.values(); re
turn value re
turns an iterator. example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the values for (var value of myheaders.values()) { console.log(value); } the result is: text/xml accept-language ...
History.length - Web APIs
syntax const length = history.length specifications specification status comment html living standardthe definition of 'history.length' in that specification. living standard no change from html5. html5the definition of 'history.length' in that specification. ...
History.state - Web APIs
this is a way to look at the state without having to wait for a popstate event. syntax const currentstate = history.state value the state at the top of the history stack. the value is null until the pushstate() or replacestate() method is used. examples the code below logs the value of history.state before using the pushstate() method to push a value to the history. the next line logs the value to the console again, showing that history.state now has a value. ...
History - Web APIs
the history interface allows manipulation of the browser session history, that is the pages visited in the tab or frame that the current page is loaded in. properties the history interface doesn't inherit any property. length read only re
turns an integer representing the number of elements in the session history, including the currently loaded page. for example, for a page loaded in a new tab this property re
turns 1. scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. state read only re
turns 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 d...
IDBCursor.direction - Web APIs
see the values section below for possible values. note: this feature is available in web workers. syntax var direction = cursor.direction; value a string (defined by the idbcursordirection enum) indicating the direction in which the cursor is traversing the data. possible values are: value description next this direction causes the cursor to be opened at the start of the source. nextunique this direction causes the cursor to be opened at the start of the source. ...
IDBCursor.key - Web APIs
if the cursor is outside its range, this is set to undefined. the cursor's key can be any data type. note: this feature is available in web workers. syntax var key = cursor.key; value a value of any type. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. within each iteration we log the key of the cursor to the console, something like this (its the album title in each case, which is our key). the cursor does not require us to select the data based on a key; we can just grab all of it. ...
IDBCursor.primaryKey - Web APIs
if the cursor is currently being iterated or has iterated outside its range, this is set to undefined. the cursor's primary key can be any data type. note: this feature is available in web workers. syntax var value = cursor.primarykey; value a value of any data type. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. ...
IDBCursor.request - Web APIs
note: this feature is available in web workers. syntax var request = cursor.request; value an idbrequest object instance. examples when you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from. ...
IDBCursor.source - Web APIs
note: this feature is available in web workers. syntax var source = cursor.source; value the idbobjectstore or idbindex that the cursor is iterating over. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. ...
IDBCursor.update() - Web APIs
the update() method of the idbcursor interface re
turns an idbrequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store. if the cursor points to a record that has just been deleted, a new record is created. be aware that you can't call update() (or idbcursor.delete()) on cursors obtained from idbindex.openkeycursor(). for such needs, you have to use idbindex.opencursor() instead. note: this feature is available in web workers. syntax var anidbrequest = myidbcursor.update(value); parameters value the new value to be stored at the current position. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types:...
IDBCursorSync - Web APIs
onically decreasing in the order of keys. prev_no_duplicate 3 this cursor does not include duplicates, and its direction is monotonically decreasing in the order of keys. methods continue() advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. if no key is specified, advance to the immediate next position. re
turns false if the cursor has reached the end of its range; otherwise re
turns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (databaseexception); exceptions this method can raise an idbdatabaseexception with the...
IDBCursorWithValue.value - Web APIs
note: this feature is available in web workers. syntax var value = myidbcursorwithvalue.value; value the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. within each iteration we log the value of the cursor with cursor.value. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. ...
IDBCursorWithValue - Web APIs
x" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbcursorwithvalue</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} methods inherits methods from its parent interface, idbcursor. properties inherits properties from its parent interface, idbcursor. idbcursorwithvalue.value read only re
turns the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the loop, you can grab data from the current record under the cursor object using c...
IDBDatabase.close() - Web APIs
the connection is not actually closed until all transactions created using this connection are complete. no new transactions can be created for this connection once this method is called. methods that create transactions throw an exception if a closing operation is pending. note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. ...
IDBDatabase: error event - Web APIs
the error event is fired on idbdatabase when a request re
turns an error and the event bubbles up to the connection object. bubbles yes cancelable no interface event event handler property onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will conta...
IDBDatabase.onerror - Web APIs
note: consider using idbopendbrequest.onsuccess instead (see idbrequest.onsuccess, where it is inherited from). note: this feature is available in web workers. syntax idbdatabase.onerror = function(event) { ... } example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases. ...
IDBFactory - Web APIs
eddb. 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 re
turns a result indicating which one is greater in value. idbfactory.databases a method that re
turns a list of all available databases, including their names and versions. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) // in the follo...
IDBIndex.getAll() - Web APIs
, though, you should use getall(). syntax var getallkeysrequest = idbindex.getall(); var getallkeysrequest = idbindex.getall(query); var getallkeysrequest = idbindex.getall(query, count); parameters query optional a key or an idbkeyrange identifying the records to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to re
turn. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description ...
IDBIndex.getAllKeys() - Web APIs
the result of the request object. syntax var allkeysrequest = idbindex.getallkeys(); var allkeysrequest = idbindex.getallkeys(query); var allkeysrequest = idbindex.getallkeys(query, count); parameters query optional a key or an idbkeyrange identifying the keys to retrieve. if this value is null or missing, the browser will use an unbound key range. count optional the number records to re
turn. if this value exceeds the number of records in the query, the browser will only retrieve the first item. if it is lower than 0 or greater than 232-1 a typeerror exception will be thrown. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of the following types: exception description ...
IDBIndex.isAutoLocale - Web APIs
the isautolocale read-only property of the idbindex interface re
turns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) syntax var myindex = objectstore.index('index'); console.log(myindex.isautolocale); value a boolean. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the isautolocale value is logged to the console. function displaydatabyindex() { tablee...
IDBIndex.keyPath - Web APIs
the keypath property of the idbindex interface re
turns the key path of the current index. if null, this index is not auto-populated. note: this feature is available in web workers. syntax var mykeypath = myindex.keypath; value any data type that can be used as a key path. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the re
turned records are sorted based on the index, not the primary key. the key path of the current index is logged to the console: it should be re
turned as lname. finally, we iterate through each recor...
IDBIndex.name - Web APIs
ion is not active. constrainterror an index is already using the specified name. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor() — this works the same as opening a cursor directly on an idbobjectstore using opencursor() except that the re
turned records are sorted based on the index, not the primary key. the name of the index is logged to the console: it should be re
turned as lname. finally, we iterate through each record, inserting the data into an html table. for a complete working example, see our idbindex-example demo repo (view the example live). function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = d...
IDBKeyRange.bound() - Web APIs
keyrange.bound(lower, upper, loweropen, upperopen); parameters lower specifies the lower bound of the new key range. upper specifies the upper bound of the new key range. loweropen optional indicates whether the lower bound excludes the endpoint value. the default is false. upperopen optional indicates whether the upper bound excludes the endpoint value. the default is false. re
turn value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the following conditions raise an exception: the lower or upper parameters were not passed a valid key. the lower key is greater than the upper key. the lower key and upper key match and eit...
IDBKeyRange.lower - Web APIs
note: this feature is available in web workers. syntax var lower = mykeyrange.lower value the lower bound of the key range (can be any type.) example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. ...
IDBKeyRange.lowerBound() - Web APIs
, it includes the lower endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the new key range. open optional indicates whether the lower bound excludes the endpoint value. the default is false. re
turn value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use a lower bound key range. here we declare keyrangevalue = idbkeyrange.lowerbound("f", fal...
IDBKeyRange.lowerOpen - Web APIs
note: this feature is available in web workers. syntax var loweropen = mykeyrange.loweropen value a boolean: value indication true the lower-bound value is not included in the key range. false the lower-bound value is included in the key range. example the following example illustrates how you'd use a key range. ...
IDBKeyRange.only() - Web APIs
exceptions this method may raise a domexception of the following types: exception description dataerror the value parameter passed was not a valid key. ...
IDBKeyRange.upper - Web APIs
note: this feature is available in web workers. syntax var upper = mykeyrange.upper value the upper bound of the key range (can be any type.) example the following example illustrates how you'd use a key range. here we declare keyrangevalue = idbkeyrange.upperbound("f", "w", true, true); — a range that includes everything between "f" and "w" but not including them — since both the upper and lower bounds have been declared as open (true). we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value. ...
IDBKeyRange.upperBound() - Web APIs
ce creates a new upper-bound key range. by default, it includes the upper endpoint value and is closed. note: this feature is available in web workers. syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the new key range. open indicates whether the upper bound excludes the endpoint value. the default is false. optional re
turn value idbkeyrange: the newly created key range. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an upper bound key range. here we declare keyrangevalue = idbkeyrange.upperbound("f"); — a ra...
IDBKeyRange.upperOpen - Web APIs
note: this feature is available in web workers. syntax var upperopen = mykeyrange.upperopen value a boolean: value indication true the upper-bound value is not included in the key range. false the upper-bound value is included in the key range. example the following example illustrates how you'd use a key range. ...
FileHandle.getFile() - Web APIs
t 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. summary the getfile method allows to retrieve a read-only snapshot of the handled file in the form of a file object. syntax var request = instanceoffilehandle.getfile(); re
turn a domrequest object. in case of success, the request's result is a file object. specifications specification status comment filesystem api editor's draft draft proposal ...
FileHandle.open() - Web APIs
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. summary the open method re
turns a lockedfile object that allows to safely write in the file. syntax var myfile = instanceoffilehandle.open(mode); parameters mode a string that specifies the writing mode for the file. it can be readonly or readwrite. re
turn a lockedfile object. specifications specification status comment filesystem api editor's draft draft proposal ...
IDBMutableFile - Web APIs
atabase.createmutablefile method. properties mutablefile.name read only the name of the handled file. mutablefile.type read only the mime type of the handled file. events handler mutablefile.onabort the abort event is triggered each time the handled file is aborted. mutablefile.onerror the error event is triggered each time something goes wrong. methods mutablefile.open() re
turns a lockedfile object to read or write the associated file safely. mutablefile.getfile() re
turns a domrequest object. in case of success, the request's result is a file object representing a snapshot of the handled file. specifications not part of any specification at present. see also lockedfile file ...
IDBObjectStore.autoIncrement - Web APIs
note that every object store has its own separate auto increment counter. note: this feature is available in web workers. syntax var myautoincrement = objectstore.autoincrement; value a boolean: value meaning true the object store auto increments. false the object store does not auto increment. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.autoincrement to the console. ...
IDBObjectStore.clear() - Web APIs
the clear() method of the idbobjectstore interface creates and immediately re
turns an idbrequest object, and clears this object store in a separate thread. this is for deleting all the current data out of an object store. clearing an object store consists of removing all records from the object store and removing all records in indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); re
turns an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlye...
IDBObjectStore.count() - Web APIs
the count() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, re
turns the total number of records that match the provided key or idbkeyrange. if no arguments are provided, it re
turns the total number of records in the store. note: this feature is available in web workers. syntax var request = objectstore.count(); var request = objectstore.count(query); parameters query optional a key or idbkeyrange object that specifies a range of records you want to count. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror this idbobjectstore has been dele...
IDBObjectStore.deleteIndex() - Web APIs
n the connected database, used during a version upgrade. note that this method must be called only from a versionchange transaction mode callback. note that this method synchronously modifies the idbobjectstore.indexnames property. note: this feature is available in web workers. syntax objectstore.deleteindex(indexname); parameters indexname the name of the existing index to remove. re
turn value undefined exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror occurs if the method was not called from a versionchange transaction mode callback. transactioninactiveerror occurs if the transaction this idbobjectstore belongs to is not active (e.g. has been deleted or removed.) in f...
IDBObjectStore.getKey() - Web APIs
the getkey() method of the idbobjectstore interface re
turns an idbrequest object, and, in a separate thread, re
turns the key selected by the specified query. this is for retrieving specific records from an object store. if a key is successfully found, then a structured clone of it is created and set as the result of the request object. note: this feature is available in web workers. syntax var request = objectstore.getkey(key); parameters key the key or key range that identifies the record to be retrieved. re
turn value an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's ...
IDBObjectStore.indexNames - Web APIs
note: this feature is available in web workers. syntax var myindexnames = objectstore.indexnames; value a domstringlist. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.indexnames to the console. ...
IDBObjectStore.keyPath - Web APIs
if this property is null, the application must provide a key for each modification operation. note: this feature is available in web workers. syntax var mykeypath = objectstore.keypath; value any value type. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.keypath to the console. ...
IDBObjectStore.transaction - Web APIs
note: this feature is available in web workers. syntax var mytransaction = objectstore.transaction; value an idbtransaction object. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.transaction to the console. ...
IDBTransaction.objectStoreNames - Web APIs
specification specification status comment indexed database api 2.0the definition of 'objectstorenames' in that specification. recommendation indexed database api draftthe definition of 'objectstorenames' in that specification. recommendation browser compatibility the compatibility table on this page is generated from structured data. ...
IDBTransaction.commit() - Web APIs
l outstanding requests have been satisfied and no new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. if it is called on a transaction that is not active, it throws an invalidstateerror domexception. note: this feature is available in web workers. syntax transaction.commit(); parameters none. re
turn value void. exceptions exception description invalidstateerror the transaction state is not active. examples // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transactio...
IDBTransaction: error event - Web APIs
the error event is fired on idbtransaction when a request re
turns an error and the event bubbles up to the transaction object. bubbles yes cancelable no interface event event handler property onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will c...
IDBTransaction.objectStore() - Web APIs
the objectstore() method of the idbtransaction interface re
turns an object store that has already been added to the scope of this transaction. every call to this method on the same transaction object, with the same name, re
turns the same idbobjectstore instance. if this method is called on a different transaction object, a different idbobjectstore instance is re
turned. note: this feature is available in web workers. syntax idbtransaction.objectstore(name); parameters name the name of the requested object store. re
turn value an idbobjectstore object for accessing an object store. exceptions this method may raise a domexception of one of the following types: exception description notfounderror the requested object store is not in this transaction's sco...
IDBTransaction.onerror - Web APIs
note: consider using idbtransaction.onabort instead to handle non- successful completion of the transaction. note: this feature is available in web workers. syntax transaction.onerror = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. ...
IDBTransactionSync - Web APIs
e this transaction was created. void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() re
turns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexception); parameters name the name of the requested object store. re
turns idbobjectstoresync an object for accessing the requested object store. exceptions the method can raise an idbdatabaseexception with the following code: ...
IDBVersionChangeEvent.newVersion - Web APIs
note: this feature is available in web workers. syntax var newversion = idbversionchangeevent.newversion value a 64-bit integer. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. these events are fired via the custom idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test. ...
IDBVersionChangeEvent.oldVersion - Web APIs
when the opened database doesn't exist yet, the value of oldversion is 0. note: this feature is available in web workers. syntax var oldversion = idbversionchangeevent.oldversion value a 64-bit integer. example var dbname = "sampledb"; var dbversion = 2; var request = indexeddb.open(dbname, dbversion); request.onupgradeneeded = function(e) { var db = request.result; if (e.oldversion < 1) { db.createobjectstore("store1"); } if (e.oldversion < 2) { db.deleteobjectstore("store1"); db.createobjectstore("store2"); } // etc. for version < 3, 4... ...
IDBVersionChangeEvent.version - Web APIs
warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to know what browsers support them. syntax readonly attribute unsigned long long? version; value a 64-bit integer. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
IDBVersionChangeEvent - Web APIs
the idbversionchangeevent interface of the indexeddb api indicates that the version of the database has changed, as the result of an idbopendbrequest.onupgradeneeded event handler function. note: this feature is available in web workers. properties also inherits properties from its parent, method. idbversionchangeevent.oldversion read only re
turns the old version of the database. idbversionchangeevent.newversion read only re
turns the new version of the database. deprecated properties idbversionchangeevent.version read only the new version of the database in a versionchange transaction. warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to ...
IDBVersionChangeRequest - Web APIs
the idbopendbrequest interface which has now the onblocked handler and the newly needed onupgradeneeded one. the idbversionchangerequest interface the indexeddb api represents a request to change the version of a database. it is used only by the setversion() method of idbdatabase. methods inherits from: idbrequest idbversionchangerequest.setversion updates the version of the database. re
turns immediately and runs a versionchange transaction on the connected database in a separate thread. attributes attribute type description onblocked function the event handler for the blocked event. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https:...
IIRFilterNode() - Web APIs
a reference to an audiocontext. options options are as follows: feedforward: a sequence of feedforward coefficients. feedback: a sequence of feedback coefficients. unlike other nodes in the web audio api, the options passed into the iir filter upon creation are not optional. the filter needs these values to work and with the vast range of filters available, there is no default. re
turn value a new iirfilternode object instance. examples let feedforward = [0.00020298, 0.0004059599, 0.00020298]; let feedbackward = [1.0126964558, -1.9991880801, 0.9873035442]; const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = new iirfilternode(audioctx, { feedforward: feedforward, feedback: feedbackward }); specificat...
IIRFilterNode.getFrequencyResponse() - Web APIs
yarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. magresponseoutput a float32array to receive the computed magnitudes of the freqency response for each frequency value in the frequencyarray. phaseresponseoutput a float32array to receive the computed phase response values in radians for each frequency value in the input frequencyarray. re
turn value undefined exceptions notsupportederror the three arrays provided are not all of the same length. examples in the following example we are using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies. we first create t...
IdleDeadline.didTimeout - Web APIs
the read-only didtimeout property on the idledeadline interface is a boolean value which indicates whether or not the idle callback is being invoked because the timeout interval specified when window.requestidlecallback() was called has expired. if didtimeout is true, the idledeadline object's timeremaining() method will re
turn approximately 0. idle callbacks support the concept of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available. your callback will typically check the value of didtimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things ...
IdleDeadline - Web APIs
callback is executing because its timeout duration expired. to learn more about how request callbacks work, see collaborative scheduling of background tasks. properties idledeadline.didtimeout read only a boolean whose value is true if the callback is being executed because the timeout specified when the idle callback was installed has expired. methods idledeadline.timeremaining() re
turns a domhighrestimestamp, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. if the idle period is over, the value is 0. your callback can call this repeatedly to see if there's enough time left to do more work before re
turning. example see our complete example in the article cooperative scheduling of background tasks api.
ImageBitmap.height - Web APIs
specifications specification status comment html living standardthe definition of 'imagebitmap.height' in that specification. ...
ImageBitmap.width - Web APIs
specifications specification status comment html living standardthe definition of 'imagebitmap.height' in that specification. ...
ImageCapture() constructor - Web APIs
the imagecapture() constructor creates a new imagecapture object. syntax const imagecapture = new imagecapture(videotrack) parameters videotrack a mediastreamtrack from which the still images will be taken. this can be any source, such as an incoming stream of a video conference, a playing movie, or the stream from a webcam. re
turn value a new imagecapture object which can be used to capture still frames from the specified video track. example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; ...
ImageData.data - Web APIs
data is stored as a one-dimensional array in the rgba order, with integer values between 0 and 255 (inclusive). syntax imagedata.data examples getting an imagedata object's pixel data this example creates an imagedata object that is 100 pixels wide and 100 pixels tall, making 10,000 pixels in all. the data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all. ...
ImageData.height - Web APIs
syntax imagedata.height example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall. thus, the height property is 100. let imagedata = new imagedata(200, 100); console.log(imagedata.height); // 100 specification specification status comment html living standardthe definition of 'imagedata.height' in that specification. ...
ImageData.width - Web APIs
syntax imagedata.width example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall. thus, the width property is 200. let imagedata = new imagedata(200, 100); console.log(imagedata.width); // 200 specification specification status comment html living standardthe definition of 'imagedata.width' in that specification. ...
Basic concepts - Web APIs
nstances 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 re
turning 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 succeeded or failed. this sounds a little compl...
InputDeviceCapabilities - Web APIs
the inputdevicecapabilities() constructor creates a new inputdevicecapabilities object provides information about the physical device responsible for generating a touch event. syntax var inputdevicecapabilities = new inputdevicecapabilities([inputdevicecapabilitiesinit]) re
turns an instance of the inputdevicecapabilities interface. parameters inputdevicecapabilitiesinit optional a dictionary object containing a set of device capabilities. it contains the following property. firetouchevents: a boolean that indicates whether the device dispatches touch events. specifications specification status comment inputdevicecapabilities draft initial definition. ...
InputEvent.data - Web APIs
this may be an empty string if the change doesn't insert text (such as when deleting characters, for example). syntax var astring = inputevent.data; value a domstring. examples in the following simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the inputevent.data property and reported in the paragraph below the input. ...
InputEvent.dataTransfer - Web APIs
syntax var datatransfer = inputevent.datatransfer value a datatransfer object. examples in the following simple example we've set up an event listener on the input event so that when any content is pasted into the contenteditable <p> element, its html source is retrieved via the inputevent.datatransfer.getdata() method and reported in the paragraph below the input. try copying and pasting some of the content provided to see the effects. ...
InputEvent.getTargetRanges() - Web APIs
specifications specification status comment input events level 2the definition of 'gettargetranges()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
InputEvent.inputType - Web APIs
possible changes include for example inserting, deleting, and formatting text. syntax var astring = inputevent.inputtype; value a domstring containing the type of input that was made. there are many possible values, such as inserttext, deletecontentbackward, insertfrompaste, and formatbold. for a complete list of the available input types, see the attributes section of the input events level 1 spec. examples this example logs the inputtype for input events on an editable <div>. ...
InputEvent.isComposing - Web APIs
the inputevent.iscomposing read-only property re
turns a boolean value indicating if the event is fired after compositionstart and before compositionend. syntax var bool = event.iscomposing; example var inputevent = new inputevent('syntheticinput', false); console.log(inputevent.iscomposing); // re
turn false specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'inputevent.iscomposing' in that specification. obsolete initial definition. ...
enabled - Web APIs
the method reflects the value of the software installation preference in the user interface, and of the xpinstall.enabled preference in pref.js. ...
install - Web APIs
parameters the install method has the following parameters: xpilist an array of files to be installed (see example below). callbackfunc an optional callback function invoked when the installation is complete (see example below). firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. re
turns install re
turns true if the function succeeded and false if it did not, but these values are not always reliable as a determinant of the success of the operation. to surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below. description in the example below, a special javascript object constructor is used to creat...
installChrome - Web APIs
pe, url, name ) parameters the installchrome method has the following parameters: type type can be installtrigger.skin or installtrigger.locale. url url is a string containing a full or relative url to download name name is displayed in the dialog, but is also used to *select* the theme somust match exactly the name in the internal manifest.rdf file. re
turns a boolean value indicating false if the software install feature has been
turned off, and true if it's on. note that this re
turn value does not indicate anything about the success of the installation. description installchrome is a special method for installing new chrome in netscape 6 and mozilla. the method performs a simplified installation of language packs or netscape 6/mozilla skins, and s...
startSoftwareUpdate - Web APIs
summary triggers the downloading and installation of the software at the specified url. method of installtrigger object syntax boolean startsoftwareupdate ( string url); parameters the startsoftwareupdate method has the following parameter: url a uniform resource locator specifying the location of the xpi file containing the software. re
turns true. description the startsoftwareupdate method triggers a software download and install from the specified url. this method has been largely superseded by newer install method, which is more flexible and allows you to install more than one xpi. note also that xpis installed with this method must have their own install.js files in which the full installation is defined. ...
InstallTrigger - Web APIs
stalltrigger object to install netscape 6/mozilla skins and language packs, and perform multiple-package installations with install. compareversion compares the version of a file or package with the version of an existing file or package. enabled indicates whether or not software installation is enabled for this client machine. getversion re
turns an object representing the version number from the client version registry for the specified component. it is used in both trigger scripts and installation scripts. install installs one or more xpi files on the local machine. installchrome installs new skin or locale packages in netscape 6 and mozilla. startsoftwareupdate triggers the downloading a...
IntersectionObserver.disconnect() - Web APIs
the intersectionobserver method disconnect() stops watching all of its target elements for visibility changes. syntax intersectionobserver.disconnect(); parameters none. re
turn value undefined. specifications specification status comment intersection observerthe definition of 'intersectionobserver.disconnect()' in that specification. working draft initial definition. ...
IntersectionObserver.observe() - Web APIs
this design allows multiple elements' intersection changes to be processed by a single call to the callback. syntax intersectionobserver.observe(targetelement); parameters targetelement an element whose visibility within the root is to be monitored. this element must be a descendant of the root element (or contained wtihin the current document, if the root is the document's viewport). re
turn value undefined. examples <<<...>>> specifications specification status comment intersection observerthe definition of 'intersectionobserver.observe()' in that specification. working draft initial definition. ...
IntersectionObserver.rootMargin - Web APIs
ing box. syntax var marginstring = intersectionobserver.rootmargin; value a string, formatted similarly to the css margin property's value, which contains offsets for one or more sides of the root's bounding box. these offsets are added to the corresponding values in the root's bounding box before the intersection between the resulting rectangle and the target element's bounds. the string re
turned by this property may not match the one specified when the intersectionobserver was instantiated. the browser is permitted to alter the values if rootmargin isn't specified when the object was instantiated, it defaults to the string "0px 0px 0px 0px", meaning that the intersection will be computed between the root element's unmodified bounds rectangle and the target's bounds. the root element ...
IntersectionObserver.thresholds - Web APIs
if only one threshold ratio was provided when instanitating the object, this will be an array containing that single value. see thresholds in intersection observer api to learn how thresholds work. syntax var thresholds = intersectionobserver.thresholds; value an array of intersection thresholds, originally specified using the threshold property when instantiating the observer. if only one observer was specified, without being in an array, this value is a one-entry array containing that threshold. ...
IntersectionObserver.unobserve() - Web APIs
the intersectionobserver method unobserve() instructs the intersectionobserver to stop observing the specified target element. syntax intersectionobserver.unobserve(target); parameters target the element to cease observing. if the specified element isn't being observed, this method does nothing and no exception is thrown. re
turn value undefined. example this snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new intersectionobserver(callback); observer.observe(document.getelementbyid("elementtoobserve")); /* ... */ observer.unobserve(document.getelementbyid("elementtoobserve")); specifications specification status comment intersection observerthe definition of 'intersectionobserver.un...
IntersectionObserverEntry.boundingClientRect - Web APIs
syntax var boundsrect = intersectionobserverentry.boundingclientrect; value a domrectreadonly which describes the smallest rectangle that contains every part of the target element whose intersection change is being described. this value is obtained using the same algorithm as element.getboundingclientrect(), so refer to that article for details on precisely what is done to obtain this rectangle and what is and is not included within its bounds. ...
IntersectionObserverEntry.intersectionRatio - Web APIs
ntry.intersectionratio; value a number between 0.0 and 1.0 which indicates how much of the target element is actually visible within the root's intersection rectangle. more precisely, this value is the ratio of the area of the intersection rectangle (intersectionrect) to the area of the target's bounds rectangle (boundingclientrect). if the area of the target's bounds rectangle is zero, the re
turned value is 1 if isintersecting is true or 0 if not. example in this simple example, an intersection callback sets each target element's opacity to the intersection ratio of that element with the root. function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.style.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at hand...
InterventionReportBody - Web APIs
an intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. so for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it. properties id a string representing the intervention that generated the report. this can be used to group reports by deprecated feature. ...
Keyboard - Web APIs
the keyboard interface of the the keyboard api provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard. a list of valid code values is found in the ui events keyboardevent code values spec. properties none. methods keyboard.getlayoutmap() re
turns a promise that resolves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. keyboard.lock() re
turns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard. keyboard.unlock() unlocks all keys captured by the lock() method and re
turns synchronously. example the following example demonstrates how to get the location- or la...
KeyboardEvent.altKey - Web APIs
the keyboardevent.altkey read-only property is a boolean that indicates if the alt key (option or ⌥ on os x) was pressed (true) or not (false) when the event occured. syntax var altkeypressed = instanceofkeyboardevent.altkey re
turn value boolean examples <html> <head> <title>altkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key keydown: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "alt key keydown: " + e.altkey + "\n" ); } </script> </head> <body onkeydown="showchar(event);"> <p> press any character key, with or without holding down the alt key.<br /> you can also use the shift key together with the alt key. </p> </body> </html> specifications specification status comment ...
KeyboardEvent.charCode - Web APIs
the charcode read-only property of the keyboardevent interface re
turns the unicode value of a character key pressed during a keypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; re
turn value a number that represents the unicode value of the character key that was pressed. example html <p>type anything into the input box below to log a <code>charcode</code>.</p> <input type="text" /> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.queryselector('#log'); input.addeventlistener('keypress', function(e) { log.innertext = `key pressed: ${string.fromcharcode(e.charcode)}\ncharcode: ${e.charcode}`; }); result notes in a keypress event, the unicode val...
KeyboardEvent: code values - Web APIs
kvk_ansi_0 (0x1d) "digit0" "digit0" kvk_ansi_rightbracket (0x1e) "bracketright" "bracketright" kvk_ansi_o (0x1f) "keyo" "keyo" kvk_ansi_u (0x20) "keyu" "keyu" kvk_ansi_leftbracket (0x21) "bracketleft" "bracketleft" kvk_ansi_i (0x22) "keyi" "keyi" kvk_ansi_p (0x23) "keyp" "keyp" kvk_re
turn (0x24) "enter" "enter" kvk_ansi_l (0x25) "keyl" "keyl" kvk_ansi_j (0x26) "keyj" "keyj" kvk_ansi_quote (0x27) "quote" "quote" kvk_ansi_k (0x28) "keyk" "keyk" kvk_ansi_semicolon (0x29) "semicolon" "semicolon" kvk_ansi_backslash (0x2a) "backslash" "backslash" kvk_ansi_comma (0x2b) "comma" "...
KeyboardEvent.isComposing - Web APIs
the keyboardevent.iscomposing read-only property re
turns a boolean value indicating if the event is fired within a composition session, i.e. after compositionstart and before compositionend. syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // re
turn false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'keyboardevent.prototype.iscomposing' in that specification. obsolete initial definition. ...
LinearAccelerationSensor.y - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var yacceleration = accelerometer.y value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
LinearAccelerationSensor.z - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var zacceleration = accelerometer.z value a number. example linear acceleration is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
LinearAccelerationSensor - Web APIs
feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor linearaccelerationsensor.linearaccelerationsensor() creates a new linearaccelerationsensor object. properties linearaccelerationsensor.x read only re
turns a double containing the linear acceleration of the device along the device's x axis. linearaccelerationsensor.y read only re
turns a double containing the linear acceleration of the device along the device's y axis. linearaccelerationsensor.z read only re
turns a double containing the linear acceleration of the device along the device's z axis. example linear acceleration is typically rea...
LocalMediaStream - Web APIs
warning: this interface is no longer available in any mainstream browser. do not use localmediastream; you need to update any code that does use it as soon as possible or your content or application will stop working. see stopping a video stream in mediastreamtrack to learn how. ...
Location: hash - Web APIs
the hash property of the location interface re
turns a usvstring containing a '#' followed by the fragment identifier of the url. the fragment is not percent-decoded. if the url does not have a fragment identifier, this property contains an empty string, "". syntax string = object.hash; object.hash = string; examples <a id="myanchor" href="/docs/location.href#examples">examples</a> <script> var anchor = document.getelementbyid("myanchor"); console.log(anchor.hash); // re
turns '#examples' </script> specifications specification status comment html living standardthe definition of 'hash' in that specification. living standard initial definition ...
Location: hostname - Web APIs
the hostname property of the location interface is a usvstring containing the domain of the url. syntax string = object.hostname; object.hostname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.hostname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.hostname; // re
turns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'hostname' in that specification. living standard initial definition. ...
Location: href - Web APIs
the href property of the location interface is a stringifier that re
turns a usvstring containing the whole url, and allows the href to be updated. setting the value of href navigates to the provided url. if you want redirection, use location.replace(). syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/location/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // re
turns: 'https://developer.mozilla.org/location/href' specifications specification status comment html living standardthe definition of 'href' in that specification. living standard initial definition. ...
Location: origin - Web APIs
lowed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:. e.g "blob:https://mozilla.org" will have "https://mozilla.org". note: this feature is available in web workers. syntax string = object.origin; examples // on this page, re
turns the origin var result = window.location.origin; // re
turns:'https://developer.mozilla.org' specifications specification status comment html living standardthe definition of 'origin' in that specification. living standard initial definition. ...
Location: password - Web APIs
sword specified before the domain name. if it is set without first setting the username property, it silently fails. syntax string = object.password; object.password = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.password; // re
turns:'flabada' ...
Location: pathname - Web APIs
nterface is a usvstring containing an initial '/' followed by the path of the url (or the empty string if there is no path). syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // re
turns:'/docs/location.pathname' specifications specification status comment html living standardthe definition of 'pathname' in that specification. living standard initial definition. ...
Location: port - Web APIs
terface is a usvstring containing the port number of the url. if the url does not contain an explicit port number, it will be set to ''. syntax string = object.port; object.port = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org:443/docs/location.port"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.port; // re
turns:'443' specifications specification status comment html living standardthe definition of 'location.port' in that specification. living standard initial definition. ...
Location: protocol - Web APIs
protocol property of the location interface is a usvstring representing the protocol scheme of the url, including the final ':'. syntax string = object.protocol; object.protocol = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/location.protocol"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.protocol; // re
turns:'https:' specifications specification status comment html living standardthe definition of 'protocol' in that specification. living standard initial definition. ...
Location: search - Web APIs
ern browsers provide urlsearchparams and url.searchparams to make it easy to parse out the parameters from the querystring. syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/location.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // re
turns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'search' in that specification. living standard initial definition. ...
Location: username - Web APIs
username property of the location interface is a usvstring containing the username specified before the domain name. syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // re
turns:'anonymous' ...
Locks.mode - Web APIs
the mode read-only property of the lock interface re
turns the access mode passed to lockmanager.request() when the lock was requested. the mode is either "exclusive" (the default) or "shared". syntax var mode = lock.mode value one of "exclusive" or "shared". example the following examples show how the mode property is passed in the call to lockmanager.request(). lockmanager is the object re
turned by navigator.locks. // should show "exclusive" (the default) navigator.locks.request("my_resource", show_lock_properties); // should show "exclusive" navigator.locks.request("my_resource", {mode: "exclusive"}, show_lock_properties); // should show "shared" navigator.locks.request("my_resource", {mode: "shared"}, show_lock_properties); function show_lock_properties(lock) { console.log(`t...
Locks.name - Web APIs
the name read-only property of the lock interface re
turns the name passed to lockmanager.request selected when the lock was requested. the name of a lock is passed by script when the lock is requested. the name is selected by the developer to represent an abstract resource for which use is being coordinated across multiple tabs, workers, or other code within the origin. for example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as "net_db_sync". syntax var name = lock.name value a domstring. example the following examples show how the name property passed in the call to lockmanager.request(). lockmanager is the object re
turned by navigator.locks. navigator.locks.request("net_db_sync", show_lock...
Lock - Web APIs
the lock interface of the the web locks api provides the name and mode of a previously requested lock, which is received in the callback to lockmanager.request(). properties lock.mode read only re
turns the access mode passed to lockmanager.request() when the lock was requested. the mode is either "exclusive" (the default) or "shared". lock.name read only re
turns the name passed to lockmanager.request() when the lock was requested. examples the following examples show how the mode and name properties are passed in the call to lockmanager.request(). lockmanager is the object re
turned by navigator.locks. navigator.locks.request("net_db_sync", show_lock_properties); navigator.locks.request("another_lock", {mode: "shared"}, show_lock_properties); function show_lock_properti...
LockManager - Web APIs
the lockmanager interface of the the web locks api provides methods for requesting a new lock object and querying for an existing lock object. to get an instance of lockmanager, call navigator.locks. methods lockmanager.request() requests a lock object with parameters specifying its name and characteristics. lockmanager.query() re
turns a promise that resolves with a lockmanagersnapshot which contains information about held and pending locks. specifications specification status comment web locks apithe definition of 'lockmanager' in that specification. draft initial definition. ...
LockedFile.abort() - Web APIs
used to release the lock on the lockedfile object, making it inactive: its active property is set to false and all ongoing operations are canceled. note: when an ongoing operation is canceled, there is no rollback (it is not a database transaction), therefore the file can be corrupted if the canceled operation was performing some writing. syntax var request = instanceoflockedfile.abort(); re
turn a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.append() - Web APIs
nge in the future. summary the append method is used to write some data at the end of the file. the write operation is performed at the end of the file, regardless of the lockedfile.location value, and actually sets this value to null. syntax var request = instanceoflockedfile.append(data); parameters data the data to write into the file. it can be a string or an arraybuffer. re
turn a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.flush() - Web APIs
. for performance reasons, a lockedfile object buffers all its operation in memory. this allows fast writing and reading operations. periodically, the data are written onto disk. however, if something goes wrong before that, some operations can be lost. to avoid that, it's possible to force a write onto the disk by calling the flush method. syntax var request = instanceoflockedfile.flush(); re
turn a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.getMetadata() - Web APIs
param optional an object used to request specific metadata. each key is a boolean where true means the metadata is expected and where false means it is not expected. note that if the key is undefined, it is considered as if it were true. the following metadata are supported: size : will provide the size of the file lastmodified : will provide the date when the file was last modified re
turn a filerequest object. in case of success, the request's result is an object with the metadata requested through the param object. they have the following format: size : a number lastmodified : a date object specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.readAsArrayBuffer() - Web APIs
the lockedfile object and provide the result of that reading as an arraybuffer. in many ways, it performs like the filereader.readasarraybuffer() method. the reading operation starts at the position given by the lockedfile.location property. syntax var request = instanceoflockedfile.readasarraybuffer(size); parameters size a number representing the number of bytes to read in the file. re
turn a filerequest object to handle the success or failure of the operation. in case of success, the request's result is an arraybuffer representing the data that have been read. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.readAsText() - Web APIs
ng as a string. in many ways, it performs like the filereader.readastext() method. the reading operation starts at the position given by the lockedfile.location property. syntax var request = instanceoflockedfile.readastext(size[, encoding]); parameters size a number representing the number of bytes to read in the file. encoding optional a string indicating the encoding to use for the re
turned data. by default, utf-8 is assumed if this parameter is not specified. re
turn a filerequest object to handle the success or failure of the operation. in case of success, the request's result is a string representing the data that have been read. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.truncate() - Web APIs
e bytes starting at the index set in lockedfile.location. if the method is called with an argument, the operation removes all the bytes starting at the index corresponding to the parameter and regardless of the value of lockedfile.location. syntax var request = instanceoflockedfile.truncate(start); parameters start optional a number representing the index where to start the operation. re
turn a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
LockedFile.write() - Web APIs
ntations and the behavior may change in the future. summary the write method is used to write some data within the file. the write starts at the position set in lockedfile.location and moves that position by the number of written bytes. syntax var request = instanceoflockedfile.write(data); parameters data the data to write into the file. it can be a string or an arraybuffer. re
turn a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
MIDIConnectionEvent - Web APIs
ge event of the midiports interface. this occurs any time a new port becomes available, or when a previously available port becomes unavailable. for example, this event is fired whenever a midi device is either plugged in to or unplugged from a computer. constructor midiconnectionevent.midiconnectionevent creates a new midiconnectionevent object. properties midiconnectionevent.port re
turns a reference to a midiport instance for a port that has been connected or disconnected." examples specifications specification status comment web midi api working draft initial definition. ...
MIDIMessageEvent - Web APIs
s pressed, a knob is tweaked, or a slider is moved. constructor midimessageevent.midimessageevent creates a new midimessageevent object instance. properties midiconnectionevent.data a uint8array containing the data bytes of a single midi message. see the midi specification for more information on its form. note: even though the web midi api specifies a receivedtime property that re
turns a domhighrestimestamp, chrome (the only implementation at the time of writing) does not support that property since the basic event.timestamp property already re
turns a domhighrestimestamp in chrome. examples // printing all messages to console navigator.requestmidiaccess().then(midiaccess => { array.from(midiaccess.inputs).foreach(input => { input[1].onmidimessage = console.log; }) }...
MSCandidateWindowHide - Web APIs
f all languages. syntax event property object.oncandidatewindowhide = handler; addeventlistener method object.addeventlistener("mscandidatewindowhide", handler, usecapture) nbsp; parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. the handler of this event will see that the iscandidatewindowvisible method re
turns false, and no clientrect object is re
turned from getcandidatewindowclientrect. web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). see also microsoft api extensions ime handling guide for gecko ...
MSGraphicsTrust - Web APIs
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 msgraphicstrust() constructor re
turns an object that provides properties for info on protected video playback. this proprietary method is specific to internet explorer and microsoft edge. syntax var trustobject = media.msgraphicstruststatus; parameters constrictionactive a read-only property which re
turns true when protected media is forced to play in a lower resolution. status a read-only property which re
turns an enum with the driver status when playing protected content. inheritance hi...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
en false, the default action cannot be canceled. viewarg [in] type: abstractview the view in which the event is taking place. detailarg [in] type: integer specifies some detailed information depending upon the event. laststate [in] type: integer indicates the last state of the manipulation event. currentstate [in] type: integer indicates the current state of the manipulation event. re
turn value this method does not re
turn a value. example interface msmanipulationevent extends uievent { readonly currentstate: number; readonly inertiadestinationx: number; readonly inertiadestinationy: number; readonly laststate: number; initmsmanipulationevent(typearg: string, canbubblearg: boolean, cancelablearg: boolean, viewarg: window, detailarg: number, laststate: number,...
MSManipulationEvent - Web APIs
is manipulated. this proprietary method is specific to internet explorer. events msmanipulationstatechanged: event fires when the state of an element being manipulated has changed. methods msmanipulationevent.initmsmanipulationevent(): used to create a manipulation event that can be called from javascript. properties property description currentstateread only re
turns the current state of a manipulation event. inertiadestinationxread only represents the predicted horizontal scroll offset after the inertia phase completes. inertiadestinationyread only represents the predicted vertical scroll offset after the inertia phase completes. laststateread only re
turns the last state after a manipulation change event. exampl...
Magnetometer.Magnetometer() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometer = new magnetometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called. ...
Magnetometer.x - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerx = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.y - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometery = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.z - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerz = magnetometer.z value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer - Web APIs
evice sensor through the permissions api. if a feature policy blocks use of a feature, it's because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor magnetometer.magnetometer() creates a new magnetometer object. properties magnetometer.x read only re
turns a double containing the magnetic field around the device's x axis. magnetometer.y read only re
turns a double containing the magnetic field around the device's y axis. magnetometer.z read only re
turns a double containing the magnetic field around the device's z axis. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty ...
MediaCapabilities - Web APIs
ilities of the device based on codecs, profile, resolution, and bitrates. the information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient. the information is accessed through the mediacapabilities property of the navigator interface. methods mediacapabilities.encodinginfo() when passed a valid media configuration, it re
turns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient. mediacapabilities.decodinginfo() when passed a valid media configuration, it re
turns a promise with information as to whether the media type is supported, and whether decoding such media would be smooth and power efficient. specifications spe...
MediaCapabilitiesInfo - Web APIs
the mediacapabilitiesinfo interface of the media capabilities api is made available when the promise re
turned by the mediacapabilities.encodinginfo() or mediacapabilities.decodinginfo() methods of the mediacapabilities interface fulfills, providing information as to whether the media type is supported, and whether encoding or decoding such media would be smooth and power efficient. properties the mediacapabilitiesinfo interface contains three boolean attribues: supported: given the properties defined in the mediaconfiguration, can the specified piece of media content be encoded (if mediaencodingconfiguration is set) or decode (if mediadecodingconfiguration is set) at all? if yes, supported is true. otherwise, it is false. smooth: given the properties defined in the mediaconfiguration, w...
MediaDeviceInfo.deviceId - Web APIs
it is un-guessable by other applications, and unique to the origin of the calling application. it is reset when the user clears cookies. for private browsing, a different identifier is used that is not persisted across sessions. syntax var deviceid = mediadeviceinfo.deviceid value a domstring. specifications specification status comment media capture and streamsthe definition of 'deviceid' in that specification. candidate recommendation initial definition. ...
MediaDeviceInfo.kind - Web APIs
syntax var kind = mediadeviceinfo.kind value a domstring. specifications specification status comment media capture and streamsthe definition of 'kind' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MediaDeviceInfo.label - Web APIs
only available during active mediastream use, or when persistent permissions have been granted. syntax var label = mediadeviceinfo.label; value a domstring which describes the media device. for security reasons, the label is always an empty string ("") if the user has not obtained permission to use at least one media device, either by starting a stream from the microphone or camera, or by persistent permissions being granted. ...
MediaElementAudioSourceNode() - Web APIs
parameters inherits parameters from the audionodeoptions dictionary. context an audiocontext representing the audio context you want the node to be associated with. options a mediaelementaudiosourceoptions dictionary object defining the properties you want the mediaelementaudiosourcenode to have: mediaelement: an htmlmediaelement that will be used as the source for the audio. re
turn value a new mediaelementaudiosourcenode object instance. example var ac = new audiocontext(); var mediaelement = document.createelement('audio'); var options = { mediaelement : mediaelement } var myaudiosource = new mediaelementaudiosourcenode(ac, options); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode' in ...
MediaError.code - Web APIs
to get a text string with specific diagnostic information, see mediaerror.message. syntax var myerror = mediaerror.code; value a numeric value indicating the general type of error which occurred. the possible values are described below, in media error code constants. media error code constants name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. ...
MediaError.message - Web APIs
syntax var errormessage = mediaerror.message; value a domstring providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. this is not simply a generic description of the mediaerror.code property's value, but instead goes deeper into the specifics of this particular error and its circumstances. if no specific details are available, this string is empty. ...
MediaMetadata - Web APIs
the mediametadata interface of the the media session api provides allows a web page to provide rich media metadata for display in a platform ui. constructor mediametadata.mediametadata() creates a new mediametadata object. properties mediametadata.title re
turns or sets the title of the media to be played. mediametadata.artist re
turns or sets the name of the artist, group, creator, etc. of the media to be played. mediametadata.album re
turns or sets the name of the album or collection containing the media to be played. mediametadata.artwork re
turns or sets an array of images associated with playing media. specifications specification status comment media session standardthe definition of 'mediametadata' in that specification. draft initial de...
MediaPositionState.duration - Web APIs
the mediapositionstate dictionary's duration property is used when calling the mediasession method setpositionstate() to provide the user agent with the overall total duration in seconds of the media currently being performed. this information can then, in
turn, be used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. syntax let positionstate = { duration: durationinseconds }; let durationinseconds = positionstate.duration; ...
MediaPositionState.playbackRate - Web APIs
the mediapositionstate dictionary's playbackrate property is used when calling the mediasession method setpositionstate() to tell the user agent the rate at which media is currently being played. this information can then, in
turn, be used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. syntax let positionstate = { playbackrate: rate }; let playbackrate = positionstate.playbackrate; value a floating-point value specifyin...
MediaPositionState.position - Web APIs
the mediapositionstate dictionary's position property is used when calling the mediasession method setpositionstate() to provide the user agent with the current playback position, in seconds, of the currently-playing media. this information is then, in
turn, used by the user agent to provide a user interface which displays media playback information to the viewer. for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls. syntax let positionstate = { position: timeinseconds }; let duration = positionstate.duration; value a floating-...
MediaQueryList.addListener() - Web APIs
unc a function or function reference representing the callback function you want to run when the media query status changes. in the original implementation, the callback was a non-standard mediaquerylistlistener object. in the new implementation the standard event mechanism is used, the callback is a standard function, and the event object is a mediaquerylistevent, which inherits from event. re
turn value void. examples var para = document.queryselector('p'); var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide...
MediaQueryList.matches - Web APIs
you can be notified when the value of matches changes by watching for the change event to be fired at the mediaquerylist. syntax var matches = <varm>mediaquerylist.matches; value a boolean which is true if the document currently matches the media query list; otherwise, it's false. ...
MediaQueryList.removeListener() - Web APIs
could use removeeventlistener() instead. syntax mediaquerylist.removelistener(func) parameters func a function or function reference representing the callback function you want to remove. in the original implementation, the callback was a non-standard mediaquerylistlistener object. in the new implementation the standard event mechanism is used, and the callback is a standard function. re
turn value void. examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wi...
MediaQueryList - Web APIs
ery useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. properties the mediaquerylist interface inherits properties from its parent interface, eventtarget. matchesread only a boolean that re
turns true if the document currently matches the media query list, or false if not. mediaread only a domstring representing a serialized media query. methods the mediaquerylist interface inherits methods from its parent interface, eventtarget. addlistener() adds to the mediaquerylist a callback which is invoked whenever the media query status—whether or not the document matches the media q...
MediaQueryListEvent.matches - Web APIs
the matches read-only property of the mediaquerylistevent interface is a boolean that re
turns true if the document currently matches the media query list, or false if not. syntax var matches = mediaquerylistevent.matches; value a boolean; re
turns true if the document currently matches the media query list, false if not. examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than 600px wide.'; document.body.style.backgroundcolor = 'blue'; }...
MediaQueryListEvent - Web APIs
ject — instances are available as the event object on a function referenced by a mediaquerylist.onchange property or mediaquerylist.addlistener() call. constructor mediaquerylistevent() creates a new mediaquerylistevent instance. properties the mediaquerylistevent interface inherits properties from its parent interface, event. mediaquerylistevent.matchesread only a boolean that re
turns true if the document currently matches the media query list, or false if not. mediaquerylistevent.mediaread only a domstring representing a serialized media query. methods the mediaquerylistevent interface inherits methods from its parent interface, event. examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 6...
MediaRecorder.audioBitsPerSecond - Web APIs
this may differ from the bit rate specified in the constructor (if it was provided). syntax var audiobitspersecond = mediarecorder.audiobitspersecond value a number (unsigned long). specifications specification status comment mediastream recordingthe definition of 'audiobitspersecond' in that specification. working draft initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
MediaRecorder.pause() - Web APIs
called, the browser queues a task that runs the below steps: if mediarecorder.state is "inactive", raise a dom invalidstate error and terminate these steps. if not, continue to the next step. set mediarecorder.state to "paused". stop gathering data into the current blob, but keep it available so that recording can be resumed later on. raise a pause event. syntax mediarecorder.pause() re
turn value undefined. exceptions invalidstateerror the mediarecorder is currently "inactive"; you can't pause recording if it's not active. if you call pause() while already paused, it silently does nothing. example ... pause.onclick = function() { mediarecorder.pause(); console.log("recording paused"); } ... specifications specification status comment ...
MediaRecorder.start() - Web APIs
he mediarecorder.stop event. syntax mediarecorder.start(timeslice) parameters timeslice optional the number of milliseconds to record into each blob. if this parameter isn't included, the entire media duration is recorded into a single blob unless the requestdata() method is called to obtain the blob and trigger the creation of a new blob into which the media continues to be recorded. re
turn value undefined. exceptions errors that can be detected immediately are thrown as dom exceptions. all other errors are reported through error events sent to the mediarecorder object. you can implement the onerror event handler to respond to these errors. invalidmodificationerror the number of tracks on the stream being recorded has changed. you can't add or remove tracks while recording me...
MediaRecorder.state - Web APIs
the mediarecorder.state read-only property re
turns the current state of the current mediarecorder object. syntax var state = mediarecorder.state values a animationplaystate object containing one of the following values: enumeration description inactive recording is not occuring — it has either not been started yet, or it has been started and then stopped. recording recording has been started and the ua is capturing data. paused recording has been started, then paused, but not yet stopped or resumed. example ... record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); // will re
turn "recording" console.log("recorder started"); } ... specifications specification s...
MediaRecorder.stream - Web APIs
syntax var stream = mediarecorder.stream values the mediastream passed into the mediarecorder() constructor when the mediarecorder was originally created. example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { var mediarecorder = new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ... ...
MediaSource.removeSourceBuffer() - Web APIs
the removesourcebuffer() method of the mediasource interface removes the given sourcebuffer from the sourcebuffers list associated with this mediasource object. syntax mediasource.removesourcebuffer(sourcebuffer); parameters sourcebuffer the sourcebuffer object to be removed. re
turn value undefined exceptions exception explanation notfounderror the supplied sourcebuffer doesn't exist in mediasource.sourcebuffers. examples for (i = 0; i < 10; i++) { var sourcebuffer = mediasource.addsourcebuffer(mimecodec); } mediasource.removesourcebuffer(mediasource.sourcebuffers[0]); specifications specification status comment media source extensionsthe definition of 'removesourcebuffer()' in that specification. recom...
MediaStream() - Web APIs
the mediastream() constructor re
turns a newly-created mediastream, which serves as a collection of media tracks, each represented by a mediastreamtrack object. if any parameters are given, the specified tracks are added to the new stream. otherwise, the stream has no tracks. syntax newstream = new mediastream(); newstream = new mediastream(stream); newstream = new mediastream(tracks[]); parameters stream a different mediastream object whose tracks are added to the newly-created stream automatically. the tracks are not removed from the original stream, so they're shared by the two streams. tracks an array of mediastreamtrack objects, one for each track to add to the stream. re
turn value a newly-created mediastream object, either empty, or containing the tracks provided, if any. s...
active - Web APIs
the active read-only property of the mediastream interface re
turns a boolean value which is true if the stream is currently active; otherwise, it re
turns false. a stream is considered active if at least one of its mediastreamtracks is not in the mediastreamtrack.ended state. once every track has ended, the stream's active property becomes false. syntax var isactive = mediastream.active; value a boolean value which is true if the stream is currently active; otherwise, the value is false. example in this example, a new stream whose source is the user's local camera and microphone is requested using getusermedia(). when that stream becomes available (that is, when the re
turned promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active. var...
MediaStream.addTrack() - Web APIs
the mediastream.addtrack() method adds a new track to the stream. the track is specified as a parameter of type mediastreamtrack. if the specified track is already in the stream's track set, this method has no effect. syntax stream.addtrack(track); parameters track a mediastreamtrack to add to the stream. re
turn value undefined example specifications specification status comment media capture and streamsthe definition of 'addtrack()' in that specification. candidate recommendation initial specification. ...
MediaStream.clone() - Web APIs
the clone() method of the mediastream interface creates a duplicate of the mediastream. this new mediastream object has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. syntax var stream = mediastream.clone(); parameters none. re
turn value a new mediastream instance which has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called. specifications specification status comment media capture and streamsthe definition of 'mediastream.clone()' in that specification. candidate recommendation initial definition. ...
MediaStream.getAudioTracks() - Web APIs
the getaudiotracks() method of the mediastream interface re
turns a sequence that represents all the mediastreamtrack objects in this stream's track set where mediastreamtrack.kind is audio. syntax var mediastreamtracks = mediastream.getaudiotracks() parameters none. re
turn value an array of mediastreamtrack objects, one for each audio track contained in the stream. audio tracks are those tracks whose kind property is audio. the array is empty if the stream contains no audio tracks. note: the order of the re
turned tracks is not defined by the specification and may, in fact, change from one call to getaudiotracks() to the next. early versions of this api included a special audiostreamtrack interface which was used as the type for each entry in the list of audio streams; however, this ...
MediaStream.getTracks() - Web APIs
the gettracks() method of the mediastream interface re
turns a sequence that represents all the mediastreamtrack objects in this stream's track set, regardless of mediastreamtrack.kind. syntax var mediastreamtracks = mediastream.gettracks() parameters none. re
turn value an array of mediastreamtrack objects. example navigator.mediadevices.getusermedia({audio: false, video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification. candidate recommendation initial ...
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
stance. syntax var myaudiodest = new mediastreamaudiodestinationnode(context, options); parameters inherits parameters from the audionodeoptions dictionary. context an audiocontext representing the audio context you want the node to be associated with. options optional an audionodeoptions dictionary object defining the properties you want the mediastreamaudiodestinationnode to have. re
turn value a new mediastreamaudiodestinationnode object instance. example var ac = new audiocontext(); var mydestination = new mediastreamaudiodestinationnode(ac); specifications specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification. working draft ...
MediaStreamEvent.stream - Web APIs
the read-only property mediastreamevent.stream re
turns the mediastream associated with the event. syntax var stream = event.stream; example pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream.id + "') has been added to this connection."); }; ...
MediaStreamEvent - Web APIs
mediastreamevent interface represents events that occurs in relation to a mediastream. two events of this type can be thrown: addstream and removestream. properties a mediastreamevent being an event, this event also implements these properties. mediastreamevent.stream read only contains the mediastream containing the stream associated with the event. constructors mediastreamevent() re
turns a new mediastreamevent. it takes two parameters, the first being a domstring representing the type of the event; the second a dictionary containing the mediastream it refers to. methods a mediastreamevent being an event, this event also implements these properties. there is no specific mediastreamevent method. examples pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream...
MediaStreamTrack.applyConstraints() - Web APIs
inable properties not included are restored to their default constraints. if this parameter is omitted, all currently set custom constraints are cleared. this object represents the basic set of constraints that must apply for the promise to resolve. the object may contain an advanced property containing an array of additional mediatrackconstrants objects, which are treated as exact requires. re
turn value a promise which resolves when the constraints have been successfully applied. if the constraints cannot be applied, the promise is rejected with a mediastreamerror whose name is overconstrainederror, to indicate that the constraints could not be met. this can happen if the specified constraints are too strict to find a match when attempting to configure the track. examples the following ...
MediaStreamTrack.clone() - Web APIs
the clone() method of the mediastreamtrack interface creates a duplicate of the mediastreamtrack. this new mediastreamtrack object is identical except for its unique id. syntax const newtrack = track.clone() re
turn value a new mediastreamtrack instance which is identical to the one clone() was called, except for its new unique id. specifications specification status comment media capture and streamsthe definition of 'clone()' in that specification. candidate recommendation initial definition. ...
MediaStreamTrack.enabled - Web APIs
when implementing a mute/unmute feature, you should use the enabled property. usage notes if the mediastreamtrack represents the video input from a camera, disabling the track by setting enabled to false also updates device activity indicators to show that the camera is not currently recording or streaming. for example, the green "in use" light next to the camera in imac and macbook computers
turns off while the track is muted in this way. example this example demonstrates a click event handler for a pause button. pausebutton.onclick = function(evt) { const newstate = !myaudiotrack.enabled; pausebutton.innerhtml = newstate ? "▶️" : "⏸️"; myaudiotrack.enabled = newstate; } this creates a variable, newstate, which is the opposite of the current value of...
MediaStreamTrack.getCapabilities() - Web APIs
the getcapabilities() method of the mediastreamtrack interface re
turns a mediatrackcapabilities object which specifies the values or range of values which each constrainable property, based upon the platform and user agent. once you know what the browser's capabilities are, your script can use applyconstraints() to ask for the track to be configured to match ideal or acceptable settings. see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const capabilities = track.getcapabilities() re
turn value a mediatrackcapabilities object which specifies the value or range of values which are supported for each of the user agent's supported constrainable properties. specifications specification status comment media ca...
MediaStreamTrack.getSettings() - Web APIs
the getsettings() method of the mediastreamtrack interface re
turns a mediatracksettings object containing the current values of each of the constrainable properties for the current mediastreamtrack. see capabilities, constraints, and settings for details on how to work with constrainable properties. syntax const settings = track.getsettings() re
turns a mediatracksettings object describing the current configuration of the track's constrainable properties. note: the re
turned object identifies the current values of every constrainable property, including those which are platform defaults rather than having been expressly set by the site's code. to instead fetch the most-recently established constraints for the track's properties, as specified by the site's code, use getconstraints(). spe...
MediaStreamTrack.id - Web APIs
syntax const id = track.id specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.id' in that specification. ...
MediaStreamTrack.kind - Web APIs
it doesn't change if the track is deassociated from its source. syntax const type = track.kind value the possible values are a domstring with on of the following values: "audio": the track is an audio track. "video": the track is a video track. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.kind' in that specification. ...
MediaStreamTrack.label - Web APIs
the string may be left empty and is empty as long as no source has been connected. when the track is deassociated from its source, the label is not changed. syntax const label = track.label specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.label' in that specification. ...
MediaStreamTrack.muted - Web APIs
to implement a way for users to mute and unmute a track, use the enabled property. when a track is disabled by setting enabled to false, it generates only empty frames (audio frames in which every sample is 0, or video frames in which every pixel is black). syntax const mutedflag = track.muted value a boolean which is true if the track is currently muted, or false if the track is currently unmuted. when possible, avoid polling muted to monitor the track's muting status. instead, add event listeners for the mute and unmute events. ...
MediaStreamTrack.readyState - Web APIs
syntax const state = track.readystate value it takes one of the following values: "live" which indicates that an input is connected and does its best-effort in providing real-time data. in that case, the output of data can be switched on or off using the mediastreamtrack.enabled property. "ended" which indicates that the input is not giving any more data and will never provide new data. specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.readystate' in that specification. ...
MediaStreamTrack.remote - Web APIs
the mediastreamtrack.remote read-only property allows javascript to know whether a webrtc mediastreamtrack is from a remote source or a local one. it re
turns a boolean with a value of true if the track is sourced remotely (that is, sourced by an rtcpeerconnection), or false if it is sourced locally. syntax var bool = track.remote; ...
MediaStreamTrackEvent() - Web APIs
the mediastreamtrackevent() constructor re
turns a newly created mediastreamtrackevent object, which represents an event announcing that a mediastreamtrack has been added to or removed from a mediastream. syntax var trackevent = new mediastreamtrackevent(type, {track: amediastreamtrack}); parameters the mediastreamtrackevent() constructor also inherits arguments from event(). type a domstring representing the name of the type of the mediastreamtrackevent. it is case-sensitive and can be "addtrack" or "removetrack". track a mediastreamtrack object representing the track which was added to or removed from the stream. re
turn value a new mediastreamtrackevent, initialized based on the provided options. specifications specification status comment media captur...
MediaTrackConstraints.aspectRatio - Web APIs
the mediatrackconstraints dictionary's aspectratio property is a constraindouble describing the requested or mandatory constraints placed upon the value of the aspectratio constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.aspectratio as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { aspectratio: constraint }; constraintsobject.aspectratio = constraint; value a constraindouble describing the acceptable or required value(s) for a video track's aspect ratio. the value is the width divided by the height and is rounded to ten deci...
MediaTrackConstraints.autoGainControl - Web APIs
the mediatrackconstraints dictionary's autogaincontrol property is a constrainboolean describing the requested or mandatory constraints placed upon the value of the autogaincontrol constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.autogaincontrol as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. automatic gain control is typically a feature provided by microphones, although it can be provided by other input sources as well. syntax var constraintsobject = { autogaincontrol: constraint }; constraintsobject.autogaincontrol = constraint; value if this value is ...
MediaTrackConstraints.channelCount - Web APIs
the mediatrackconstraints dictionary's channelcount property is a constrainlong describing the requested or mandatory constraints placed upon the value of the channelcount constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.channelcount as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { channelcount: constraint }; constraintsobject.channelcount = constraint; value if this value is a number, the user agent will attempt to obtain media whose channel count is as close as possible to this number given the capabilities of the hardwar...
MediaTrackConstraints.echoCancellation - Web APIs
the mediatrackconstraints dictionary's echocancellation property is a constrainboolean describing the requested or mandatory constraints placed upon the value of the echocancellation constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.echocancellation as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var constraintsobject = { echocancellation: constraint }; constraintsobject.echocancellation = constraint; value if this value...
MediaTrackConstraints.facingMode - Web APIs
the mediatrackconstraints dictionary's facingmode property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the facingmode constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.facingmode as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var constraintsobject = { facingmode: constraint }; constraintsobject.facingmode = constraint; value an object based on constraindomstring spe...
MediaTrackConstraints.frameRate - Web APIs
the mediatrackconstraints dictionary's framerate property is a constraindouble describing the requested or mandatory constraints placed upon the value of the framerate constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.framerate as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { framerate: constraint }; constraintsobject.framerate = constraint; value a constraindouble describing the acceptable or required value(s) for a video track's frame rate, in frames per second. if this value is a number, the user agent will attempt to ob...
MediaTrackConstraints.height - Web APIs
the mediatrackconstraints dictionary's height property is a constrainlong describing the requested or mandatory constraints placed upon the value of the height constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.height as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { height: constraint }; constraintsobject.height = constraint; value if this value is a number, the user agent will attempt to obtain media whose height is as close as possible to this number given the capabilities of the hardware and the other constraints specified...
MediaTrackConstraints.latency - Web APIs
the mediatrackconstraints dictionary's latency property is a constraindouble describing the requested or mandatory constraints placed upon the value of the latency constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var constraintsobject = { latency: constraint }; constraintsobject.latency = constraint; value a constraindouble describing the acceptable or required val...
MediaTrackConstraints.noiseSuppression - Web APIs
the mediatrackconstraints dictionary's noisesuppression property is a constrainboolean describing the requested or mandatory constraints placed upon the value of the noisesuppression constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. noise suppression is typically provided by microphones, although it can be provided by other input sources as well. syntax var constraintsobject = { noisesuppression: constraint }; constraintsobject.noisesuppression = constraint; value if this value is a simple t...
MediaTrackConstraints.sampleRate - Web APIs
the mediatrackconstraints dictionary's samplerate property is a constrainlong describing the requested or mandatory constraints placed upon the value of the samplerate constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplerate as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { samplerate: constraint }; constraintsobject.samplerate = constraint; value if this value is a number, the user agent will attempt to obtain media whose sample rate is as close as possible to this number given the capabilities of the hardware and the ot...
MediaTrackConstraints.sampleSize - Web APIs
the mediatrackconstraints dictionary's samplesize property is a constrainlong describing the requested or mandatory constraints placed upon the value of the samplesize constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplesize as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { samplesize: constraint }; constraintsobject.samplesize = constraint; value if this value is a number, the user agent will attempt to obtain media whose sample size (in bits per linear sample) is as close as possible to this number given the capabilitie...
MediaTrackControls.volume - Web APIs
the mediatrackconstraints dictionary's volume property is a constraindouble describing the requested or mandatory constraints placed upon the value of the volume constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.volume as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { volume: constraint }; constraintsobject.volume = constraint; value a constraindouble describing the acceptable or required value(s) for an audio track's volume, on a linear scale where 0.0 means silence and 1.0 is the highest supported volume. if this value i...
MediaTrackConstraints.width - Web APIs
the mediatrackconstraints dictionary's width property is a constrainlong describing the requested or mandatory constraints placed upon the value of the width constrainable property. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.width as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { width: constraint }; constraintsobject.width = constraint; value if this value is a number, the user agent will attempt to obtain media whose width is as close as possible to this number given the capabilities of the hardware and the other constraints specified. othe...
MediaTrackSettings.aspectRatio - Web APIs
determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.aspectratio property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.aspectratio as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var aspectratio = mediatracksettings.aspectratio; value a double-precision floating-point number indicating the current configuration of the track's aspect ratio. the aspect ratio is computed by taking the track's widt...
MediaTrackSettings.autoGainControl - Web APIs
a feature in which a sound source automatically manages changes in the volume of its source media to maintain a steady overall volume level. this feature is typically used on microphones, although it can be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.autogaincontrol as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var autogaincontrol = mediatracksettings.autogaincontrol; value a boolean value which is true if the track has automatic gain control enabled or false if agc is disabled. example see example: constraint exerciser in ...
MediaTrackSettings.channelCount - Web APIs
termine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.channelcount property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.channelcount as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var channelcount = mediatracksettings.channelcount; value an integer value indicating the number of audio channels on the track. a value of 1 indicates monaural sound, 2 means stereo, and so forth. example see exampl...
MediaTrackSettings.cursor - Web APIs
syntax cursorsetting = mediatracksettings.cursor; value the value of cursor comes from the cursorcaptureconstraint enumerated string type, and may have one of the following values: always the mouse should always be visible in the video content of the {domxref("mediastream"), unless the mouse has moved outside the area of the content. ...
MediaTrackSettings.echoCancellation - Web APIs
reduce or eliminate crosstalk between the user's output device and their input device. for example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphone. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.echocancellation as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var echocancellation = mediatracksettings.echocancellation; value a boolean value which...
MediaTrackSettings.facingMode - Web APIs
u determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.facingmode property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.facingmode as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var facingmode = mediatracksettings.facingmode; value a domstring whose value is one of...
MediaTrackSettings.frameRate - Web APIs
you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.framerate property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.framerate as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var framerate = mediatracksettings.framerate; value a double-precision floating-point number indicating the current configuration of the track's frame rate, in frames per second. example see example: constraint exerc...
MediaTrackSettings.groupId - Web APIs
source for the mediastreamtrack. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.groupid property you provided when calling either getusermedia(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.groupid as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var groupid = mediatracksettings.groupid; value a domstring whose value is a browsing-s...
MediaTrackSettings.height - Web APIs
lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.height property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.height as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var height = mediatracksettings.height; value an integer value indicating the height, in pixels, of the video track as currently configured. example see example: constraint exerciser in capabilities, constraints, and...
MediaTrackSettings.latency - Web APIs
mediatrackconstraints.latency property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). this is, of course, an approximation, since latency can vary for many reasons including cpu, transmission, and storage overhead. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will never include this property. syntax var latency = mediatracksettings.latency; value a double-precision floating-point numbe...
MediaTrackSettings.logicalSurface - Web APIs
face. the most common scenario in which a display surface may be a logical one is if the selected surface contains the entire content area of a window which is too large to display onscreen at once. since the window that contains the surface has to be scrolled to show the rest of the contents, the surface is a logical one. a visible display surface (that is, a surface for which logicalsurface re
turns false) is the portion of a logical display surface which is currently visible onscreen. for example, a user agent may choose to allow the user to choose whether to share the entire document (a browser with logicalsurface value of true), or just the currently visible portion of the document (where the logicalsurface of the browser surface is false). specifications specification sta...
MediaTrackSettings.noiseSuppression - Web APIs
emove background noise, hum caused by equipment, and the like from the sound before delivering it to your code. this feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var noisesuppression = mediatracksettings.noisesuppression; value a boolean value which is true if the input track has noise suppression enabled or false if agc is disabled. example see example: constraint exerciser ...
MediaTrackSettings.sampleRate - Web APIs
u determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplerate property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplerate as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var samplerate = mediatracksettings.samplerate; value an integer value indicating how many samples each second of audio data includes. common values include 44,100 (standard cd audio), 48,000 (standard digital audio), ...
MediaTrackSettings.sampleSize - Web APIs
u determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplesize property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplesize as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var samplesize = mediatracksettings.samplesize; value an integer value indicating how many bits each audio sample is represented by. the most commonly used sample size for many years now is 16 bits per sample, which wa...
MediaTrackSettings.volume - Web APIs
lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.volume property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.volume as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var volume = mediatracksettings.volume; value a double-precision floating-point number indicating the volume, from 0.0 to 1.0, of the audio track as currently configured. example see example: constraint exerciser in ...
MediaTrackSettings.width - Web APIs
is lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.width property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.width as re
turned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var width = mediatracksettings.width; value an integer value indicating the width, in pixels, of the video track as currently configured. example see example: constraint exerciser in capabilities, constraints, and se...
MediaTrackSettings - Web APIs
these values will adhere as closely as possible to any constraints previously described using a mediatrackconstraints object and set using applyconstraints(), and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched. to learn more about how constraints and settings work, see capabilities, constraints, and settings. properties some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context. ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false. you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints(). ...
MediaTrackSupportedConstraints.channelCount - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false. you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints(). ...
MediaTrackSupportedConstraints.cursor - Web APIs
portedconstraints.cursor; value a boolean value which is true if the cursor 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 re
turned stream to the video element referenced by the variable videoelem. async function capturewithcursor() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { displaysurface: "browser" }, audio: false; }; if (supportedconstraints.cursor) { displaymediaoptions.video.cursor = "always"; } try { video...
MediaTrackSupportedConstraints.deviceId - Web APIs
if the constraint isn't supported, it's not included in the list, so this value will never be false. you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints(). ...
MediaTrackSupportedConstraints.displaySurface - Web APIs
displaysurface 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 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 re
turned stream to the video element referenced by the variable videoelem. async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.displaysurface) { displaymediaoptions.video.displaysurface = "monitor"; } try { videoelem.srcobject = await na...
MerchantValidationEvent.methodName - Web APIs
syntax methodid = merchantvalidationevent.methodname; value a read-only domstring which uniquely identifies the payment handler which is requesting merchant validation. see merchant validation in payment processing concepts for more information on the process. ...
MessageChannel() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
MessageChannel.port1 - Web APIs
note: this feature is available in web workers. syntax channel.port1; value a messageport object, the first port of the channel, that is the port attached to the context that originated the channel. example in the following code block, you can see a new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. ...
MessageChannel.port2 - Web APIs
note: this feature is available in web workers. syntax channel.port2; value a messageport object representing the second port of the channel, the port attached to the context at the other end of the channel. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. ...
MessageChannel - Web APIs
the messagechannel interface of the channel messaging api allows us to create a new message channel and send data through it via its two messageport properties. note: this feature is available in web workers. properties messagechannel.port1 read only re
turns port1 of the channel. messagechannel.port2 read only re
turns port2 of the channel. constructor messagechannel() re
turns a new messagechannel object with two new messageport objects. example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is...
MessagePort.close() - Web APIs
parameters none. example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener. ...
MessagePort.postMessage() - Web APIs
parameters message the message you want to send through the channel. this can be of any basic data type. multiple data items can be sent as an array. ...
MouseEvent.altKey - Web APIs
alt key was pressed or not when a given mouse event occurs. be aware that the browser can't always detect the alt key on some operating systems. on some linux variants, for example, a left mouse click combined with the alt key is used to move or resize windows. note: on macintosh keyboards, this key is also known as the option key. syntax var altkeypressed = instanceofmouseevent.altkey re
turn value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the altkey property when you trigger a click event. html <p>click anywhere to test the <code>altkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e)...
MouseEvent.buttons - Web APIs
i.e., 2 + 4). note: do not confuse this property with the mouseevent.button property. the mouseevent.buttons property indicates the state of buttons pressed during any kind of mouse event, while the mouseevent.button property only guarantees the correct value for mouse events caused by pressing or releasing one or multiple buttons. syntax var buttonspressed = instanceofmouseevent.buttons re
turn value a number representing one or more buttons. for more than one button pressed simultaneously, the values are combined (e.g., 3 is primary + secondary). 0 : no button or un-initialized 1 : primary button (usually the left button) 2 : secondary button (usually the right button) 4 : auxiliary button (usually the mouse wheel button or middle button) 8 : 4th button (typically the "bro...
MouseEvent.clientX - Web APIs
e mouseevent interface provides the horizontal coordinate within the application's client area at which the event occurred (as opposed to the coordinate within the page). for example, clicking on the left edge of the client area will always result in a mouse event with a clientx value of 0, regardless of whether the page is scrolled horizontally. syntax var x = instanceofmouseevent.clientx re
turn value a double floating point value, as redefined by the cssom view module. originally, this property was defined as a long integer. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.
MouseEvent.clientY - Web APIs
of the mouseevent interface provides the vertical coordinate within the application's client area at which the event occurred (as opposed to the coordinate within the page). for example, clicking on the top edge of the client area will always result in a mouse event with a clienty value of 0, regardless of whether the page is scrolled vertically. syntax var y = instanceofmouseevent.clienty re
turn value a double floating point value, as redefined by the cssom view module. originally, this property was defined as a long integer. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.
MouseEvent.metaKey - Web APIs
. be aware that many operating systems bind special functionality to the meta key, so this property may be false even when the key is actually pressed. on windows, for example, this key may open the start menu. note: on macintosh keyboards, this key is the command key (⌘). on windows keyboards, this key is the windows key (⊞). syntax var metakeypressed = instanceofmouseevent.metakey re
turn value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the metakey property when you trigger a click event. html <p>click anywhere to test the <code>metakey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(...
MouseEvent.movementX - Web APIs
the movementx read-only property of the mouseevent interface provides the difference in the x coordinate of the mouse pointer between the given event and the previous mousemove event. in other words, the value of the property is computed like this: currentevent.movementx = currentevent.screenx - previousevent.screenx. syntax var xshift = instanceofmouseevent.movementx; re
turn value a number example this example logs the amount of mouse movement using movementx and movementy. html <p id="log">move your mouse around.</p> javascript function logmovement(event) { log.insertadjacenthtml('afterbegin', `movement: ${event.movementx}, ${event.movementy}<br>`); while (log.childnodes.length > 128) log.lastchild.remove() } const log = document.getelementbyid('log'); document.addeventliste...
NDEFMessage - Web APIs
the ndefmessage interface of the web nfc api is an abstract interface that represents message that can be received or sent to a to compatible nfc devices, e.g. nfc tags supporting ndef. constructor ndefmessage.ndefmessage() re
turns a new ndefmessage containing specified data. attributes ndefmessage.records read only represents a list of ndef records defining the ndef message. specifications specification status comment web nfc, ndefmessage draft initial definition. ...
NDEFReader() - Web APIs
the ndefreader() constructor of the web nfc api re
turns a newly constructed ndefreader object used to read ndef messages from compatiable nfc devices, e.g. ndef tags, within the reader's magnetic induction field. syntax writer = new ndefreader(); parameters none. re
turn value a new ndefreader. specifications specification status comment web nfc, ndefreader draft initial definition. ...
NDEFReader.scan() - Web APIs
def nfc tags. syntax var readerpromise = ndefreader.scan(options); parameters options optional id -- the match pattern for matching each ndefrecord.id. recordtype -- the match pattern for matching each ndefrecord.recordtype. mediatype -- the match pattern for matching each ndefrecord.mediatype. signal -- optional abortsignal that allows to cancell this scan() operation. re
turn value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter. exceptions this method doesn't throw true exceptions; instead, it rejects the re
turned promise, passing into it a domexception whose name is one of the following: aborterror the scan operation was aborted with abortsignal passed in options. notallowederror the permission for th...
NDEFReader - Web APIs
properties in addition to the properties listed below, ndefreader inherits properties from its parent interface, eventtarget. ...
NDEFRecord() - Web APIs
the ndefrecord() constructor of the web nfc api re
turns a newly constructed ndefrecord object that represents data that can be read from or written to compatible nfc devices, e.g. nfc tags supporting ndef. syntax writer = new ndefrecord(ndefrecordinit); parameters ndefrecordinit read only ndefrecordinit with initialization data. re
turn value a new ndefrecord. specifications specification status comment web nfc, ndefrecord draft initial definition. ...
NDEFRecord.toRecords() - Web APIs
the torecords() method of the ndefrecord interface of web nfc api parses record payload ndefrecord.data besed on ndefrecord.recordtype and re
turns the result. in practice, it's possible to implement the parsing mechanism manually, but this method simplifies the process. syntax ndefrecord.torecords() parameters none. re
turn value a list of ndefrecords. exceptions notsupported the user agent does not know how to parse this combination of ndefrecord.data and ndefrecord.recordtype. specifications specification status comment web nfc, ndefrecord.torecords() draft initial definition. ...
NDEFRecord - Web APIs
attributes ndefrecord.recordtype read only represents the ndef record type. ndefrecord.mediatype read only represents the mime type of the ndef record payload. ndefrecord.id read only represents the identificator of the record. ...
NDEFWriter() - Web APIs
the ndefwriter() constructor of the web nfc api re
turns a newly constructed ndefwriter object used to write ndef messages to compatiable nfc devices, e.g. ndef tags, within the reader's magnetic induction field. syntax writer = new ndefwriter(); parameters none. re
turn value a new ndefwriter. specifications specification status comment web nfc, ndefwriter draft initial definition. ...
NDEFWriter.write() - Web APIs
er domstring or buffersource or ndefmessageinit. options optional ignoreread -- boolean specifying whether or not to skip reading for the activated reader objects. will be ignored if overwrite is false. overwrite -- boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional abortsignal that allows to cancell this write operation. re
turn value a promise that resolves with undefined when and if the message transfer is successfully completed. exceptions this method doesn't throw true exceptions; instead, it rejects the re
turned promise, passing into it a domexception whose name is one of the following: aborterror the write operation was aborted with abortsignal passed in options. notallowederror the permission for this ope...
NDEFWriter - Web APIs
the ndefwriter interface of the web nfc api is an abstract interface used to write data to compatible nfc devices, e.g. nfc tags supporting ndef, when these devices are within the reader's magnetic induction field. constructor ndefwriter.ndefwriter() re
turns an ndefwriter. methods ndefwriter.write() called to write ndef message to a tag (after ensuring hardware and ua compatibility and obtaining permission from the user) or get an error explaining why feature is not available. specifications specification status comment web nfc, ndefreader draft initial definition. ...
NameList - Web APIs
cko, there was no way to actually create one. namelist has been removed, effective with gecko 10.0 the namelist interface provides an abstraction for an ordered collection of name and namespace value pairs. items can be accessed by a 0-based index. the dom spec does not specify how the collection is to be implemented. properties namelist.length read only methods namelist.contains() re
turns a boolean. namelist.containsns() re
turns a boolean. namelist.getname() re
turns a domstring. namelist.getnamespaceuri() re
turns a domstring. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'namelist' in that specification. obsolete initial definition ...
NamedNodeMap.getNamedItem() - Web APIs
the getnameditem() method of the namednodemap interface re
turns the attr corresponding to the given name, or null if there is no corresponding attribute. syntax myattr = attrs.getnameditem(name) parameters name is the name of the desired attribute ...
Navigator.battery - Web APIs
the battery read-only property re
turns a batterymanager which provides information about the system's battery charge level and whether the device is charging and exposes events that fire when these parameters change. this interface was introduced in early drafts of the battery status api and but has been replaced with promise-based navigator.getbattery(). the battery property has been removed in favor of the standard navigator.getbattery() method, which re
turns a battery promise. syntax var battery = navigator.battery; ...
Navigator.buildID - Web APIs
20181001000000 in firefox 64 onwards. syntax buildid = navigator.buildid; value a string representing the build identifier of the application. the build id is in the form yyyymmddhhmmss. example console.log(window.navigator.buildid); specification not part of any public standard. ...
Navigator.connection - Web APIs
this could be used to select high definition content or low definition content based on the user's connection. syntax networkinformation = navigator.connection value a networkinformation object. ...
Navigator.sendBeacon() - Web APIs
the navigator.sendbeacon() method asynchronously sends a small amount of data over http to a web server. 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. re
turn values the sendbeacon() method re
turns true if the user agent successfully queued the data for transfer. otherwise, it re
turns 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. for example, which link the user clicked before navigating away and unloading the page. ensuring that data has ...
Navigator.serviceWorker - Web APIs
the feature may not be available in private mode. syntax var workercontainerinstance = navigator.serviceworker; value serviceworkercontainer examples this code checks if the browser supports service workers. ...
Navigator.share() - Web APIs
navigator.share(data); parameters data an object containing data to share. at least one of the following fields must be specified. available options are: url: a usvstring representing a url to be shared. text: a usvstring representing text to be shared. title: a usvstring representing the title to be shared. files: a " frozenarray" representing the array of file to be shared. re
turn value a promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to). it will reject immediately if the data parameter is not correctly specified, and will also reject if the user cancels sharing. examples in our web share test (see the source code) there is a button which, when clicked, invokes the web share api to share mdn'...
Navigator.vibrate() - Web APIs
the navigator.vibrate() method pulses the vibration hardware on the device, if such hardware exists. if the device doesn't support vibration, this method has no effect. if a vibration pattern is already in progress when this method is called, the previous pattern is halted and the new one begins instead. if the method was unable to vibrate because of invalid parameters, it will re
turn false, else it re
turns true. if the pattern leads to a too long vibration, it is truncated: the max length depends on the implementation. syntax var successbool = window.navigator.vibrate(pattern); pattern provides a pattern of vibration and pause intervals. each value indicates a number of milliseconds to vibrate or pause, in alternation. you may provide either a single value (to vibrate once for that m...
Navigator.wakeLock - Web APIs
the wakelock read-only property re
turns a wakelock interface which allows a document to acquire a screen wake lock. while a screen wake lock is active, the user agent will try to prevent the device from dimming the screen,
turning it off completely, or showing a screensaver. syntax const wakelock = navigator.wakelock; specifications specification status comment screen wake lock api editor's draft initial definition ...
Navigator.xr - Web APIs
syntax const xr = navigator.xr value the xr object used to interface with the webxr device api in the current context. this can be used to present augmented and/or virtual reality imagery to the user. usage notes each window has its own instance of navigator, which can be accessed as window.navigator or simply as navigator. at the same time, a new xr instance is also created and attached to the navigator instance as navigator.xr. if the xr property exists and is non-null, you can use it to access the webxr device api. ...
NavigatorConcurrentHardware - Web APIs
b workers. the number of logical processor cores is a way to measure the number of threads which can effectively be run at once without them having to share cpus. modern computers have multiple physical cores in their cpu (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. so a four-core cpu may re
turn 8. the browser may, however, choose to reduce the number in order to represent more accurately the number of workers that can run at once properties navigatorconcurrenthardware.hardwareconcurrency read only re
turns the number of logical processors which may be available to the user agent. this value is always at least 1, and will be 1 if the actual number of logical processors can't be dete...
NavigatorID.platform - Web APIs
re
turns a string representing the platform of the browser. the specification allows browsers to always re
turn the empty string, so don't rely on this property to get a reliable answer. syntax platform = navigator.platform value a domstring identifying the platform on which the browser is running, or an empty string if the browser declines to (or is unable to) identify the platform. platform is a string that must be an empty string or a string representing the platform on which the browser is executing. for example: "macintel", "win32", "freebsd i386", "webtv os" example console.log(navigator.platform); usage notes most browsers, including chrome, edge, and firefox 63 and later, re
turn "win32" even if running on a 64-bit version of windows. internet explorer and versions of firefox p...
NavigatorID.taintEnabled() - Web APIs
tainting was a security method used by javascript 1.2. it has long been removed; this method only stays for maintaining compatibility with very old scripts. syntax result = window.navigator.taintenabled() specifications specification status comment html living standardthe definition of 'navigatorid.taintenabled' in that specification. ...
NavigatorID.userAgent - Web APIs
the specification asks browsers to provide as little information via this field as possible. never assume that the value of this property will stay the same in future versions of the same browser. try not to use it at all, or only for current and past versions of a browser. new browsers may start using the same ua, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property. also keep in mind that users of a browser can change the value of this field if they want (ua spoofing). ...
NavigatorLanguage.language - Web APIs
the navigatorlanguage.language read-only property re
turns a string representing the preferred language of the user, usually the language of the browser ui. syntax const lang = navigator.language value a domstring. lang stores a string representing the language version as defined in bcp 47. examples of valid language codes include "en", "en-us", "fr", "fr-fr", "es-es", etc. note that in safari on ios prior to 10.2, the country code re
turned is lowercase: "en-us", "fr-fr" etc. example if (/^en\b/.test(navigator.language)) { dolangselect(window.navigator.language); } specifications specification status comment html living standardthe definition of 'navigatorlanguage: language' in that specification. living standard initial definition ...
NavigatorLanguage - Web APIs
navigatorlanguage contains methods and properties related to the language of the navigator. there is no object of type navigatorlanguage, but other interfaces, like navigator or workernavigator, implement it. properties the navigatorlanguage interface doesn't inherit any property. navigatorlanguage.language read only re
turns a domstring representing the preferred language of the user, usually the language of the browser ui. the null value is re
turned when this is unknown. navigatorlanguage.languages read only re
turns an array of domstring representing the languages known to the user, by order of preference. methods the navigatorlanguage interface neither implements, nor inherit any method. specifications specification status comment html living stan...
NavigatorOnLine - Web APIs
the navigatoronline interface contains methods and properties related to the connectivity status of the browser. there is no object of type navigatoronline, but other interfaces, like navigator or workernavigator, implement it. properties the navigatoronline interface doesn't inherit any property. navigatoronline.online read only re
turns a boolean indicating whether the browser is working online. methods the navigatoronline interface neither implements, nor inherit any method. specifications specification status html living standardthe definition of 'navigatoronline' in that specification. living standard ...
NavigatorPlugins.javaEnabled() - Web APIs
this method indicates whether the current browser is java-enabled or not. syntax result = window.navigator.javaenabled() example if (window.navigator.javaenabled()) { // browser has java } notes the re
turn value for this method indicates whether the preference that controls java is on or off - not whether the browser offers java support in general. specifications specification status comment html living standardthe definition of 'navigatorplugins.javaenabled' in that specification. living standard initial definition. ...
NavigatorPlugins - Web APIs
the navigatorplugins mixin adds to the navigator interface methods and properties for discovering and interacting with plugins installed into the browser. properties navigatorplugins.mimetypes read only re
turns an mimetypearray listing the mime types supported by the browser. navigatorplugins.plugins read only re
turns a pluginarray listing the plugins installed in the browser. methods the navigatorplugins interface doesn't inherit any methods. navigatorplugins.javaenabled() read only re
turns a boolean flag indicating whether the host browser is java-enabled or not. specifications specification status comment html living standardthe definition of 'navigatorplugins' in that specification. living standard initial definition. ...
NavigatorStorage.storage - Web APIs
syntax var storagemanager = navigator.storage; value a storagemanager object you can use to maintain persistence for stored data, as well as to determine roughly how much room there is for data to be stored. ...
NavigatorStorage - Web APIs
g cookies, the web storage api (window.localstorage and window.sessionstorage), and indexeddb. the storage standard is designed to serve as a common basis for the implementation of all of those apis and storage technologies, so that their constraints and configurations can be understood and controlled using a common set of methods and properties. properties storage read only secure context re
turns the storagemanager singleton object which is used to access the storage manager. through the re
turned object, you can control persistence of data stores as well as get estimates of how much space is left for your site or appliation to store data. methods the navigatorstorage mixin has no methods. specifications specification status comment storage living stand...
NetworkInformation.downlink - Web APIs
this value is based on recently observed application layer throughput across recently active connections, excluding connections made to a private address space. in the absence of recent bandwidth measurement data, the attribute value is determined by the properties of the underlying connection technology. note that chrome-based browsers do not conform to the specification, and arbitrarily cap the reported downlink at a maximum of 10 mbps as an anti-fingerprinting measure. similar caps exist for the reported latency. ...
NetworkInformation.effectiveType - Web APIs
this value is determined using a combination of recently observed, round-trip time and downlink values. syntax var effectivetype = networkinformation.effectivetype value a string containing one of 'slow-2g', '2g', '3g', or '4g'. ...
NetworkInformation.rtt - Web APIs
the networkinformation.rtt read-only property re
turns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. this value is based on recently observed application-layer rtt measurements across recently active connections. it excludes connections made to a private address space. if no recent measurement data is available, the value is based on the properties of the underlying connection technology. note: this feature is available in web workers. syntax rtt = networkinformation.rtt re
turn value a number. specifications specification status comment network information apithe definition of 'rtt' in that specification. draft initial definition ...
NetworkInformation.saveData - Web APIs
the networkinformation.savedata read-only property of the networkinformation interface re
turns true if the user has set a reduced data usage option on the user agent. syntax var savedata = networkinformation.savedata; value a boolean. specifications specification save data api ...
NetworkInformation.type - Web APIs
the networkinformation.type read-only property re
turns the type of connection a device is using to communicate with the network. note: this feature is available in web workers. syntax var type = netinfo.type re
turn value an enumerated value that is one of the following values: "bluetooth" "cellular" "ethernet" "none" "wifi" "wimax" "other" "unknown" specifications specification status comment network information apithe definition of 'type' in that specification. draft initial definition ...
Node.baseURIObject - Web APIs
this property exists on all nodes (html, xul, svg, mathml, etc.), but only if the script trying to use it has universalxpconnect privileges. see node.baseuri for details on what the base url is. syntax uriobj = node.baseuriobject value an nsiuri. this property is read-only; attempting to write to it will throw an exception. in addition, this property may only be accessed from privileged code. ...
Node.childNodes - Web APIs
the node.childnodes read-only property re
turns a live nodelist of child nodes of the given element where the first child node is assigned index 0. syntax let nodelist = elementnodereference.childnodes; examples simple usage // parg is an object reference to a <p> element // first check that the element has child nodes if (parg.haschildnodes()) { let children = parg.childnodes; for (let i = 0; i < children.length; i++) { // do something with each child as children[i] // note: list is live! adding or removing children will change the list's `length` } } remove all children from a node // this is one way to remove all children from a node // box is an object reference to an element while (box.firstchild) { //the list is live so it will re-index each call ...
Node.cloneNode() - Web APIs
syntax let newclone = node.clonenode([deep]) node the node to be cloned. newclone the new node, cloned from node. the newclone has no parent and is not part of the document, until it is added to another node that is part of the document (using node.appendchild() or a similar method). deep optional* if true, then node and its whole subtree—including text that may be in child text nodes—is also copied. if false, only node will be cloned. any text that node contains is not cloned, either (since text is contained by one or more child text nodes). deep has no effect on empty elements (such as the <img> and <input> elements). ...
Node.contains() - Web APIs
the node.contains() method re
turns a boolean value indicating whether a node is a descendant of a given node, i.e. the node itself, one of its direct children (childnodes), one of the children's direct children, and so on. syntax node.contains( othernode ) example this function checks to see if an element is in the page's body. as contains is inclusive and determining if the body contains itself isn't the intention of isinpage this case explicitly re
turns false. function isinpage(node) { re
turn (node === document.body) ? false : document.body.contains(node); } specifications specification status comment domthe definition of 'node.contains()' in that specification. living standard initial definition ...
Node.getUserData() - Web APIs
the node.setuserdata and node.getuserdata methods are no longer available from web content. element.dataset or weakmap can be used instead. syntax userdata = somenode.getuserdata(userkey); parameters userkey is the key to choose the specific data sought for the given node. more than one key may have been assigned on a given node, containing its own value. ...
Node.isDefaultNamespace() - Web APIs
the node.isdefaultnamespace() method accepts a namespace uri as an argument and re
turns a boolean with a value of true if the namespace is the default namespace on the given node or false if not. syntax result = node.isdefaultnamespace(namespaceuri); parameters namespaceuri is a string representing the namespace against which the element will be checked. re
turn value result is a boolean that holds the re
turn value true or false. example var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getelementsbytagnamens(xulns, 'textbox')[0]; alert(el.isdefaultnamespace(xulns)); // true specifications specification status comment domthe definition of 'node: isdefaultnamespace' in that specification. living standard ...
Node.isSupported() - Web APIs
the node.issupported()re
turns a boolean flag containing the result of a test whether the dom implementation implements a specific feature and this feature is supported by the specific node. syntax boolvalue = element.issupported(feature, version) parameters feature is a domstring containing the name of the feature to test. this is the same name which can be passed to the method hasfeature on domimplementation. possible values defined within the core dom specification are listed on the dom level 2 conformance section. version is a domstring containing the version number of the feature to test. in dom level 2, version 1, this is the string 2.0. if the version is not specified, supporting any version of the feature will cause the method to re
turn true. example <div id="doc"> </div>...
Node.lastChild - Web APIs
syntax var childnode = node.lastchild; example var tr = document.getelementbyid("row1"); var corner_td = tr.lastchild; specifications specification status comment domthe definition of 'node.lastchild' in that specification. living standard no change document object model (dom) level 3 core specificationthe definition of 'node.lastchild' in that specification. ...
Node.lookupNamespaceURI() - Web APIs
the node.lookupnamespaceuri() method accepts a prefix and re
turns the namespace uri associated with it on the given node if found (and null if not). syntax var namespace = node.lookupnamespaceuri(prefix); parameters prefix the prefix to look for. if this parameter is null, the method will re
turn the default namespace uri, if any. re
turn value a domstring containing the the namespace uri. if the prefix is not found, it re
turns null. specifications specification status comment domthe definition of 'node: lookupnamespaceuri' in that specification. living standard ...
Node.namespaceURI - Web APIs
the node.namespaceuri read-only property re
turns the namespace uri of the node, or null if the node is not in a namespace. when the node is a document, it re
turns the xml namespace for the current document. in dom4 this api was moved from node to the element and attr interfaces. syntax namespace = node.namespaceuri example in this snippet, a node is being examined for its node.localname and its namespaceuri. if the namespaceuri re
turns the xul namespace and the localname re
turns "browser", then the node is understood to be a xul <browser/>. if (node.localname == "browser" && node.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an ...
Node.nextSibling - Web APIs
syntax nextnode = node.nextsibling notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get. see whitespace in the dom and w3c dom 3 faq: why are some text nodes empty? for more information. ...
Node.nodePrincipal - Web APIs
note: this property exists on all nodes (html, svg, mathml, xul, etc.), but only if the script trying to use it has chrome privileges. ...
Node.nodeType - Web APIs
possible values are listed in node type constants. constants node type constants constant value description node.element_node 1 an element node like <p> or <div>. node.text_node 3 the actual text inside an element or attr. ...
Node.ownerDocument - Web APIs
syntax var document = element.ownerdocument; value document is the top-level document object in which all the child nodes are created. if this property is used on a node that is itself a document, the value is null. ...
Node.parentElement - Web APIs
syntax parentelement = node.parentelement parentelement is the parent element of the current node. this is always a dom element object, or null. ...
Node.parentNode - Web APIs
the node.parentnode read-only property re
turns the parent of the specified node in the dom tree. syntax parentnode = node.parentnode parentnode is the parent of the current node. the parent of an element is an element node, a document node, or a documentfragment node. example if (node.parentnode) { // remove a node from the tree, unless // it's not in the tree already node.parentnode.removechild(node); } notes document and documentfragment nodes can never have a parent, so parentnode will always re
turn null. it also re
turns null if the node has just been created and is not yet attached to the tree. specifications specification status comment domthe definition of 'node: parentnode' in that specification. living standard ...
Node.prefix - Web APIs
in dom4 this api was moved from node to the element and attr interfaces. syntax string = node.prefix examples the following logs "x" to the console. <x:div onclick="console.log(this.prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.prefix' in that specification. obsolete specifies the behavior when it's set to null. ...
Node.previousSibling - Web APIs
syntax previousnode = node.previoussibling; example <img id="b0"> <img id="b1"> <img id="b2"> console.log(document.getelementbyid("b1").previoussibling); // <img id="b0"> console.log(document.getelementbyid("b2").previoussibling.id); // "b1" notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get. ...
Node.removeChild() - Web APIs
syntax var oldchild = node.removechild(child); or node.removechild(child); child is the child node to be removed from the dom. node is the parent node of child. oldchild holds a reference to the removed child node, i.e., oldchild === child. the removed child node still exists in memory, but is no longer part of the dom. with the first syntax form shown, you may reuse the removed node later in your code, via the oldchild object reference. ...
Node.replaceChild() - Web APIs
de.replacechild() method replaces a child node within the given (parent) node. note the idiosyncratic argument order (new before old). childnode.replacewith() may be easier to read and use. syntax parentnode.replacechild(newchild, oldchild); parameters newchild the new node to replace oldchild. if it already exists in the dom, it is first removed. oldchild the child to be replaced. re
turn value the re
turned value is the replaced node. this is the same node as oldchild. example // given: // <div> // <span id="childspan">foo bar</span> // </div> // create an empty element node // without an id, any attributes, or any content var sp1 = document.createelement("span"); // give it an id attribute called 'newspan' sp1.id = "newspan"; // create some content for the new element. var...
Node.rootNode - Web APIs
important: for compatibility reasons, this property has been replaced by the node.getrootnode() method. the node.rootnode read-only property re
turns a node object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. this is found by walking backward along node.parentnode until the top is reached. syntax rootnode = node.rootnode; value a node object representing the topmost node in the tree. example running the following line in supporting browsers should re
turn a reference to the html/document node: console.log(document.body.rootnode); notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. therefore a node obtained, for example, using node.firstchild or node.previoussibling may ...
NodeIterator.detach() - Web APIs
which it iterates, releasing any resources used by the set and setting the iterator's state to invalid. once this method had been called, calls to other methods on nodeiterator would raise the invalid_state_err exception. syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err exception specifications specification status comment domthe definition of 'nodeiterator.detach' in that specification. living standard transformed in a no-op document object model (dom) level 2 traversal and...
NodeIterator.pointerBeforeReferenceNode - Web APIs
the nodeiterator.pointerbeforereferencenode read-only property re
turns a boolean flag that indicates whether the nodefilter is anchored before (if this value is true) or after (if this value is false) the anchor node indicated by the nodeiterator.referencenode property. syntax flag = nodeiterator.pointerbeforereferencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); flag = nodeiterator.pointerbeforereferencenode; specifications specification status comment domthe definition of 'nodeiterator.pointerbeforereferencenode' in that specification. living standard initial definition. ...
NodeIterator.referenceNode - Web APIs
the nodeiterator.referencenode read-only re
turns the node to which the iterator is anchored; as new nodes are inserted, the iterator remains anchored to the reference node as specified by this property. syntax node = nodeiterator.referencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); node = nodeiterator.referencenode; specifications specification status comment domthe definition of 'nodeiterator.referencenode' in that specification. living standard initial definition. ...
NodeIterator.root - Web APIs
the nodeiterator.root read-only property represents the node that is the root of what the nodeiterator traverses. syntax root = nodeiterator.root; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); root = nodeiterator.root; // document.body in this case specifications specification status comment domthe definition of 'nodeiterator.root' in that specification. living standard no change from document object model (dom) level 2 traversal and range specification. document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator.root' in that specification. obsolete initial ...
NodeList.entries() - Web APIs
the nodelist.entries() method re
turns an iterator allowing to go through all key/value pairs contained in this object. the values are node objects. syntax list.entries(); re
turn value re
turns an iterator. example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var entry of list.entries()) { console.log(entry); } results in: array [ 0, <p> ] array [ 1, #text "hey" ] array [ 2, <span> ] ...
NodeList.prototype.forEach() - Web APIs
allback a function to execute on each element of somenodelist. it accepts 3 parameters: currentvalue the current element being processed in somenodelist. currentindex optional the index of the currentvalue being processed in somenodelist. listobj optional the somenodelist that foreach() is being applied to. thisarg optional value to use as this when executing callback. re
turn value undefined. example let node = document.createelement("div"); let kid1 = document.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' ...
NodeList.keys() - Web APIs
the nodelist.keys() method re
turns an iterator allowing to go through all keys contained in this object. the keys are unsigned integer. syntax nodelist.keys(); re
turn value re
turns an iterator. example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var key of list.keys()) { console.log(key); } the result is: 0 1 2 ...
NodeList.length - Web APIs
syntax numitems = nodelist.length numitems is an integer value representing the number of items in a nodelist. example the length property is often useful in dom programming. it's often used to test the length of a list, to see if it exists at all. it's also commonly used as the iterator in a for loop, as in this example. ...
NodeList.values() - Web APIs
the nodelist.values() method re
turns an iterator allowing to go through all values contained in this object. the values are node objects. syntax nodelist.values(); re
turn value re
turns an iterator. example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var value of list.values()) { console.log(value); } the result is: <p> #text "hey" <span> ...
NonDocumentTypeChildNode - Web APIs
cumenttypechildnode interface contains methods that are particular to node objects that can have a parent, but not suitable for documenttype. nondocumenttypechildnode is a raw interface and no object of this type can be created; it is implemented by element, and characterdata objects. properties there are no inherited properties. nondocumenttypechildnode.previouselementsibling read only re
turns the element immediately prior to this node in its parent's children list, or null if there is no element in the list prior to this node. nondocumenttypechildnode.nextelementsibling read only re
turns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node. methods there are neither inherited nor specific metho...
Notification.actions - Web APIs
this is a list of the application-defined actions the user can choose to take immediately within the context of a notification. note: device and user agent might be able to display only a limited number of actions (due to, e.g., limited screen space). this limit can be infered from notification.maxactions. ...
Notification.close() - Web APIs
tification from any notification tray, preventing users from interacting with it after it was initially shown. a valid use for this api would be to remove a notification that is no longer relevant (e.g. the user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). syntax notification.close(); parameters none. re
turns void. examples in the following snippet, we have a simple function that when called creates an options object and then a new notification. at the end of the function, it also calls close() inside a addeventlistener() function to remove the notification when the relevant content has been read on the webpage. function spawnnotification(thebody, theicon, thetitle) { var options = { body: ...
Notification.dir - Web APIs
em to ignore explicit ltr and rtl settings, and just go with the browser-wide setting. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', dir: 'rtl' } var n = new notification('test notification',options); console.log(n.dir) // should re
turn 'rtl' specifications specification status comment notifications apithe definition of 'dir' in that specification. living standard living standard ...
Notification.lang - Web APIs
var language = notification.lang; value a domstring specifying the language tag. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', lang: 'en-us' } var n = new notification('test notification',options); console.log(n.lang) // should re
turn 'en-us' specifications specification status comment notifications apithe definition of 'lang' in that specification. living standard living standard ...
Notification.maxActions - Web APIs
effectively, this is the maximum number of elements in notification.actions array which will be respected by the user agent. syntax notification.maxactions value an integer number which indicates the largest number of notification actions that can be presented to the user by the user agent and the device. examples the following snippet logs the maximum number of supported actions. ...
Notification.requestPermission() - Web APIs
syntax that works like this: notification.requestpermission().then(function(permission) { ... }); previously, the syntax was based on a simple callback; this version is now deprecated: notification.requestpermission(callback); parameters callback optional deprecated since gecko 46 an optional callback function that is called with the permission value. deprecated in favor of the promise re
turn value. re
turns a promise that resolves to a domstring with the permission picked by the user. possible values for this string are: granted denied default examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first che...
Notification.requireInteraction - Web APIs
note: this can be set when the notification is first created by setting the requireinteraction option to true in the options object of the notification.notification() constructor. ...
Notification.timestamp - Web APIs
the notification's timestamp can represent the time, in milliseconds since 00:00:00 utc on 1 january 1970, of the event for which the notification was created, or it can be an arbitrary timestamp that you want associated with the notification. for example, a timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past. syntax var timestamp = notification.timestamp; value a domtimestamp. ...
Notification - Web APIs
the actions array of the notification as specified in the constructor's options parameter. notification.badge read only the url of the image used to represent the notification when there is not enough space to display the notification itself. notification.body read only the body string of the notification as specified in the constructor's options parameter. notification.data read only re
turns a structured clone of the notification’s data. notification.dir read only the text direction of the notification as specified in the constructor's options parameter. notification.lang read only the language code of the notification as specified in the constructor's options parameter. notification.tag read only the id of the notification (if any) as specified in the constructor's optio...
NotificationEvent.action - Web APIs
re
turns the string id of the notification button the user clicked. this value re
turns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. the notification id is set during the creation of the notification via the actions array attribute and can't be modified unless the notification is replaced. re
turns a domstring object. example self.registration.shownotification("new articles available", { actions: [{action: "get", title: "get now."}] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizereader(); } else { clients.openwindow("/reader"); } }, false); specifications specification status comme...
Using the Notifications API - Web APIs
ation.requestpermission() in the load event handler (see issue 274284). feature-detecting the requestpermission() promise above we said that we had to check whether the browser supports the promise version of notification.requestpermission(). we did this using the following: function checknotificationpromise() { try { notification.requestpermission().then(); } catch(e) { re
turn false; } re
turn true; } we basically try to see if the .then() method is available on requestpermission(). if so, we move on and re
turn true. if it fails, we re
turn false in the catch() {} block. creating a notification creating a notification is easy; just use the notification constructor. this constructor expects a title to display within the notification and some options to enhan...
OES_vertex_array_object.createVertexArrayOES() - Web APIs
the oes_vertex_array_object.createvertexarrayoes() method of the webgl api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data. syntax webglvertexarrayobjectoes ext.createvertexarrayoes(); parameters none. re
turn value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data. examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment oes_vertex_array_objectthe definitio...
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
the oes_vertex_array_object.deletevertexarrayoes() method of the webgl api deletes a given webglvertexarrayobject object. syntax void ext.deletevertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to delete. re
turn value none. examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ... ext.deletevertexarrayoes(vao); specifications specification status comment oes_vertex_array_objectthe definition of 'oes_vertex_array_object' in that specification. recommendation initial definition. ...
OES_vertex_array_object - Web APIs
ions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default and the constants and methods are available without the "oes" suffix. constants this extension exposes one new constant, which can be used in the gl.getparameter() method: ext.vertex_array_binding_oes re
turns a webglvertexarrayobject object when used in the gl.getparameter() method as the pname parameter. methods this extension exposes four new methods. ext.createvertexarrayoes() creates a new webglvertexarrayobject. ext.deletevertexarrayoes() deletes a given webglvertexarrayobject. ext.isvertexarrayoes() re
turns true if a given object is a webglvertexarrayobject. ext.bindvert...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
cil_attachment: depth and stencil buffer data storage. texture a webgltexture object whose image to attach. level a glint specifying the mipmap level of the texture image to be attached. must be 0. baseviewindex a glint specifying the base view index of the framebuffer object attachment. numviews a glsizei specifying the number of views of the framebuffer object attachment. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer. attachment is not one of the accepted attachment points. a gl.invalid_value error is thrown if level is not 0. if numviews is less than one or more than max_views_ovr. a gl.invalid_operation error is thrown if texture isn't 0 or the name of an existing texture object. e...
OVR_multiview2 - Web APIs
headset with ultra-wide fov using 4 views which is currently the maximum number of views supported by multiview. framebuffer_incomplete_view_targets_ovr if baseviewindex is not the same for all framebuffer attachment points where the value of framebuffer_attachment_object_type is not none, the framebuffer is considered incomplete. calling checkframebufferstatus for a framebuffer in this state re
turns framebuffer_incomplete_view_targets_ovr. methods framebuffertexturemultiviewovr() simultaneously renders to multiple elements of a 2d texture array. examples this example is taken from the specification. see also this three.js demo for a live multiview example. const gl = document.createelement('canvas').getcontext( 'webgl2', { antialias: false } ); const ext = gl.getextension('ovr_mul...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
manually. offlineaudiocompletionevents are despatched to offlineaudiocontext instances for legacy reasons. syntax var offlineaudiocompletionevent = new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create. init optional options are as follows: renderedbuffer: the rendered audiobuffer containing the audio data. re
turn value a new offlineaudiocompletionevent object instance. specifications specification status comment web audio apithe definition of 'offlineaudiocompletionevent()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, p...
OfflineAudioContext.resume() - Web APIs
interface resumes the progression of time in an audio context that has been suspended. the promise resolves immediately because the offlineaudiocontext does not require the audio hardware. if the context is not currently suspended or the rendering has not started, the promise is rejected with invalidstateerror. syntax offlineaudiocontext.resume().then(function() { ... }); parameters none. re
turns a promise resolving to void. exceptions the promise is rejected when the following exception is encountered. invalidstateerror if the context is not currently suspended or the rendering has not started. specifications specification status comment web audio apithe definition of 'resume()' in that specification. working draft initial definition. ...
OffscreenCanvas.convertToBlob() - Web APIs
lob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. re
turn value a promise re
turning a blob object representing the image contained in the canvas. examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: ...
OffscreenCanvas() - Web APIs
syntax new offscreencanvas(width, height); parameters width the width of the offscreen canvas. height the height of the offscreen canvas. examples this example creates a new offscreen canvas using the offscreencanvas() constructor. we then initialize a webgl context on it using the getcontext() method. ...
OffscreenCanvas.convertToBlob() - Web APIs
lob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. re
turn value a promise re
turning a blob object representing the image contained in the canvas. examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications specification status ...
OffscreenCanvas.height - Web APIs
the height property re
turns and sets the height of an offscreencanvas object. syntax var pxl = offscreen.height; offscreen.height = pxl; examples creating a new offscreen canvas and re
turning or setting the height of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.height; // 256 offscreen.height = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.height' in that specification. living standard ...
OffscreenCanvas.convertToBlob() - Web APIs
lob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format. the default type is image/png. quality: a number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. if this argument is anything else, the default value for image quality is used. other arguments are ignored. re
turn value a promise re
turning a blob object representing the image contained in the canvas. examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some drawing using the gl context ... offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: ...
OffscreenCanvas.width - Web APIs
the width property re
turns and sets the width of an offscreencanvas object. syntax var pxl = offscreen.width; offscreen.width = pxl; examples creating a new offscreen canvas and re
turning or setting the width of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.width; // 256 offscreen.width = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.width' in that specification. living standard ...
OrientationSensor.populateMatrix() - Web APIs
feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax orientationinstance.populatematrix(targetmatrix) because orientationsensor is a base class, populatematrix may only be read from one of its derived classes. parameters targetmatrix tbd re
turn value undefined example // tbd specifications specification status comment orientation sensorthe definition of 'populatematrix' in that specification. candidate recommendation initial definition. ...
OrientationSensor.quaternion - Web APIs
syntax var quaternion = orientationinstance.quaternion because orientationsensor is a base class, quaternion may only be read from one of its derived classes. value a array whose values are the x, y, z, and w components of the quaternion representing the device orientation. ...
OrientationSensor - Web APIs
because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. interfaces based on orientationsensor below is a list of interfaces based on the orientationsensor interface. absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion re
turns a four element array whose elements contain the components of the unit quaternion representing the device's orientation. methods orientationsensor.populatematrix() populates the given object with the rotation matrix based on the latest sensor reading. the rotation maxtrix is shown below. examples basic example the following example, which is loosely based on intel's orientation phone d...
OscillatorNode.OscillatorNode() - Web APIs
oduced by the node. valid values are 'sine', 'square', 'sawtooth', 'triangle' and 'custom'. the default is 'sine'. detune a detuning value (in cents) which will offset the frequency by the given amount. its default is 0. frequency the frequency (in hertz) of the periodic waveform. its default is 440. periodicwave an arbitrary period waveform described by a periodicwave object. re
turn value a new oscillatornode object instance. specifications specification status comment web audio apithe definition of 'oscillatornode()' in that specification. working draft initial definition. ...
OscillatorNode.detune - Web APIs
value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. ...
OscillatorNode.setPeriodicWave() - Web APIs
f the oscillatornode interface is used to point to a periodicwave defining a periodic waveform that can be used to shape the oscillator's output, when type is custom. this replaces the now-obsolete oscillatornode.setwavetable(). syntax oscillatornode.setperiodicwave(wave); parameters wave a periodicwave object representing the waveform to use as the shape of the oscillator's output. re
turns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave. var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.
OscillatorNode - Web APIs
ying default values for the node's properties. if the default values are acceptable, you can simply call the baseaudiocontext.createoscillator() factory method. properties inherits properties from its parent, audioscheduledsourcenode, and adds the following properties: oscillatornode.frequency an a-rate audioparam representing the frequency of oscillation in hertz (though the audioparam re
turned is read-only, the value it represents is not). the default value is 440 hz (a standard middle-a note). oscillatornode.detune an a-rate audioparam representing detuning of oscillation in cents (though the audioparam re
turned is read-only, the value it represents is not). the default value is 0. oscillatornode.type a string which specifies the shape of waveform to play; this can be one ...
PaymentAddress.organization - Web APIs
syntax var paymentorganization = paymentaddress.organization; value a domstring whose value is the name of the organization or company located at the address described by the paymentaddress object. this should be the name of the organization that is to receive the shipment for shipping addresses, or which is repsonsible for payment for payment addresses. ...
PaymentAddress.phone - Web APIs
syntax var paymentphone = paymentaddress.phone; value a domstring containing the telephone number for the recipient of the shipment or of the responsible party for payment. if no phone number is available, this value is an empty string. ...
PaymentAddress.postalCode - Web APIs
syntax var paymentpostalcode = paymentaddress.postalcode; value a domstring which contains the postal code portion of the address. a postal code is a string (either numeric or alphanumeric) which is used by a postal service to optimize mail routing and delivery. various countries use different terms for this. in most of the world, it's known as the "post code" or "postal code." in the united states, the zip code is used. india uses pin codes. ...
PaymentAddress.recipient - Web APIs
syntax var paymentrecipient = paymentaddress.recipient; value a domstring giving the name of the person receiving or paying for the purchase, or the name of a contact person in other contexts. if no name is available, this string is empty. ...
PaymentAddress.region - Web APIs
the read-only region property of the paymentaddress interface re
turns a string containing the top-level administrative subdivision of the country in which the address is located. for example, this may be a state, province, oblast, or prefecture. syntax var paymentregion = paymentaddress.region; value a domstring specifying the top-level administrative subdivision within the country in which the address is located. this region has different names in different countries, such as: state, province, oblast, prefecture, or county. usage notes in some countries, like belgium, it's uncommon for people to provide a region as part of their postal address. in such cases, the browser re
turns an empty string as the value of region. however, the address should still be acceptable to use for its inten...
PaymentAddress.toJSON() - Web APIs
specifications specification status comment web idlthe definition of 'tojson()' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PaymentAddress - Web APIs
erties are obsolete and should no longer be used, but may still be present in some browser versions. paymentaddress.languagecode read only a domstring indicating the language code of the address. this identifies the language in which the address is given, and is intended to aid in localization of the display of the address. methods paymentaddress.tojson() a standard serializer that re
turns a json representation of the paymentaddress object's properties. examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an op...
PaymentDetailsBase - Web APIs
choose. derived dictionaries the following dictionaries include paymentdetailsbase. paymentdetailsinit provides payment information when calling the paymentrequest() constructor. paymentdetailsupdate provides updated payment details while the payment user interface is being handled. this can be delivered to the payment interface using either paymentdetailsupdateevent.updatewith() or by re
turning it from the optional detailsupdate promise provided to the paymentrequest.show() call that begins the user interaction. specifications specification status comment payment request apithe definition of 'paymentdetailsbase' in that specification. candidate recommendation initial definition. ...
PaymentDetailsUpdate - Web APIs
the paymentdetailsupdate dictionary is used to provide updated information to the payment user interface after it has been instantiated. this can be done either by calling the paymentrequestupdateevent.updatewith() method or by using the paymentrequest.show() method's detailspromise parameter to provide a promise that re
turns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time. properties the paymentdetailsupdate dictionary is based on the paymentdetailsbase dictionary, and inherits its properties, which are included in the list below. displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. error o...
PaymentMethodChangeEvent - Web APIs
lowing properties: methodname optional a domstring containing the payment method identifier for the payment handler being used. this is an empty string by default. methoddetails optional an object providing payment method-specific information describing the changes made to the payment, or null if there is no additional information available or required. this is null by default. re
turn value a newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property. the type of the methoddetails property depends on the payment method. for example, if methodname is basic-card, indicating that the basic card payment method is being used for validation, the methoddetails field must be a basiccardchangedeta...
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent interface of the payment request api describes the paymentmethodchange event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using apple pay). constructor paymentmethodchangeevent() creates and re
turns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary. properties in addition to the properties below, this interface includes properties inherited from paymentrequestupdateevent. methoddetails read only secure context an object containing payment method-specific data useful when handling a payment method change. if no such information is available, this value is null. ...
PaymentRequest.PaymentRequest() - Web APIs
shippingtype. the default is false. shippingtype lets you specify how the user interface refers to shipping when the word 'shipping' isn't appropriate for your use case. for example, in english speaking countries you would say "pizza delivery" not "pizza shipping". valid values are "shipping", "delivery", and "pickup". quotation marks must be included. the default value is "shipping". re
turn value a new paymentrequest object, configured for use as configured by the input parameters. examples the following example shows minimal functionality and focuses instead on showing the complete context of instantiating a paymentrequest object. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', ...
PaymentRequest.abort() - Web APIs
parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
PaymentRequest.onmerchantvalidation - Web APIs
elves 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; re
turn await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. specifications specification status comment payment request apithe definition of 'onmerchantvalidation' in that specification. candidate recommendation initial definition. ...
PaymentResponse.onpayerdetailchange - Web APIs
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, re
turning a promise which // resolves if the data is valid. if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphon...
PaymentResponse.payerEmail - Web APIs
this option is only present when the requestpayeremail option is set to true in the paymentoptions object passed to the paymentrequest constructor. syntax var payeremail = paymentresponse.payeremail; specifications specification status comment payment request api candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PaymentRequest.payerName - Web APIs
this option is only present when the requestpayername option is set to true in the options parameter of the paymentrequest() constructor. syntax var payername = paymentresponse.payername; value a string containing the payer name. specifications specification status comment payment request apithe definition of 'payername' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
PayerResponse.payerPhone - Web APIs
this option is only present when the requestpayerphone option is set to true in the paymentoptions object passed to the paymentrequest constructor. ...
PaymentResponse: payerdetailchange event - Web APIs
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, re
turning a promise which // resolves if the data is valid. if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphon...
PaymentResponse.requestId - Web APIs
syntax var id = paymentrequest.id value a domstring. specifications specification status comment payment request apithe definition of 'requestid' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PaymentResponse.shippingAddress - Web APIs
syntax var shippingaddress = paymentrequest.shippingaddress; value a paymentaddress object providing details comprising the shipping address provided by the user. example generally, the user agent will fill the shippingaddress property for you. you can trigger this by setting paymentoptions.requestshipping to true when calling the paymentrequest constructor. in the example below, the cost of shipping varies by geography. ...
PaymentValidationErrors - Web APIs
the paymentvalidationerrors dictionary represents objects providing information about any and all errors that occurred while processing a payment request. when validation of the paymentresponse re
turned by the paymentrequest.show() or paymentresponse.retry() methods fails, your code creates a paymentvalidationerrors object to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user. properties error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview whil...
Payment processing concepts - Web APIs
t; for example, if the user chooses to pay using a credit card that isn't accepted by the payee, the payment can't be made. if merchant validation is supported by the payment handler, respond to merchant validation requests from the user agent. see merchant validation for details. verify that the information provided by the user results in a valid transaction. this results in the creation and re
turning of a payment method-specific object that contains the information needed to handle the transaction. merchant validation some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic challenge. if the merchant doesn't successfully validate, it's not allowed to use the payment handler. the ex...
Payment Request API - Web APIs
gent's payment interface. paymentrequestevent an event delivered to a payment handler when a paymentrequest is made. paymentrequestupdateevent enables the web page to update the details of the payment request in response to a user action. paymentmethodchangeevent represents the user changing payment instrument (e.g., switching from a credit card to debit card). paymentresponse an object re
turned after the user selects a payment method and approves a payment request. merchantvalidationevent represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allowed to use apple pay). dictionaries addresserrors a dictionary containing strings providing descriptive explanations of any errors in any p...
performance.clearMarks() - Web APIs
performance entries with an entry type of "mark" will be removed from the performance entry buffer. note: this feature is available in web workers. syntax performance.clearmarks(); performance.clearmarks(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "mark" will be removed. re
turn value void example the following example shows both uses of the clearmarks() method. // create a small helper to show how many performancemark entries there are. function logmarkcount() { console.log( "found this many entries: " + performance.getentriesbytype("mark").length ); } // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.
performance.clearMeasures() - Web APIs
entries with an entry type of "measure" will be removed from the performance entry buffer. note: this feature is available in web workers. syntax performance.clearmeasures(); performance.clearmeasures(name); arguments name optional a domstring representing the name of the timestamp. if this argument is omitted, all performance entries with an entry type of "measure" will be removed. re
turn value void example the following example shows both uses of the clearmeasures() method. // create a small helper to show how many performancemeasure entries there are. function logmeasurecount() { console.log( "found this many entries: " + performance.getentriesbytype("measure").length ); } // create a bunch of measures. performance.measure("from navigation"); performance.mark(...
performance.mark() - Web APIs
entries*() methods (getentries(), getentriesbyname() or getentriesbytype()). the mark()'s stores its data internally as performanceentry. note: this feature is available in web workers. syntax performance.mark(name); arguments name a domstring representing the name of the mark. if the name given to this method already exists in the performancetiming interface, syntaxerror is thrown. re
turn value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); // get all of the performancemark entries. const allentries = performance.getentri...
performance.measure() - Web APIs
rtmark optional a domstring representing the name of the measure's starting mark. may also be the name of a performancetiming property. if it is omitted, then the start time will be the navigation start time. endmark optional a domstring representing the name of the measure's ending mark. may also be the name of a performancetiming property. if it is omitted, then the current time is used. re
turn value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer. const markernamea = "example-marker-a" const markernameb = "example-marker-b" // run some nested timeouts, and create a performancemark for each. performance.mark(markernamea); settimeout(function() { performance.mark(markernameb); ...
Performance.onresourcetimingbufferfull - Web APIs
the onresourcetimingbufferfull property is an event handler that will be called when the resourcetimingbufferfull event is fired. this event is fired when the browser's resource timing performance buffer is full. note: this feature is available in web workers. syntax callback = performance.onresourcetimingbufferfull = buffer_full_cb; re
turn value callback an eventhandler that is invoked when the resourcetimingbufferfull event is fired. examples the following example sets a callback function on the onresourcetimingbufferfull property. function buffer_full(event) { console.log("warning: resource timing buffer is full!"); performance.setresourcetimingbuffersize(200); } function init() { // set a callback if the resource buffer becomes filled performance.onresourcetimingbuffe...
performance.setResourceTimingBufferSize() - Web APIs
esource" performance entry type objects. a browser's recommended resource timing buffer size is at least 150 performance entry objects. note: this feature is available in web workers. syntax performance.setresourcetimingbuffersize(maxsize); arguments maxsize a number representing the maximum number of performance entry objects the browser should hold in its performance entry buffer. re
turn value none this method has no re
turn value. example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); re
turn; } var supported = typeof performance.setresourcetimingbuffersize == "function"; if (supported) { log("... performance.setresourcetimingbuffersize() = yes"); performance.setresour...
Performance.timeOrigin - Web APIs
note: this feature is available in web workers. syntax var timeorigin = performance.timeorigin value a high resolution timestamp. specifications specification status high resolution time level 2the definition of 'timeorigin' in that specification. recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Performance.timing - Web APIs
this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performance.timing read-only property re
turns a performancetiming object containing latency-related performance information. this property is not available in workers. syntax timinginfo = performance.timing; specifications specification status comment navigation timing level 2 working draft initial definition. ...
performance.toJSON() - Web APIs
the tojson() method of the performance interface is a standard serializer: it re
turns a json representation of the performance object's properties. note: this feature is available in web workers. syntax myperf = performance.tojson() arguments none re
turn value myperf a json object that is the serialization of the performance object. example var js; js = window.performance.tojson(); console.log("json = " + json.stringify(js)); specifications specification status comment high resolution time level 2the definition of 'tojson() serializer' in that specification. recommendation defines tojson(). ...
PerformanceLongTaskTiming.attribution - Web APIs
syntax var taskattributetiming = performancelongtasktiming.attribution; value a sequence of taskattributiontiming instances. specifications specification status comment long tasks api 1the definition of 'attribution' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PerformanceLongTaskTiming - Web APIs
specifications specification status comment long tasks api 1the definition of 'performancelongtasktiming' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check...
PerformanceMeasure - Web APIs
y="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">performancemeasure</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has no properties but it extends the following performanceentry properties by qualifying/constrainting the properties as follows: performanceentry.entrytype re
turns "measure". performanceentry.name re
turns the name given to the measure when it was created via a call to performance.measure(). performanceentry.starttime re
turns a timestamp given to the measure when performance.measure() was called. performanceentry.duration re
turns a domhighrestimestamp that is the duration of the measure (typically, the measure's end mark timestamp minus its start mark...
PerformanceNavigation.redirectCount - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancenavigation.redirectcount read-only property re
turns an unsigned short representing the number of redirects done before reaching the page. syntax amount = performancenavigation.redirectcount; specifications specification status comment navigation timingthe definition of 'performancenavigation.redirectcount' in that specification. recommendation initial definition. ...
PerformanceNavigation.type - Web APIs
possible values are: value constant name meaning 0 type_navigate the page was accessed by following a link, a bookmark, a form submission, a script, or typing the url in the address bar. ...
PerformanceNavigation - Web APIs
ion.reload() method. type_back_forward (2) the page was accessed by navigating into the history. type_reserved (255) any other way. performancenavigation.redirectcount read only an unsigned short representing the number of redirects done before reaching the page. methods the performance interface doesn't inherit any methods. performancenavigation.tojson() is a jsonizer re
turning a json object representing the performancenavigation object. specifications specification status comment navigation timingthe definition of 'performancenavigation' in that specification. recommendation initial definition. ...
PerformanceNavigationTiming.toJSON() - Web APIs
the tojson() method is a serializer - it re
turns a json representation of the performancenavigationtiming object. syntax json = resourceperfentry.tojson(); arguments none re
turn value json a json object that is the serialization of the performancenavigationtiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. example // get a resource performance entry var perfentries = performance.getentriesbytype("navigation"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performancenavigationtiming.tojson() = " + s); specifications specification status comment navigation timing level 2the definiti...
PerformanceObserver() - Web APIs
try types that have been registered, via the observe() method. syntax var observer = new performanceobserver(callback); parameters callback a performanceobservercallback callback that will be invoked when observed performance events are recorded. when the callback is invoked, its first parameter is a list of performance observer entries and the second parameter is the observer object. re
turn value a new performanceobserver object which will call the specified callback when observed performance events occur. example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, o...
PerformanceObserver.takeRecords() - Web APIs
the takerecords() method of the performanceobserver interface re
turns the current list of performance entries stored in the performance observer, emptying it out. syntax var performanceentry[] = performanceobserver.takerecords(); parameters none. re
turn value a list of performanceentry objects. example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); var records = observer.takerecords(); console.log(records[0].name); console.log(records[0].starttime); console.log(records[0].duration); specifications specification status comment performance timeline level 2the definition ...
PerformanceObserver - Web APIs
the performanceobserver interface is used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline. note: this feature is available in web workers. constructor performanceobserver() creates and re
turns a new performanceobserver object. methods performanceobserver.observe() specifies the set of entry types to observe. the performance observer's callback function will be invoked when a performance entry is recorded for one of the specified entrytypes performanceobserver.disconnect() stops the performance observer callback from receiving performance entries. performanceobserver.takerecords() re
turns the current list of performance entries stored in the performance observer, emptying it out. ...
PerformanceObserverEntryList - Web APIs
the performanceobserverentrylist interface is a list of peformance events that were explicitly observed via the observe() method. note: this interface is exposed to window and worker. methods performanceobserverentrylist.getentries() re
turns a list of explicitly observed performanceentry objects based on the given filter. performanceobserverentrylist.getentriesbytype() re
turns a list of explicitly observed performanceentry objects of the given entry type. performanceobserverentrylist.getentriesbyname() re
turns a list of explicitly observed performanceentry objects based on the given name and entry type. example // create observer for all performance event types // list is of type performanceobserveentrylist var observe_all = new performanceobserver(function(list, obs) { var pe...
PerformanceResourceTiming.encodedBodySize - Web APIs
the encodedbodysize read-only property represents the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. note: this feature is available in web workers. if the resource is retrieved from an application cache or a local resource, it must re
turn the size of the payload body before removing any applied content-codings. syntax resource.encodedbodysize; re
turn value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and p...
PerformanceResourceTiming.initiatorType - Web APIs
the initiatortype read-only property is a string that represents the type of resource that initiated the performance event. the value of this string is as follows: if the initiator is a element, the property re
turns the element's localname. if the initiator is a css resource, the property re
turns "css". if the initiator is a xmlhttprequest object, the property re
turns "xmlhttprequest". if the initiator is a performancenavigationtiming object, the property re
turns an empty string (""). note: this feature is available in web workers. syntax resource.initiatortype; re
turn value a string representing the type of resource that initiated the performance event, as specified above. example function print_performanceentries() { // use getentriesbytype() to just get the "resource" eve...
PerformanceResourceTiming.nextHopProtocol - Web APIs
the nexthopprotocol read-only property is a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). when a proxy is used, if a tunnel connection is established, this property re
turns the alpn protocol id of the tunneled protocol. otherwise, this property re
turns the alpn protocol id of the first hop to the proxy. note: this feature is available in web workers. syntax resource.nexthopprotocol; re
turn value a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). example the following example uses the nexthopprotocol property. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytyp...
PerformanceResourceTiming.redirectEnd - Web APIs
the redirectend read-only property re
turns a timestamp immediately after receiving the last byte of the response of the last redirect. when fetching a resource, if there are multiple http redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property re
turns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is re
turned. note: this feature is available in web workers. syntax resource.redirectend; re
turn value a timestamp immediately after receiving the last byte of the response of the last redirect. example in the following example, the value of the *start and *end properties of all "resource" type events are lo...
PerformanceResourceTiming.requestStart - Web APIs
the requeststart read-only property re
turns a timestamp of the time immediately before the browser starts requesting the resource from the server, cache, or local resource. if the transport connection fails and the browser retires the request, the value re
turned will be the start of the retry request. there is no end property for requeststart. note: this feature is available in web workers. syntax resource.requeststart; re
turn value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = perf...
PerformanceResourceTiming.toJSON() - Web APIs
the tojson() method is a serializer that re
turns a json representation of the performanceresourcetiming object. syntax json = resourceperfentry.tojson(); arguments none re
turn value json a json object that is the serialization of the performanceresourcetiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. example // get a resource performance entry var perfentries = performance.getentriesbytype("resource"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performanceentry.tojson = " + s); specifications specification status comment resource timing level 2the definition of 'tojson' in that specific...
PerformanceResourceTiming.transferSize - Web APIs
the transfersize read-only property represents the size (in octets) of the fetched resource. the size includes the response header fields plus the response payload body (as defined by rfc7230). note: this feature is available in web workers. if the resource is fetched from a local cache, or if it is a cross-origin resource, this property re
turns zero. syntax resource.transfersize; re
turn value a number representing the size (in octets) of the fetched resource. the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
PerformanceTiming.domComplete - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcomplete read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domcomplete; specifications specification status comment navigation timingthe definition of 'performancetiming.domcomplete' in that specification. recommendation initial definition. ...
PerformanceTiming.domContentLoadedEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcontentloadedeventend read-only property re
turns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after all the scripts that need to be executed as soon as possible, in order or not, has been executed. syntax time = performancetiming.domcontentloadedeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.domContentLoadedEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcontentloadedeventstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing has been executed. syntax time = performancetiming.domcontentloadedeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventstart' in that specification. recommendation initial definition. ...
PerformanceTiming.domLoading - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domloading read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domloading; specifications specification status comment navigation timingthe definition of 'performancetiming.domloading' in that specification. recommendation initial definition. ...
PerformanceTiming.loadEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface's performancenavigationtiming.loadeventend read-only property instead. the legacy performancetiming.loadeventend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the load event handler terminated, that is when the load event is completed. if this event has not yet been sent, or is not yet completed, it re
turns 0. syntax time = performancetiming.loadeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.loadeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.loadEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface's performancenavigationtiming.loadeventstart read-only property instead.. the legacy performancetiming.loadeventstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the load event was sent for the current document. if this event has not yet been sent, it re
turns 0. syntax time = performancetiming.loadeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.loadeventstart' in that specification. recommendation initial definition. ...
PerformanceTiming.redirectEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.redirectend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirect is not of the same origin, the value re
turned is 0. syntax time = performancetiming.redirectend; specifications specification status comment navigation timingthe definition of 'performancetiming.redirectend' in that specification. recommendation initial definition. ...
PerformanceTiming.redirectStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.redirectstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, the first http redirect starts. if there is no redirect, or if one of the redirect is not of the same origin, the value re
turned is 0. syntax time = performancetiming.redirectstart; specifications specification status comment navigation timingthe definition of 'performancetiming.redirectstart' in that specification. recommendation initial definition. ...
PerformanceTiming.requestStart - Web APIs
if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. ...
PerformanceTiming.responseEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.responseend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the browser received the last byte of the response, or when the connection is closed if this happened first, from the server from a cache or from a local resource. syntax time = performancetiming.responseend; specifications specification status comment navigation timingthe definition of 'performancetiming.responseend' in that specification. recommendation initial definition. ...
PerformanceTiming.responseStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.responsestart read-only property re
turns an unsigned long long representing the moment in time (in milliseconds since the unix epoch) when the browser received the first byte of the response from the server, cache, or local resource. syntax time = performancetiming.responsestart; specifications specification status comment navigation timingthe definition of 'performancetiming.responsestart' in that specification. recommendation initial definition. ...
PerformanceTiming.secureConnectionStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.secureconnectionstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the secure connection handshake starts. if no such connection is requested, it re
turns 0. syntax time = performancetiming.secureconnectionstart; specifications specification status comment navigation timingthe definition of 'performancetiming.secureconnectionstart' in that specification. recommendation initial definition. ...
PerformanceTiming.unloadEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.unloadeventend read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value re
turned is 0. syntax time = performancetiming.unloadeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.unloadeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.unloadEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.unloadeventstart read-only property re
turns an unsigned long long representing the moment, in miliseconds since the unix epoch, the unload event has been thrown. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value re
turned is 0. syntax time = performancetiming.unloadeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.unloadeventstart' in that specification. recommendation initial definition. ...
PeriodicWave.PeriodicWave() - Web APIs
herits the options defined in the periodicwaveconstraints dictionary.): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave). imag: a float32array containing the sine terms that you want to use to form the wave (equivalent to the imag parameter of audiocontext.createperiodicwave). re
turn value a new periodicwave object instance. example var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave = new periodicwave(ac, options); specifications specification status comment web aud...
PeriodicWave - Web APIs
constructor periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties. ...
PermissionStatus.state - Web APIs
the state read-only property of the permissionstatus interface re
turns the state of a requested permission. this property re
turns one of 'granted', 'denied', or 'prompt'. syntax var permission = permissionstatus.state; example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission state is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission status has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'state' in that specification. working draft initial definition. ...
Permissions.revoke() - Web APIs
y message or be able to send silent push notifications. the default is false. sysex: (midi only) indicates whether you need and/or receive system exclusive messages. the default is false. note: as of firefox 44, the permissions for notifications and push have been merged. if permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will re
turn true for both notifications and push. note: the persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the storage api. re
turns a promise that calls its fulfillment handler with a permissionstatus object indicating the result of the request. exceptions typeerror retrieving the permissiondescriptor information failed in so...
Permissions - Web APIs
permissions.request() requests permission to use a given api. this is not currently supported in any browser. permissions.requestall() requests permission to use a given set of apis. this is not currently supported in any browser. permissions.revoke() revokes the permission currently set on a given api. ...
Using the Permissions API - Web APIs
or querying, requesting, and revoking permissions, although currently it only contains permissions.query(); see below. querying permission state in our example, the permissions functionality is handled by one function — handlepermission(). this starts off by querying the permission status using permissions.query(). depending on the value of the state property of the permissionstatus object re
turned when the promise resolves, it reacts differently: "granted" the "enable geolocation" button is hidden, as it isn't needed if geolocation is already active. "prompt" the "enable geolocation" button is hidden, as it isn't needed if the user will be prompted to grant permission for geolocation. the geolocation.getcurrentposition() function is then run, which prompts the user for permission; ...
Permissions API - Web APIs
f the user denied the initial permission request). the permissions api provides the tools to allow developers to implement a better user experience as far as permissions are concerned. the permissions property has been made available on the navigator object, both in the standard browsing context and the worker context (workernavigator — so permission checks are available inside workers), and re
turns a permissions object that provides access to the permissions api functionality. once you have this object you can then perform permission-related tasks, for example querying a permission using the permissions.query() method to re
turn a promise that resolves with the permissionstatus for a specific api. not all apis' permission statuses can be queried using the permissions api. notable apis tha...
PhotoCapabilities.fillLightMode - Web APIs
options may include auto, off, or flash. syntax const lightmodes = photocapabilities.filllightmode value an array of available fill light modes. auto the device's fill light will be used automatically in low light conditions. off no fill light will be used. flash always use the device's fill light. specifications specification status comment mediastream image capturethe definition of 'filllightmode' in that specification. working draft initial definition. ...
PhotoCapabilities.imageHeight - Web APIs
syntax var mediasettingsrange = photocapabilities.imageheight value a mediasettingsrange object. specifications specification status comment mediastream image capturethe definition of 'imageheight' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
imageWidth - Web APIs
syntax var mediasettingsrange = photocapabilities.imagewidth value a mediasettingsrange is an object. specifications specification status comment mediastream image capturethe definition of 'imagewidth' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Plugin - Web APIs
plugin. note: own properties of plugin objects are no longer enumerable in the latest browser versions. properties plugin.description read only a human readable description of the plugin. plugin.filename read only the filename of the plugin file. plugin.name read only the name of the plugin. plugin.version read only the plugin's version number string. methods plugin.item re
turns the mime type of a supported content type, given the index number into a list of supported types. plugin.nameditem re
turns the mime type of a supported item. specifications specification status comment html living standardthe definition of 'plugin' in that specification. living standard initial definition. ...
PointerEvent.getCoalescedEvents() - Web APIs
specifications specification status comment pointer events – level 3the definition of 'getcoalescedevents()' in that specification. editor's draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PointerEvent.height - Web APIs
ointerevent interface represents the height of the pointer's contact geometry, along the y-axis (in css pixels). depending on the source of the pointer device (for example a finger), for a given pointer, each event may produce a different value. if the input hardware cannot report the contact geometry to the browser, the height defaults to 1. syntax var contactheight = pointerevent.height; re
turn value contactheight the height of the event's contact area (in css pixels). example an example of this property is included in the pointerevent.width example. specifications specification status comment pointer events – level 2the definition of 'height' in that specification. recommendation non-stable version. pointer eventsthe definition of 'heig...
PointerEvent.pointerId - Web APIs
the pointerid read-only property of the pointerevent interface is an identifier assigned to a given pointer event. the identifier is unique, being different from the identifiers of all other active pointer events. since the value may be randomly generated, it is not guaranteed to convey any particular meaning. syntax var id = pointerevent.pointerid; re
turn value id the pointer event's unique identifier number. example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired. let id; // let's assume that this is a previously saved pointerid target.addeventlistener('pointerdown', function(event) { // compare previous event's id that was cached // to current event's id and handle accordingly if (id === event.poi...
PointerEvent.pointerType - Web APIs
the supported values are the following strings: "mouse" the event was generated by a mouse device. "pen" the event was generated by a pen or stylus device. "touch" the event was generated by a touch, such as a finger. if the device type cannot be detected by the browser, the value can be an empty string (""). ...
PointerEvent.pressure - Web APIs
for hardware that does not support pressure, such as a mouse, the value is 0.5 when the pointer is active buttons state and 0 otherwise. ...
PointerEvent.tiltX - Web APIs
the tiltx read-only property of the pointerevent interface is the angle (in degrees) between the y-z plane of the pointer and the screen. this property is typically only useful for a pen/stylus pointer type. for an illustration of this property see figure 2 in the specification. syntax var tiltx = pointerevent.tiltx; re
turn value tiltx the angle in degrees between the y-z plane of the pointer (stylus) and the screen. the range of values is -90 to 90, inclusive, where a positive value is a tilt to the right. for devices that do not support this property, the value is 0. example this example illustrates simple accessing of the tiltx and tilty properties. someelement.addeventlistener("pointerdown", function(event) { process_tilt(event.tiltx, event.tilty); }, false); specificatio...
PointerEvent.tiltY - Web APIs
the tilty read-only property of the pointerevent interface is the angle (in degrees) between the x-z plane of the pointer and the screen. this property is typically only useful for a pen/stylus pointer type. for an illustration of this property, see figure 3 in the specification. syntax var tilty = pointerevent.tilty; re
turn value tilty the angle in degrees between the x-z plane of the pointer (stylus) and the screen. the range of values is -90 to 90, inclusive, where a positive value is a tilt towards the user. for devices that do not support this property, the value is 0. example this example illustrates simple accessing of the tiltx and tilty properties. someelement.addeventlistener("pointerdown", function(event) { process_tilt(event.tiltx, event.tilty); }, false); specific...
PointerEvent.twist - Web APIs
the value is in the range 0 to 359, inclusive. for devices that do not report twist, the value is 0. example when a pointerdown event is fired, different functions are called depending on the value of the event's twist property. ...
PointerEvent.width - Web APIs
pointerevent interface represents the width of the pointer's contact geometry along the x-axis, measured in css pixels. depending on the source of the pointer device (such as a finger), for a given pointer, each event may produce a different value. if the input hardware cannot report the contact geometry to the browser, the width defaults to 1. syntax var contactwidth = pointerevent.width; re
turn value contactwidth the width of the event's contact area (in css pixels). example this example illustrates using the pointerevent interface's width and height properties to calculate the contact area. target.addeventlistener("pointerdown", function(ev) { // calculate the contact area var area = ev.width * ev.height; }, false); specifications specification status c...
PointerEvent - Web APIs
clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359. pointerevent.pointertype read only indicates the device type that caused the event (mouse, pen, touch, etc.) pointerevent.isprimary read only indicates if the pointer represents the primary pointer of this pointer type. methods pointerevent.getcoalescedevents() re
turns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event. pointerevent.getpredictedevents() re
turns a sequence of pointerevent instances that the browser predicts will follow the dispatched pointermove event's coalesced events. pointer event types the pointerevent interface has several event types. to determine which event fired, look at the event...
Pinch zoom gestures - Web APIs
nterid) { evcache.splice(i, 1); break; } } } event logging these functions are used to send event activity to the application's window (to support debugging and learning about the event flow). ...
PositionOptions.maximumAge - Web APIs
the positionoptions.maximumage property is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to re
turn. if set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. if set to infinity the device must re
turn a cached position regardless of its age. syntax positionoptions.maximumage = timelength specifications specification status comment geolocation apithe definition of 'positionoptions.maximumage' in that specification. recommendation initial definition ...
PositionOptions.timeout - Web APIs
the positionoptions.timeout property is a positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to re
turn a position. the default value is infinity, meaning that getcurrentposition() won't re
turn until the position is available. syntax positionoptions.timeout = timelength specifications specification status comment geolocation apithe definition of 'positionoptions.timeout' in that specification. recommendation initial definition ...
ProgressEvent() - Web APIs
syntax progressevent = new progressevent(type, {lengthcomputable: abooleanvalue, loaded: anumber, total: anumber}); arguments the progressevent() constructor also inherits arguments from event(). type is a domstring representing the name of the type of the progressevent. it is case-sensitive. lengthcomputable optional is a boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. in other words, it tells if the progress is measurable or not. it defaults to false. ...
PublicKeyCredential - Web APIs
object. it is either of type authenticatorattestationresponse if the publickeycredential was the results of a navigator.credentials.create() call, or of type authenticatorassertionresponse if the publickeycredential was the result of a navigator.credentials.get() call. methods publickeycredential.getclientextensionresults()secure context if any extensions were requested, this method will re
turn the results of processing those extensions. publickeycredential.isuserverifyingplatformauthenticatoravailable()secure context a static method re
turning a promise which resolves to true if an authenticator bound to the platform is capable of verifying the user. with the current state of implementation, this method only resolves to true when windows hello is available on the system. examples c...
PushSubscription.subscriptionId - Web APIs
syntax var subid = pushsubscription.subscriptionid; specifications specification status comment push api working draft initial definition browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PushSubscription.unsubscribe() - Web APIs
the unsubscribe() method of the pushsubscription interface re
turns a promise that resolves to a boolean when the current subscription is successfully unsubscribed. syntax pushsubscription.unsubscribe().then(function(boolean) { ... }); parameters none. re
turns a promise that resolves to a boolean when the current subscription is successfully unsubscribed. example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'unsubscribe()' in that specification...
Push API - Web APIs
pushsubscription provides a subcription's url endpoint, and allows unsubscription from a push service. service worker additions the following additions to the service worker api have been specified in the push api spec to provide an entry point for using push messages. they also monitor and respond to push and subscription change events. serviceworkerregistration.pushmanager read only re
turns a reference to the pushmanager interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. this is the entry point into using push messaging. serviceworkerglobalscope.onpush an event handler fired whenever a push event occurs; that is, whenever a server push message is received. serviceworkerglobalscope.onpushsubscript...
RTCCertificate - Web APIs
the interface of the the webrtc api provides an object represents a certificate that an rtcpeerconnection uses to authenticate. properties rtccertificate.expires read only re
turns the expiration date of the certificate. specifications specification status comment webrtc 1.0: real-time communication between browsers candidate recommendation initial definition. ...
RTCConfiguration.iceTransportPolicy - Web APIs
relay candidates. the agent—or the browser itself—may still perform some form of ip filtering on the incoming candidates for reasons including privacy and security, as well as to simply limit the number of candidates. this is the default. relay the ice agent only considers media relay candidates when evaluating candidates. this includes, for example, those candidates relayed by a stun or
turn server. this can be used to prevent the remote endpoint from receiving the user's ip addresses, which may be important in some security situations. for example, in a video calling application, the app may want to prevent unknown callers from learning the callee's ip addresses until the callee has agreed to receive the call. examples in this example, a new connection is configured to only a...
RTCDTMFSender.insertDTMF() - Web APIs
ptional the amount of time, in milliseconds, that each dtmf tone should last. this value must be between 40 ms and 6000 ms (6 seconds), inclusive. the default is 100 ms. intertonegap optional the length of time, in milliseconds, to wait between tones. the browser will enforce a minimum value of 30 ms (that is, if you specify a lower value, 30 ms will be used instead); the default is 70 ms. re
turn value undefined exceptions invalidstateerror the dtmf tones couldn't be sent because the track has been stopped, or is in a read-only or inactive state. invalidcharactererror one or more of the characters in tones is not valid dtmf. example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rt...
RTCDTMFSender.toneBuffer - Web APIs
to place tones into the buffer, call insertdtmf(). tones are removed from the string as they're played, so only upcoming tones are listed. syntax var tonebuffer = rtcdtmfsender.tonebuffer; value a domstring listing the tones to be played. if the string is empty, there are no tones pending. tone buffer format the tone buffer is a string which can contain any combination of the characters that are permitted by the dtmf standard. dtmf tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad. ...
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
he event. this is always "tonechange". options a dictionary of type rtcdtmftonechangeeventinit, which may contain one or more of the following fields: tone a domstring containing a single dtmf tone character which has just begun to play, or an empty string ("") to indicate that the previous tone has stopped playing. see tone characters for details on what characters are permitted. re
turn value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options. tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad. the letters a-d these characters represent the "a" through "d" keys which are part of the dtmf standard but not included on most telephones. these are not interpreted as digits. lower-case "a"-"d" aut...
RTCDTMFToneChangeEvent.tone - Web APIs
if all queued tones have finished playing (that is, rtcdtmfsender.tonebuffer is empty). syntax var tone = dtmftonechangeevent.tone; example this example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
RTCDTMFToneChangeEvent - Web APIs
hat dtmf tones have started or finished playing. this interface is used by the tonechange event. properties in addition to the properties of event, this interface offers the following: rtcdtmftonechangeevent.tone read only a domstring specifying the tone which has begun playing, or an empty string ("") if the previous tone has finished playing. constructors rtcdtmftonechangeevent() re
turns a new rtcdtmftonechangeevent. it takes two parameters, the first being a domstring representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event. methods supports the methods defined in event. there are no additional methods. examples this snippet is derived loosely from the full, working example you'll find in ...
RTCDataChannel.bufferedAmount - Web APIs
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. ...
RTCDataChannel.id - Web APIs
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true). each rtcpeerconnection can therefore have up to a theoretical maximum of 65,534 data channels on it, although the actual maximum may vary from browser to browser. in early versions of the webrtc specification, this property's name was stream. code that uses that property needs to be updated. ...
RTCDataChannel.label - Web APIs
these labels are not required to be unique. you may use the label as you wish; you could use it to identify all the channels that are being used for the same purpose, by giving them all the same name. or you could give each channel a unique label for tracking purposes. it's entirely up to the design decisions made when building your site or app. a unique id can be found in the id property. a data channel's label is set when the channel is created by calling rtcpeerconnection.createdatachannel(). it cannot be changed after that. ...
RTCDataChannel.maxPacketLifeTime - Web APIs
this limits how long the browser can continue to attempt to transmit and retransmit the message before giving up. syntax var lifetime = adatachannel.maxpacketlifetime; value the number of milliseconds over which the browser may continue to attempt to transmit the message until it either succeeds or gives up. if not set when rtcpeerconnection.createdatachannel() was called to create the data channel, this value is null. ...
RTCDataChannel.maxRetransmits - Web APIs
this can only be set when the rtcdatachannel is created by calling rtcpeerconnection.createdatachannel(), using the maxretransmits field in the specified options. syntax var tries = adatachannel.maxretransmits; value the maximum number of times the browser will try to retransmit a message before giving up, or null if not set when rtcpeerconnection.createdatachannel() was called. the default is null. ...
RTCDataChannel.onerror - Web APIs
rror occurs on the data channel, the function receives as input an errorevent object describing the error which occurred. syntax rtcdatachannel.onerror = function; value a function which the browser will call to handle the error event when it occurs on the data channel. this function receives as its only input an errorevent object describing the event which was received. that event object, in
turn, describes the error that took place. example in the example below, a data channel is established, and an onerror handler is added to it. the error handler passes information about the error to a ui library's alert box function to present an error message to the user. let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.onerror = function(event) { myuilibrary...
RTCDataChannel.protocol - Web APIs
if no protocol was specified when the data channel was created, then this property's value is "" (the empty string). the permitted values of this property are defined by the web site or app using the data channel. the ability for each channel to have a defined subprotocol lets your app, for example, use json objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format. syntax var subprotocol = adatachannel.protocol; value a string identifying the app-defined subprotocol being used for exchanging data on the channel. ...
RTCDataChannel.readyState - Web APIs
syntax var state = adatachannel.readystate; values a string which is one of the values in the rtcdatachannelstate enum, indicating the current state of the underlying data transport. rtcdatachannelstate enum the rtcdatachannelstate enum defines string constants which reflect the current status of the rtcdatachannel's underlying data connection. ...
RTCDataChannel.send() - Web APIs
s implement them, and those that do have various additional restrictions. this will get less complicated over time, but for now, if you have questions, see understanding message size limits in using webrtc data channels. syntax rtcdatachannel.send(data); parameters data the data to transmit across the connection. this may be a usvstring, a blob, an arraybuffer, or an arraybufferview. re
turn value undefined. exceptions invalidstateerror since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its readystate is "connecting"), this error occurs without sending or buffering the data. networkerror the specified data would need to be buffered, and there isn't room for it in the b...
RTCDataChannel.stream - Web APIs
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true). this property has been replaced with the rtcdatachannel.id property. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. ...
RTCDataChannelEvent.channel - Web APIs
syntax var channel = rtcdatachannelevent.channel; value a rtcdatachannel object representing the data channel linking the receiving rtcpeerconnection to its remote peer. example the first line of code in the datachannel event handler shown below takes the channel from the event object and saves it locally for use by the code handling data traffic. ...
RTCError - Web APIs
the rtcerror interface describes an error which has occurred while handling webrtc operations. it's based upon the standard domexception interface that describes general dom errors. constructor rtcerror() creates and re
turns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property. properties in addition to the properties defined by the parent interface, domexception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred. receivedalert read only an unsigned long integer value indicating the fatal dtls error which was received from the network. only valid ...
RTCErrorEvent - Web APIs
the webrtc api's rtcerrorevent interface represents an error sent to a webrtc object. it's based on the standard event interface, but adds rtc-specific information describing the error, as shown below. constructor rtcerrorevent() creates and re
turns a new rtcerrorevent object. properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue). methods no additional methods are provided beyond any found on the parent interface, event. description there are other data types use...
RTCIceCandidate.RTCIceCandidate() - Web APIs
the rtcicecandidate() constructor creates and re
turns a new rtcicecandidate object, which can be configured to represent a single ice candidate. syntax candidate = new rtcicecandidate([candidateinfo]); parameters candidateinfo optional an optional rtcicecandidateinit object providing information about the candidate; if this is provided, the candidate is initialized configured to represent the described candidate. re
turn value a newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary. if candidateinfo is provided, the new rtcicecandidate is initialized as follows: each member of the rtcicecandidateinit object is initialized to the value of the property by the same name from rtcicecandidateinit. this inc...
RTCIceCandidate.relatedPort - Web APIs
ms, so do not rely on them having non-null values. syntax var relport = rtcicecandidate.relatedport; value an unsigned 16-bit value containing the candidate's related port number, if any. for both peer and server reflexive candidates, the related address and port describe the base for that candidate. for relay candidates, the related address and port provide the mapped address selected by the
turn server. for host candidates, relatedport is null, meaning the field is not included in the candidate's a-line. usage notes the related address and port are not used by ice itself, and are only present for diagnostic and quality-of-service purposes. they may in fact be omitted for security reasons, but if present can be a useful tool during debugging. see the example, which shows a bit of this.
RTCIceCandidate.sdpMid - Web APIs
this id uniquely identifies a given stream for the component with which the candidate is associated. this property can be configured by specifying the value of the sdpmid property when constructing the new candidate object using rtcicecandidate(). if you call the constructor with an m-line string instead of an rtcicecandidateinit object, the value of sdpmid is extracted from the specified candidate m-line string. ...
RTCIceCandidate.type - Web APIs
peer. srflx the candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the stun server to represent the candidate's peer anonymously. prflx the candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the stun server to represent the candidate's peer anonymously. relay the candidate is a relay candidate, obtained from a
turn server. the relay candidate's ip address is an address the
turn server uses to forward the media between the two peers. if type is null, that information was missing from the candidate's a-line, which will cause rtcpeerconnection.addicecandidate() to throw an operationerror exception. example in this example, the candidate's type is used to present a modified user interface for host candidat...
RTCIceCandidate.usernameFragment - Web APIs
ction. to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.getreceivers(); receivers.foreach(receiver => { let parameters = receiver.transport.getparameters(); if (parameters.usernamefragment === candidate.usernamefragment) { re
turn; } }); pc.addicecandidate(candidate) .catch(reporterror); } this walks through the list of the rtcrtpreceiver objects being used to receive ice data, and looks to see if the usernamefragment indicated in the candidate matches any of them. if it does, ssnewcandidate() aborts. otherwise, after checking every receiver, it adds the new candidate to the connection. specifications ...
RTCIceCandidatePair.local - Web APIs
the local property of the rtcicecandidatepair dictionary specifies the rtcicecandidate which describes the configuration of the local end of a viable webrtc connection. syntax localcandidate = rtcicecandidatepair.local; value an rtcicecandidate which describes the configuration of the local end of a viable pair of ice candidates. the rtcicecandidatepair is re
turned by the rtcicetransport method getselectedcandidatepair(). example this one-line example simply obtains the current candidate pair and then from that gets the local candidate. var candidatepair = pc.getsenders()[0].transport.transport.getselectedcandidatepair(); var localcandidate = candidatepair.local; the rtcicetransport is found by getting the list of rtcrtpsender objects for the rtcpeerconnection pc. in the first rtcrtp...
RTCIceCandidatePair.remote - Web APIs
the remote property of the rtcicecandidatepair dictionary specifies the rtcicecandidate describing the configuration of the remote end of a viable webrtc connection. syntax remotecandidate = rtcicecandidatepair.remote; value an rtcicecandidate which describes the configuration of the remote end of a viable pair of ice candidates. the rtcicecandidatepair is re
turned by the rtcicetransport method getselectedcandidatepair(). example this one-line example simply obtains the current candidate pair and then from that gets the remote candidate. var candidatepair = pc.getsenders()[0].transport.transport.getselectedcandidatepair(); var remotecandidate = candidatepair.remote; the rtcicetransport is found by getting the list of rtcrtpsender objects for the rtcpeerconnection pc. in the first rtc...
RTCIceCandidatePair - Web APIs
properties local an rtcicecandidate describing the configuration of the local end of the connection. remote the rtcicecandidate describing the configuration of the remote end of the connection. ...
RTCIceCandidatePairStats.requestsReceived - Web APIs
dates. syntax requestsreceived = rtcicecandidatepairstats.requestsreceived; value an integer value which specifies the number of stun connectivity and/or consent requests that have been received to date on the connection described by this pair of ice candidates. because there's no way to tell the difference between requests made to check connectivity and requests made to check consent, the re
turned figure includes both. note: the reported number of requests includes retransmissions. if a request had to be repeated due to network issues, it will be counted multiple times here. this differs from requestssent, which does not include retransmisions. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecand...
RTCIceCandidateStats.address - Web APIs
ipv4 address. if the value is entirely comprised of hexadecimal digits and colon (":") characters, it is interpreted as an ipv6 address. otherwise, the address is presumed to be a fully-qualified domain name, which is resolved first using an aaaa record (assuming ipv6 is available), then using an a record (if no result is found or the device onlu supports ipv4). if multiple ip addresses are re
turned in response to the query, the user agent selects one, which is then used for the duration of ice processing. usage notes the address property was previously known as ip, and only permitted ipv4 and ipv6 addresses to be used. the addition of support for fully-qualified domain names to be used for the address brought about the renaming of the property. specifications specification ...
RTCIceCandidateStats.candidateType - Web APIs
peer. srflx the candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the stun server to represent the candidate's peer anonymously. prflx the candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the stun server to represent the candidate's peer anonymously. relay the candidate is a relay candidate, obtained from a
turn server. the relay candidate's ip address is an address the
turn server uses to forward the media between the two peers. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatestats.candidatetype' in that specification. candidate recommendation initial specification. ...
RTCIceCandidateStats.deleted - Web APIs
object is no longer under consideration. dthe exact meaning varies depending on the type of candidate: local candidate a value of true means the candidate has been deleted as described by rfc 5245: 8.3. host candidate a value of true indicates that the candidate's network resources have been released. this generally mean sthat any associated socket(s) have been closed and released. remote (
turn) candidate a value of true means the candidate's
turn allocation is no longer active. the net result is the same; the candidate is no longer under consideration if this value is true. example in this example, setinterval() is used to set up a function that runs periodically to display the latest statistics for candidates. only candidates which have not been deleted are included in the output...
RTCIceCandidateStats.relayProtocol - Web APIs
the rtcicecandidatestats dictionary's relayprotocol property specifies the protocol being used by a local ice candidate to communicate with the
turn server. the ice protocl being used by the candidate otherwise can be obtained from the protocol property. syntax relayprotocol = rtcicecandidatestats.relayprotocol; value a domstring identifying the protocol being used by the endpoint to communicate with the
turn server. the possible values are: tcp tcp (transport control protocol) is being used to communicate with the
turn server. tls tls (transport layer security) is being used to communicate with the
turn server. udp udp (user datagram protocol) is being used to communicate with the
turn server. note: this property is only present on rtcicecandidatestats objects that represent ...
RTCIceCandidateType - Web APIs
peer. srflx the candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the stun server to represent the candidate's peer anonymously. prflx the candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the stun server to represent the candidate's peer anonymously. relay the candidate is a relay candidate, obtained from a
turn server. the relay candidate's ip address is an address the
turn server uses to forward the media between the two peers. usage notes the rtcicecandidatetype enumeration is used by the type property of rtcicecandidate objects, as well as when reporting statistics on candidates using rtcicecandidatestats.candidatetype. specifications specification status comment webrtc ...
RTCIceGathererState - Web APIs
values "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. the transport won't gather any further candidates unless an ice restart occurs, at which point the gathering process starts over from scratch. ...
RTCIceTransport.gatheringState - Web APIs
syntax gatherstate = rtcicetransport.gatheringstate; value a string from the rtcicegathererstate enumerated type whose value indicates the current state of the ice agent's candidate gathering process: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. ...
RTCIceTransport.getLocalParameters() - Web APIs
the rtcicetransport method getlocalparameters() re
turns an rtciceparameters object which provides information uniquely identifying the local peer for the duration of the ice session. the local peer's parameters are obtained during ice signaling and delivered to the transport when the client calls rtcpeerconnection.setlocaldescription(). syntax parameters = rtcicetransport.getlocalparameters(); parameters none. re
turn value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the local peer for the duration of the ice session. re
turns null if the parameters have not yet been received. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicetransport.
RTCIceTransport.getRemoteCandidates() - Web APIs
the rtcicetransport method getremotecandidates() re
turns an array which contains one rtcicecandidate for each of the candidates that have been received from the remote peer so far during the current ice gathering session. each time your signaling code calls rtcpeerconnection.addicecandidate() to add a received candidate to the ice session, the ice agent places it in the list re
turned by this function. syntax remotecandidates = rtcicetransport.getremotecandidates(); parameters none. re
turn value an array containing one rtcicecandidate object for each candidate that has been received so far from the remote peer during the current ice candidate gathering session. it's important to keep in mind that there's no way to correlate these remote candidates with compatible local candidates. to f...
RTCIceTransport.getRemoteParameters() - Web APIs
the rtcicetransport method getremoteparameters() re
turns an rtciceparameters object which provides information uniquely identifying the remote peer for the duration of the ice session. the remote peer's parameters are received during ice signaling and delivered to the transport when the client calls rtcpeerconnection.setremotedescription(). syntax parameters = rtcicetransport.getremoteparameters(); parameters none. re
turn value an rtciceparameters object indicating the usernamefragment and password which uniquely identify the remote peer for the duration of the ice session. re
turns null if the parameters haven't been received yet. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicetrans...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
the rtcicetransport method getselectedcandidatepair() re
turns an rtcicecandidatepair object containing the current best-choice pair of ice candidates describing the configuration of the endpoints of the transport. syntax candidatepair = rtcicetransport.getselectedcandidatepair(); parameters none. re
turn value a rtcicecandidatepair object describing the configurations of the currently-selected candidate pair's two endpoints. local describes the configuration of the local end of the connection, while remote describes the remote peer's configuration. the re
turn value is null if no pair of candidates has been selected yet. usage notes as the ice agent performs negotiation of a rtcpeerconnection, it gathers and analyzes candidate configurations from each the two peers. as soon as it find...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
t the rtcicetransport will be using for communication with the remote peer. this event will occur at least once, and may occur more than once if the ice agent continues to identify candidate pairs that will work better, more closely match the requested parameters, and so forth. the event handler can determine the current state by calling the transport's getselectedcandidatepair() method, which re
turns a rtcicecandidatepair whose rtcicecandidatepair.local and rtcicecandidatepair.global properties specify rtcicecandidate objects describing the local and remote candidates that are currently being used. example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. var icetra...
RTCIceTransport.state - Web APIs
this differs from the gatheringstate, which only indicates whether or not ice gathering is currently underway. syntax icestate = icetransport.state; value a domstring, whose value is one of those found in the enumerated type rtcicetransportstate, which indicates the stage of ice gathering that's currently underway. its value will be one of the following: "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both. ...
RTCIceTransportState - Web APIs
the transport state indicates which stage of the candidate gathering process is currently underway. values "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both. in this state, checking of candidates to look for those which might be acceptable has not yet begun. ...
RTCIdentityErrorEvent.idp - Web APIs
firefox implements the interface of this property under the following name: rtcpeerconnectionidentityerrorevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityEvent.assertion - Web APIs
firefox implements the interface this property belongs to under the following name: rtcpeerconnectionidentityevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCIdentityEvent - Web APIs
s type is identityresult.. firefox implements this interface under the following name: rtcpeerconnectionidentityevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. properties a rtcidentityevent being an event, this event also implements these properties. rtcidentityevent.assertion read only re
turns the domstring containing a blob being the assertion generated. methods a rtcidentityevent being an event, this event also implements these properties. there is no specific rtcidentityevent method. examples pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
an unsigned integer value which indicates the total number of fec packets which have been recieved from the remote peer during this rtp session. forward error correction uses an exclusive-or method to perform parity checks on the received data. by using the fec parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in
turn helps to reduce lag, or the need to skip damaged frames entirely. note: this counter may also be incremented when fec packets arrive in-band along with media content; this can happen with opus, for example. usage notes it's possible that a subset of the fec packets which have been received were discarded instead of being used. this can happen if the packets covered by the fec packets have al...
RTCOutboundRtpStreamStats - Web APIs
a string which identifies the rtcremoteinboundrtpstreamstats object that provides statistics for the remote peer for this same ssrc. this id is stable across multiple calls to getstats(). retransmittedbytessent the total number of bytes that have been retransmitted for this source as of the time the statistics were sampled. these retransmitted bytes comprise the packets included in the value re
turned by retransmittedpacketssent. retransmittedpacketssent the total number of packets that have needed to be retransmitted for this source as of the time the statistics were sampled. these retransmitted packets are included in the value re
turned by packetssent. senderid the {domxref("rtcstats.id", "id")}} of the rtcaudiosenderstats or rtcvideosenderstats object containing statistics about this ...
RTCPeerConnection.addStream() - Web APIs
gstate is set to closed, an invalidstateerror is raised. if the signalingstate is set to stable, the event negotiationneeded is sent on the rtcpeerconnection to indicate that ice negotiation must be repeated to consider the new stream. syntax rtcpeerconnection.addstream(mediastream); parameters mediastream a mediastream object indicating the stream to add to the webrtc peer connection. re
turn value none. example this simple example adds the audio and video stream coming from the user's camera to the connection. navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.ge...
RTCPeerConnection.close() - Web APIs
the rtcpeerconnection.close() method closes the current peer connection. syntax peerconnection.close(); this method has no parameters, and re
turns nothing. calling this method terminates the rtcpeerconnection's ice agent, ending any ongoing ice processing and any active streams. this also releases any resources in use by the ice agent, including
turn permissions. all rtcrtpsender objects are considered to be stopped once this re
turns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). once this method re
turns, the signaling state as re
turned by rtcpeerconnection.signalingstate is closed. make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, ...
RTCPeerConnection.connectionState - Web APIs
the read-only connectionstate property of the rtcpeerconnection interface indicates the current state of the peer connection by re
turning one of the string values specified by the enum rtcpeerconnectionstate. when this property's value changes, a connectionstatechange event is sent to the rtcpeerconnection instance. syntax var connectionstate = rtcpeerconnection.connectionstate; value the current state of the connection, as a value from the enum rtcpeerconnectionstate. rtcpeerconnectionstate enum the rtcpeerconnectionstate enum defines string constants which describe states in which the rtcpeerconnection may be. these values are re
turned by the connectionstate property. this state essentially represents the aggregate state of all ice transports (which are of type rtcicetransport or rtc...
RTCPeerConnection.createDataChannel() - Web APIs
h sides call createdatachannel with an agreed-upon id. default: false. id optional an 16-bit numeric id for the channel; permitted values are 0-65534. if you don't include this option, the user agent will select an id for you. the options which can be configured using the rtcdatachannelinit dictionary represent the script-settable subset of the properties on the rtcdatachannel interface. re
turn value a new rtcdatachannel object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established. exceptions invalidstateerror the rtcpeerconnection is closed. typeerror this can happen in a couple of situations: the label and/or protocol string is too long; these cannot be longer than 65,...
RTCPeerConnection.generateCertificate() - Web APIs
the generatecertificate() method of the rtcpeerconnection interface creates and stores an x.509 certificate and corresponding private key then re
turns an rtccertificate, providing access to it. syntax var cert = rtcpeerconnection.generatecertificate(keygenalgorithm) parameters keygenalgorithm a domstring identifying the algorithm to use in creating the key. rtcpeerconnection.generatecertificate() is a static method, so it is always called on the rtcpeerconnection interface itself, not an instance thereof. re
turn value a reference to an rtccertificate object. example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { var pc = new rtcpeerconne...
RTCPeerConnection.getConfiguration() - Web APIs
the rtcpeerconnection.getconfiguration() method re
turns an rtcconfiguration object which indicates the current configuration of the rtcpeerconnection on which the method is called. the re
turned configuration is the last configuration applied via setconfiguration(), or if setconfiguration() hasn't been called, the configuration the rtcpeerconnection was constructed with. the configuration includes a list of the ice servers used by the connection, information about transport policies, and identity information. syntax var configuration = rtcpeerconnection.getconfiguration(); parameters this method takes no input parameters. re
turn value an rtcconfiguration object describing the rtcpeerconnection's current configuration. example this example adds a new certificate to an active connecti...
RTCPeerConnection.getDefaultIceServers() - Web APIs
the getdefaulticeservers() method of the rtcpeerconnection interface re
turns an array of objects based on the rtciceserver dictionary, which indicates what, if any, ice servers the browser will use by default if none are provided to the rtcpeerconnection in its rtcconfiguration. however, browsers are not required to provide any default ice servers at all. syntax var defaulticeservers = rtcpeerconnection.getdefaulticeservers(); re
turn value an array of ice servers, specified as objects based on rtciceserver, which the browser will use if none are specified in the configuration of the rtcpeerconnection. if there are no defaults provided by the browser, the re
turned array is empty; this property's value is never null. example var pc = new rtcpeerconnection(); var iceservers = pc.getdefa...
RTCPeerConnection.getIdentityAssertion() - Web APIs
the rtcpeerconnection.getidentityassertion() method initiates the gathering of an identity assertion. this has an effect only if the signalingstate is not "closed". the method re
turns immediately. if the assertion cannot be generated, an idpassertionerror will be sent to the object. it is not expected for the application dealing with the rtcpeerconnection: this is automatically done; an explicit call only allows to anticipate the need. syntax pc.getidentityassertion(); there is neither parameter nor re
turn value for this method. example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future. specifications specification status comment identity for webrtcthe definition of 'rtcpeerco...
RTCPeerConnection.getReceivers() - Web APIs
the rtcpeerconnection.getreceivers() method re
turns an array of rtcrtpreceiver objects, each of which represents one rtp receiver. each rtp receiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection syntax var receivers = rtcpeerconnection.getreceivers(); re
turn value an array of rtcrtpreceiver objects, one for each track on the connection. the array is empty if there are no rtp receivers on the connection. the order of the re
turned rtcrtpreceiver instances is not defined by the specification, and may change from one call to getreceivers() to the next. example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.getreceiver...
RTCPeerConnection.iceGatheringState - Web APIs
the read-only property rtcpeerconnection.icegatheringstate re
turns an enum of type rtcicegatheringstate that describes connection's ice gathering state. this lets you detect, for example, when collection of ice candidates has finished. you can detect when the value of this property changes by watching for an event of type icegatheringstatechange. syntax var state = rtcpeerconnection.icegatheringstate; value the possible values are those of an enum of type rtcicegatheringstate. rtcicegatheringstate enum the rtcicegatheringstate enum defines string constants which reflect the current status of ice gathering, as re
turned using the rtcpeerconnection.icegatheringstate property. you can detect when this value changes by watching for an event of type icegatheringstatechange. cons...
RTCPeerConnection: identityresult event - Web APIs
to an rtcpeerconnection object's onidentityresult event handler to inform it that an assertion has been generated by an associated identity provider (idp) during the process of creating an sdp offer or answer. note: while older versions of the webrtc specification used events to report assertions, this has been deprecated and removed from the specification. instead, the peeridentity property re
turns a promise that resolves with an identity or rejects if an error occurs or if unable to validate the identity. bubbles no cancelable no interface rtcidentityevent event handler property onidentityresult specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of ...
RTCPeerConnection: idpassertionerror event - Web APIs
te an identity assertion. an event handler for this event can be added using the rtcpeerconnection.onidpassertionerror property. bubbles no cancelable no interface rtcidentityerrorevent event handler property onidpassertionerror warning: this event is no longer used; instead, you can detect an assertion error by detecting when the promise re
turned by rtcpeerconnection.peeridentity is rejected. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'idpassertionerror' in that specification. candidate recommendation ...
RTCPeerConnection: idpvalidationerror event - Web APIs
an identity assertion. an event handler for this event can be added using the rtcpeerconnection.onidpvalidationerror property. bubbles no cancelable no interface rtcidentityerrorevent event handler property onidpvalidationerror warning: this event is no longer used; instead, you can detect a validation error by detecting when the promise re
turned by rtcpeerconnection.peeridentity is rejected. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'idpvalidationerror' in that specification. candidate recommendation ...
RTCPeerConnection.onicecandidateerror - Web APIs
d a single parameter: an rtcpeerconnectioniceerrorevent object describing the icecandidateerror event. the event offers properties describing the error to help you handle it appropriately. example pc.onicecandidateerror = function(event) { if (event.errorcode >= 300 && event.errorcode <= 699) { // stun errors are in the range 300-699. see rfc 5389, section 15.6 // for a list of codes.
turn adds a few more error codes; see // rfc 5766, section 15 for details. } else if (event.errorcode >= 700 && event.errorcode <= 799) { // server could not be reached; a specific error number is // provided but these are not yet specified. } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition o...
RTCPeerConnection.onidpassertionerror - Web APIs
er is a property containing the code to execute whent the idpassertionerror event, of type rtcidentityerrorevent, is received by this rtcpeerconnection. such an event is sent when the associated identity provider (idp) encounters an error while generating an identity assertion. this event handler is deprecated. you should instead detect idp assertion errors by handling rejection of the promise re
turned by rtcpeerconnection.peeridentity. syntax peerconnection.onidpassertionerror = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentityerrorevent. example pc.onidpassertio...
RTCPeerConnection.onidpvalidationerror - Web APIs
ent handler is a property containing the code to execute whent the idpvalidationerror event, of type rtcidentityerrorevent, is received by this rtcpeerconnection. such an event is sent when the associated identity provider (idp) encounters an error while validating an identity assertion. this event handler is obsolete. you should instead detect idp validation errors by watching for the promise re
turned by rtcpeerconnection.peeridentity to be rejected. syntax peerconnection.onidpvalidationerror = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentityerrorevent. example ...
RTCPeerConnection.onpeeridentity - Web APIs
the rtcpeerconnection.onpeeridentity event handler is a property containing the code to execute whent the peeridentity event, of type event, is received by this rtcpeerconnection. such an event is sent when an identity assertion, received from a peer, has been successfully validated. this event handler is obsolete. to detect successful validation of the identity, wait for the promise re
turned by peeridentity to resolve successfully with the peer's identity. syntax peerconnection.onpeeridentity = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type event. example pc.onpeeriden...
RTCPeerConnection: peeridentity event - Web APIs
via the rtcpeerconnection.onpeeridentity property. bubbles no cancelable no interface event event handler property onpeeridentity important: this event and its event handler have been removed from the specification and are no longer available. instead of using this event to detect when an identity is available, simply wait for the promise re
turned by rtcpeerconnection.peeridentity to be resolved. once resolved, its value is the new identity. examples for the correct way to detect a new peer identity, see rtcpeerconnection.peeridentity. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'peeridentity' in that specification. candidate recommendat...
RTCPeerConnection.pendingLocalDescription - Web APIs
the read-only property rtcpeerconnection.pendinglocaldescription re
turns an rtcsessiondescription object describing a pending configuration change for the local end of the connection. this does not describe the connection as it currently stands, but as it may exist in the near future. use rtcpeerconnection.currentlocaldescription or rtcpeerconnection.localdescription to get the current state of the endpoint. for details on the difference, see pending and current descriptions in webrtc connectivity. syntax sessiondescription = rtcpeerconnection.pendinglocaldescription; re
turn value if a local description change is in progress, this is an rtcsessiondescription describing the proposed configuration. otherwise, this re
turns null. example this example looks at the pendinglocaldescription to ...
RTCPeerConnection.pendingRemoteDescription - Web APIs
the read-only property rtcpeerconnection.pendingremotedescription re
turns an rtcsessiondescription object describing a pending configuration change for the remote end of the connection. this does not describe the connection as it currently stands, but as it may exist in the near future. use rtcpeerconnection.currentremotedescription or rtcpeerconnection.remotedescription to get the current session description for the remote endpoint. for details on the difference, see pending and current descriptions in webrtc connectivity. syntax sessiondescription = rtcpeerconnection.pendingremotedescription; re
turn value if a remote description change is in progress, this is an rtcsessiondescription describing the proposed configuration. otherwise, this re
turns null. example this example looks at the...
RTCPeerConnection.remoteDescription - Web APIs
the read-only property rtcpeerconnection.remotedescription re
turns a rtcsessiondescription describing the session (which includes configuration and media information) for the remote end of the connection. if this hasn't been set yet, this is null. the re
turned value typically reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling rtcpeerconnection.setremotedescription() in response. syntax var sessiondescription = peerconnection.remotedescription; on a more fundamental level, the re
turned value is the value of rtcpeerconnection.pendingremotedescription if that property isn't null; otherwise, the value of rtcpeerconnection.currentremotedescription is re
turned. see pending and current...
RTCRtpParameters - Web APIs
changed once initially set. rtcp an rtcrtcpparameters object providing the configuration parameters used for rtcp on the sender or receiver. this parameter cannot be changed once initially set. examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpsender or rtcrtpreceiver. function getrtpcname(rtpobject) { let parameters = rtpobject.getparameters(); re
turn parameters.rtcp.cname; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiveparameters' in that specification. candidate recommendation initial definition. ...
RTCRtpReceiver.getStats() - Web APIs
the rtcrtpreceiver method getstats() asynchronously requests an rtcstatsreport object which provides statistics about incoming traffic on the owning rtcpeerconnection, re
turning a promise whose fulfillment handler will be called once the results are available. syntax var promise = rtcrtpreceiver.getstats(); re
turn 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 re
turned statistics include those from all streams which are coming in through the rtcrtpreceiver, as well as any of their dependencies. example this simple example obtains the statistics for an rtcrtpreceiver and updates an element's innertext to display the number of packe...
RTCRtpReceiver.track - Web APIs
syntax var mediastreamtrack = rtcrtpreceiver.track value a mediastreamtrack instance. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'track' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
RTCRtpSendParameters.encodings - Web APIs
or octet) specifying the codec to use for sending the stream; the value matches one from the owning rtcrtpparameters object's codecs parameter. this value can only be set when creating the transceiver; after that, this value is read only. dtx only used for an rtcrtpsender whose kind is audio, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is
turned off or the microphone muted automatically in the absence of voice activity). the value is taken from the enumerated string type rtcdtxstatus. maxbitrate an unsigned long integer indicating the maximum number of bits per second to allow for this encoding. other parameters may further constrain the bit rate, such as the value of maxframerate or transport or physical network limitations. maxfra...
RTCRtpSender.dtmf - Web APIs
syntax var dtmfsender = rtcrtpsender.dtmf; value an rtcdtmfsender which can be used to send dtmf over the rtp session, or null if the track being carried by the rtp session or the rtcpeerconnection as a whole doesn't support dtmf. ...
RTCRtpSender.getStats() - Web APIs
the rtcrtpsender method getstats() asynchronously requests an rtcstatsreport object which provides statistics about outgoing traffic on the rtcpeerconnection which owns the sender, re
turning a promise which is fulfilled when the results are available. syntax var promise = rtcrtpsender.getstats(); re
turn 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 re
turned 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. example this simple example obtains the statistics for an rtcrtpsender and updates an element's innertext to d...
RTCRtpSender.setParameters() - Web APIs
be used to encode the track's media. priority a string from the rtcprioritytype enumerated type which indicates the encoding's priority. the default value is low. transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameters(). re
turn value a promise that resolves when the rtcrtpsender.track property is updated with the given parameters. exceptions if an error occurs, the re
turned promise is rejected with the appropriate exception from the list below. invalidmodificationerror one of the following problems was detected: the number of encodings specified in the parameters object's encodings property does not match the...
RTCRtpSender.setStreams() - Web APIs
y of mediastream objects. syntax rtcrtpsender.setstreams(mediastream); rtcrtpsender.setstreams([mediastream...]); parameters mediastream or [mediastream...] optional an mediastream object—or an array of multiple mediastream objects—identifying the streams to which the rtcrtpsender's track belongs. if this parameter isn't specified, no new streams will be associated with the track. re
turn value none. exceptions invalidstateerror the sender's connection is closed. description setstreams() is purely additive. it doesn't remove the track from any streams; it simply adds it to new ones. if you specify streams to which the track already belongs, that stream is unaffected. once the track has been added to all of the streams, renegotiation of the connection will be triggered by...
RTCRtpSender.track - Web APIs
syntax var mediastreamtrack = rtcrtpsender.track value a mediastreamtrack object representing the media associated with the rtcrtpsender. if no track is associated with the sender, this value is null, in which case the sender transmits nothing. ...
RTCRtpStreamStats - Web APIs
while the dictionary has a base set of properties that are present in each of these cases, there are also additional properties added depending on which interface the method is called on. rtcrtpstreamstats is the base class for all rtp-related statistics reports. it's based on rtcstats and adds the following additional fields. note: this interface was called rtcrtpstreamstats until a specification update in the spring of 2017. check the browser compatibility table to know if and when the name change was implemented in specific browsers. ...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
cs supported by webrtc—and each codec's positive and negative characteristics—can be found in codecs used by webrtc. syntax rtcrtptransceiver.setcodecpreferences(codecs) parameters codecs an array of rtcrtpcodeccapability objects, in order of preference, each providing the parameters for one of the transceiver's supported codecs. if codecs is empty, the codec configurations are all re
turned to the user agent's defaults. note: any codecs not included in codecs will not be considered during the process of negotiating a connection. this lets you prevent the use of codecs you don't wish to use. re
turn value undefined exceptions invalidaccesserror the codecs list includes one or more codecs which are not supported by the transceiver. usage notes getting a list of support...
RTCRtpTransceiver.stop() - Web APIs
the stop() method in the rtcrtptransceiver interface permanently stops the transceiver by stopping both the associated rtcrtpsender and rtcrtpreceiver. note: until recently, the stopped property was provided to re
turn true if the connection is stopped. that property has been deprecated and will be removed at some point. instead, check the value of currentdirection. if it's stopped, the transceiver has been stopped. this method does nothing if the transceiver is already stopped. syntax rtcrtptransceiver.stop() paramters none. re
turn value undefined exceptions invalidstateerror the rtcpeerconnection of which the transceiver is a member is closed. usage notes when you call stop() on a transceiver, the sender immediately stops sending media and each of its rtp streams are closed...
RTCSessionDescription - Web APIs
ion object describes a provisional answer; that is, a response to a previous offer that is not the final answer. it is usually employed by legacy hardware. rollback this special type with an empty session description is used to roll back to the previous stable state. methods the rtcsessiondescription doesn't inherit any methods. rtcsessiondescription() this constructor re
turns a new rtcsessiondescription. the parameter is a rtcsessiondescriptioninit dictionary containing the values to assign the two properties. rtcsessiondescription.tojson() re
turns a json description of the object. the values of both properties, type and sdp, are contained in the generated json. example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var me...
RTCSessionDescriptionCallback - Web APIs
d avoid using it (and the callback-based forms of createoffer() and createanswer() that make use of it). syntax rtcsessiondescriptioncallback(description); parameters description an rtcsessiondescriptioninit (or rtcsessiondescription) object describing the session being offered or being accepted. this object contains the type and sdp properties which are part of rtcsessiondescription. re
turn value the callback doesn't need to re
turn anything, so the re
turn value is undefined. example var pc = new rtcpeerconnection(); var descriptioncallback = function(offer) { pc.setlocaldescription(offer); } pc.createoffer(descriptioncallback); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsession...
RTCStatsReport - Web APIs
crtpsender.getstats() methods. this statistics report contains a mapping of statistic category string names to objects containing the corresponding statistics data. calling getstats() on an rtcpeerconnection lets you specify whether you wish to obtain statistics for outbound, inbound, or all streams on the connection. the rtcrtpreceiver and rtcrtpsender versions of getstats() specifically only re
turn statistics available to the incoming or outgoing stream on which you call them. the statistics objects for each category of statistic information, there is a dictionary whose properties provide the relevant information. properties common to all statistic categories all webrtc statistics objects are fundamentally based on the rtcstats dictionary, which provides the most fundamental information...
Range.setEnd() - Web APIs
above (higher in the document) than the start point will result in a collapsed range with the start and end points both set to the specified end position. syntax range.setend(endnode, endoffset); parameters endnode the node inside which the range should end. endoffset an integer greater than or equal to zero representing the offset for the end of the range from the start of endnode. re
turn value undefined. exceptions exceptions are thrown as domexception objects of the following types: invalidnodetypeerror the node specified by endnode is a doctype node; range endpoints cannot be located inside a doctype node. indexsizeerror the value specified by endoffset is either greater than or equal to the length of the node or is less than zero. usage notes if the endnode is a no...
Range.startContainer - Web APIs
to change the start position of a node, use one of the range.setstart() methods. syntax startrangenode = range.startcontainer; example range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); startrangenode = range.startcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.startcontainer' in that specification. ...
Range.startOffset - Web APIs
if the startcontainer is a node of type text, comment, or cdatasection, then the offset is the number of characters from the start of the startcontainer to the boundary point of the range. for other node types, the startoffset is the number of child nodes between the start of the startcontainer and the boundary point of the range. to change the startoffset of a range, use the range.setstart method. ...
Range.toString() - Web APIs
alerting the contents of a range makes an implicit tostring() call, so comparing range and text through an alert dialog is ineffective. syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>. ...
ReadableByteStreamController.close() - Web APIs
the close() method of the readablebytestreamcontroller interface closes the associated stream. note: readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. syntax readablebytestreamcontroller.close(); parameters none. re
turn value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'close()' in that specification. living standard initial definition. ...
ReadableByteStreamController.enqueue() - Web APIs
the enqueue() method of the readablebytestreamcontroller interface enqueues a given chunk in the associated stream. syntax readablebytestreamcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. re
turn value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'enqueue()' in that specification. living standard initial definition. ...
ReadableByteStreamController.error() - Web APIs
the error() method of the readablebytestreamcontroller interface causes any future interactions with the associated stream to error. syntax readablebytestreamcontroller.error(e); parameters e the error you want future interactions to fail with. re
turn value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'error()' in that specification. living standard initial definition. ...
ReadableByteStreamController - Web APIs
the readablebytestreamcontroller interface of the streams api represents a controller allowing control of a readablestream's state and internal queue. byte stream controllers are for byte streams. constructor none. readablebytestreamcontroller instances are created automatically during readablestream construction. properties readablebytestreamcontroller.byobrequest read only re
turns the current byob pull request. readablebytestreamcontroller.desiredsize read only re
turns the desired size required to fill the stream's internal queue. methods readablebytestreamcontroller.close() closes the associated stream. readablebytestreamcontroller.enqueue() enqueues a given chunk in the associated stream. readablebytestreamcontroller.error() causes any future interactions with th...
ReadableStream.locked - Web APIs
the locked read-only property of the readablestream interface re
turns whether or not the readable stream is locked to a reader. syntax var locked = readablestream.locked; value a boolean indicating whether or not the readable stream is locked. examples const stream = new readablestream({ ... }); const reader = stream.getreader(); stream.locked // should re
turn true, as the stream has been locked to a reader specifications specification status comment streamsthe definition of 'locked' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.cancel() - Web APIs
consumer. the supplied reason parameter will be given to the underlying source, which may or may not use it. note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreambyobreader.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. re
turn value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreambyobreader, or the stream has no owner. examples tbd. specifications specification status comment streamsthe definition of 'cancel()' in that specification. living standard initial definition. ...
ReadableStreamBYOBReader.read() - Web APIs
the different possibilities are as follows: if a chunk is available, the promise will be fulfilled with an object of the form { value: thechunk, done: false }. if the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. if the stream becomes errored, the promise will be rejected with the relevant error. ...
ReadableStreamBYOBReader.releaseLock() - Web APIs
estreambyobreader interface releases the reader's lock on the stream. after the lock is released, the reader is no longer active. if the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise re
turned by the reader’s readablestreambyobreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreambyobreader.releaselock(); parameters none. re
turn value undefined. exceptions typeerror the source object is not a readablestreambyobreader, or a read request is pending. examples tbd. specifications specification status com...
ResizeObserverEntry.target - Web APIs
syntax var element = resizeobserverentry.target; var svgelement = resizeobserverentry.target; value an element or svgelement representing the element being observed. examples the following snippet is taken from the resize-observer-border-radius.html (see source) example. this example includes a green box, sized as a percentage of the viewport size. when the viewport size is changed, the box's rounded corners change in proportion to the size of the box. ...
Response.headers - Web APIs
act a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response headers value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // re
turns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification. living standard initial definition ...
Response.ok - Web APIs
etch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note: at the top of the fetch() block we log the response ok value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // re
turns true if the response re
turned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification. living standard initial definition ...
Response.status - Web APIs
tract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // re
turns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification. living standard initial definition ...
Response.statusText - Web APIs
blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response statustext value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.statustext); // re
turns "ok" if the response re
turned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'statustext' in that specification. living standard initial definition ...
Response.type - Web APIs
etch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response type to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // re
turns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification. living standard initial definition ...
Response.url - Web APIs
fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // re
turns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification. living standard initial definition ...
Response.useFinalURL - Web APIs
the usefinalurl property of the response interface contains a boolean stating whether this is the final url of the response. this property applies only to serviceworkers. in other contexts it will re
turn undefined. syntax var isfinalurl = response.usefinalurl; value a boolean indicating whether or not the url is final rather than a redirect. example consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: onfetch = (e) => { e.respondwith(fetch('/page2').then((r) => { r.usefinalurl = true; re
turn r; }) } the output will be /page2 and not /test in index.html, since setting the usefinalurl means that the response's url is not set to request's url. ...
SVGAElement.target - Web APIs
this property is used when there are multiple possible targets for the ending resource, like when the parent document is a mlti-frame html or xhtml document. syntax mylink.target = 'value'; value an svganimatedstring indicating the ending resource target that opens the document when the link is activated. sample values can be found here example the code is taken from the "svgaelement example code" ... var linkref = document.queryselector('a'); linkref.target ='_blank'; ... ...
SVGAltGlyphElement.glyphRef - Web APIs
the svgaltglyphelement.glyphref property is a domstring representing a glyph identifier. it has the same meaning as the ‘glyphref’ property on the svgglyphrefelement interface of the <glyphref> element. syntax string = myglyph.glyphref; myglyph.glyphref = string; value the re
turn value is a glyph identifier, the value of which depends on the format of the given font. example myglyph.glypref = "#glyphid"; specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'glyphref' in that specification. recommendation ...
targetElement - Web APIs
the svganimationelement.targetelement property refers to the element which is being animated. if no target element is being animated (for example, because the href attribute specifies an unknown element), the value re
turned is null. syntax var targetelement = someelement.targetelement; specifications specification status comment svg animations level 2the definition of 'svganimationelement.targetelement' in that specification. editor's draft added null as re
turn value in case that no target element is being animated. scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimationelement.targetelement' in that specification. recommendation initial definition ...
SVGDocument - Web APIs
properties name type description domain domstring the domain name of the server that served the document, or a null string if the server cannot be identified by a domain name. referrer domstring re
turns the uri of the page that linked to this page. the value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark). rootelement svgsvgelement the root "svg" in the document hierarchy. title domstring the title of a document as specified by ...
SVGGeometryElement.isPointInFill() - Web APIs
ules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill. the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinfill(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordiante system of the element. re
turn value a boolean indicating whether the given point is within the fill or not. example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> javas...
SVGGeometryElement.isPointInStroke() - Web APIs
apply; the value of the pointer-events property on the element determines whether a point is considered to be within the stroke. the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinstroke(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordinate system of the element. re
turn value a boolean indicating whether the given point is within the stroke or not. example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle c...
SVGGeometryElement - Web APIs
nts property on the element determines whether a point is considered to be within the fill. svggeometryelement.ispointinstroke() determines whether a given point is within the stroke shape of an element. normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the stroke. svggeometryelement.gettotallength() re
turns the user agent's computed value for the total length of the path in user units. svggeometryelement.getpointatlength() re
turns the point at a given distance along the path. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement' in that specification. candidate recommendation initial definition ...
getBBox() - Web APIs
the svggraphicselement.getbbox() allows us to determine the coordinates of the smallest rectangle in which the object fits. the coordinates re
turned are with respect to the current svg space (after the application of all geometry attributes on all the elements contained in the target element). note: getbbox() must re
turn the actual bounding box at the time the method was called—even in case the element has not yet been rendered. it also does not account for any transformation applied to the element or its parents. getbbox re
turns different values than getboundingclientrect(), as the latter re
turns value relative to the viewport syntax let bboxrect = object.getbbox(); re
turn value the re
turned value is a svgrect object, which defines the bounding box. this value is irrespective of ...
SVGImageElement.preserveAspectRatio - Web APIs
syntax var svganimatedpreerveaspectratio = svgimageelement.preserveaspectratio; value an svganimatedpreserveaspectratio. specifications specification status comment scalable vector graphics (svg) 2the definition of 'preserveaspectratio' in that specification. ...
SVGLength - Web APIs
tomatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. methods name & arguments re
turn description newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_lengthtype_unknown or not a valid unit type c...
SVGPathElement.getPointAtLength() - Web APIs
the svgpathelement.getpointatlength() method re
turns the point at a given distance along the path. note: in svg 2 this property was moved to the svggeometryelement interface, from which the svgpathelement inherits it. syntax svgpoint someelement.getpointatlength(float distance); parameters distance a float referring to the distance along the path. re
turn value an svgpoint indicating the point at a given distance along the path. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgpathelement.gettotallength()' in that specification. recommendation initial definition ...
SVGStylable - Web APIs
readonly cssstyledeclaration style normative document svg 1.1 (2nd edition) properties name type description classname svganimatedstring corresponds to attribute class on the given element. style cssstyledeclaration corresponds to attribute style on the given element. methods name & arguments re
turn description getpresentationattribute(in domstring name) cssvalue re
turns the base (i.e., static) value of a given presentation attribute as an object of type cssvalue. the re
turned object is live; changes to the objects represent immediate changes to the objects to which the cssvalue is attached. browser compatibility the compatibility table on this page is generated...
SVGTests - Web APIs
nly an svgstringlist corresponding to the requiredfeatures attribute of the given element. svgtests.requiredextensions read only an svgstringlist corresponding to the requiredextensions attribute of the given element. svgtests.systemlanguage read only an svgstringlist corresponding to the systemlanguage attribute of the given element. methods svgtests.hasextension() read only re
turns true if the browser supports the given extension, specified by a uri. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgtests' in that specification. candidate recommendation removed requiredfeatures property and hasextension() method. scalable vector graphics (svg) 1.1 (second edition)the definition of 'sv...
SVGTransform - Web APIs
f=0). for svg_transform_skewx and svg_transform_skewy, a, b, c and d represent the matrix which will result in the given skew (e=0 and f=0). for svg_transform_rotate, a, b, c, d, e and f together represent the matrix which will result in the given rotation. when the rotation is around the center point (0, 0), e and f will be zero. methods name & arguments re
turn description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation. note that the values from the parameter matrix are copied. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object its...
SVGURIReference - Web APIs
t-anchor="middle" alignment-baseline="middle">svgurireference</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties svgurireference.href read only an svganimatedstring that represents the value of the href attribute, and, on elements that are defined to support it, the deprecated xlink:href attribute. on getting href, an svganimatedstring object is re
turned that reflects the href attribute, and if the element is defined to support the deprecated xlink:href attribute, additionally reflects that deprecated attribute. methods this interface does not provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgurireference' in that specification. ...
SVGUseElement - Web APIs
h corresponding to the height attribute of the given element. svguseelement.instanceroot read only an svgelement corresponding to the instance root of the given element, which is a direct child of the elements shadow root. if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute re
turns null. svguseelement.animatedinstanceroot read only an svgelement corresponding to the instance root of the given element, which is a direct child of the elements shadow root. if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute re
turns null. methods this interface doesn't ...
Screen Capture API - Web APIs
ely simple to use. its sole method is mediadevices.getdisplaymedia(), whose job is to ask the user to select a screen or portion of a screen to capture in the form of a mediastream. to start capturing video from the screen, you call getdisplaymedia() on the instance of media navigator.mediadevices: capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); the promise re
turned by getdisplaymedia() resolves to a mediastream which streams the captured media. see the article using the screen capture api for a more in-depth look at how to use the api to capture screen contents as a stream. additions to existing interfaces the screen capture api doesn't have any interfaces of its own; instead, it adds one method to the existing mediadevices interface. mediadevices int...
ScriptProcessorNode.bufferSize - Web APIs
its value can be a power of 2 value in the range 256–16384. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer. ...
ScriptProcessorNode - Web APIs
mmended, the browser will pick one that its heuristic deems appropriate. number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" properties inherits properties from its parent, audionode. scriptprocessornode.buffersize read only re
turns an integer representing both the input and output buffer size. its value can be a power of 2 value in the range 256–16384. methods no specific methods; inherits methods from its parent, audionode. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: audioprocess fired when an input buffer of a scriptpro...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
lt value is "". sample: the sample of the securitypolicyviolationevent. if not included, the default value is "". sourcefile: the sourcefile of the securitypolicyviolationevent. if not included, the default value is "". statuscode: the statuscode of the securitypolicyviolationevent (required). violateddirective: the violateddirective of the securitypolicyviolationevent (required). re
turn value a securitypolicyviolationevent object instance. example let spvevt = new securitypolicyviolationevent('foo', { ... }); specifications specification status comment content security policy level 3the definition of 'securitypolicyviolationevent' in that specification. working draft initial definition ...
Selection.anchorNode - Web APIs
a user may make a selection from left to right (in document order) or right to left (reverse of document order). the anchor is where the user began the selection. this can be visualized by holding the shift key and pressing the arrow keys on your keyboard. the selection's anchor does not move, but the selection's focus, the other end of the selection, does move. ...
Selection.anchorOffset - Web APIs
the selection.anchoroffset read-only property re
turns the number of characters that the selection's anchor is offset within the selection.anchornode. this number is zero-based. if the selection begins with the first character in the selection.anchornode, 0 is re
turned. syntax number = sel.anchoroffset specifications specification status comment selection apithe definition of 'selection.anchoroffset' in that specification. working draft current ...
Selection.focusNode - Web APIs
a user may make a selection from left to right (in document order) or right to left (reverse of document order). the focus is where the user ended the selection. this can be visualized by holding the shift key and pressing the arrow keys on your keyboard to modify the current selection. the selection's focus moves, but the selection's anchor, the other end of the selection, does not move. ...
Selection.focusOffset - Web APIs
the selection.focusoffset read-only property re
turns the number of characters that the selection's focus is offset within the selection.focusnode. this number is zero-based. if the selection ends with the first character in the selection.focusnode, 0 is re
turned. syntax offset = sel.focusoffset specifications specification status comment selection apithe definition of 'selection.focusoffset' in that specification. working draft current ...
Selection.getRangeAt() - Web APIs
the selection.getrangeat() method re
turns a range object representing one of the ranges currently selected. syntax range = sel.getrangeat(index) parameters index the zero-based index of the range to re
turn. a negative number or a number greater than or equal to selection.rangecount will result in an error. re
turn value the specified range object. example let ranges = []; sel = window.getselection(); for(let i = 0; i < sel.rangecount; i++) { ranges[i] = sel.getrangeat(i); } /* each item in the ranges array is now * a range object representing one of the * ranges in the current selection */ specifications specification status comment selection apithe definition of 'selection: getrangeat()' in that specification. working draft current ...
Selection.isCollapsed - Web APIs
the selection.iscollapsed read-only property re
turns a boolean which indicates whether or not there is currently any text selected. no text is selected when the selection's start and end points are at the same position in the content. keep in mind that a collapsed selection may still have one (or more, in gecko) ranges, so selection.rangecount may not be zero. in that scenario, calling a selection object's getrangeat() method may re
turn a range object which is collapsed. syntax bool = sel.iscollapsed specifications specification status comment selection apithe definition of 'selection.iscollapsed' in that specification. working draft current ...
Selection.rangeCount - Web APIs
before the user has clicked a freshly loaded page, the rangecount is 0. after the user clicks on the page, rangecount is 1, even if no selection is visible. a user can normally only select one range at a time, so the rangecount will usually be 1. scripting can be used to make the selection contain more than one range. gecko browsers allow multiple selections across table cells. firefox allows to select multiple ranges in the document by using ctrl+click (unless the click within an element with display: table-cell). syntax value = sel.rangecount example the following example will show the rangecount every second. ...
Selection.setBaseAndExtent() - Web APIs
d node is included. and so on. note: if the focus position appears before the anchor position in the document, the direction of the selection is reversed — the caret is placed at the beginning of the text rather the end, which matters for any keyboard command that might follow. for example, shift + ➡︎ would cause the selection to narrow from the beginning rather than grow at the end. re
turn value void. exceptions if anchoroffset is larger than the number of child nodes inside anchornode, or if focusoffset is larger than the number of child nodes inside focusnode, an indexsizeerror exception is thrown. examples in this example, we have two paragraphs containing spans, each one containing a single word. the first one is set as the anchornode and the second is set as the focusnode...
Selection.toString() - Web APIs
in javascript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getselection()) // what is called alert(window.getselection().tostring()) // what is actually being effectively called. specifications specification status comment selection apithe definition of 'selection: tostring()' in that specification. ...
Selection.type - Web APIs
the type read-only property of the selection interface re
turns a domstring describing the type of the current selection. syntax value = sel.type value a domstring describing the type of the current selection. possible values are: none: no selection has currently been made. caret: the selection is collapsed (i.e. the caret is placed on some text, but no range has been selected). range: a range has been selected. example in this example, the event handler will fire each time a new selection is made. console.log(selection.type) will re
turn caret or range depending on whether the caret is placed at a single point in the text, or a range has been selected. var selection; document.onselectionchange = function() { console.log('new selection made'); selection = document.g...
ShadowRoot.host - Web APIs
the host read-only property of the shadowroot re
turns a reference to the dom element the shadowroot is attached to. syntax const someelement = shadowroot.host value a dom element. examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; ... // re
turn the original host element some time later let hostelem = shadow.host; specifications specification status comment domthe definition of 'shadowroot.host' in that specification. living standard ...
ShadowRoot.mode - Web APIs
tation internals of, for example, the <video> element are inaccessible and unchangeable from javascript. syntax var mode = shadowroot.mode value a value defined in the shadowrootmode enum — either open or closed. examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; // another way to check whether the shadow root is open; it will re
turn null if not if(shadow) { // if it is open, close it to stop people stealing our secrets! shadow.mode = 'closed'; } specifications specification status comment domthe definition of 'shadowroot.mode' in that specification. living standard ...
SharedWorker() - Web APIs
credentials: a domstring specifying the type of credentials to use for the worker. the value can be omit, same-origin, or include. if not specified, or if type is classic, the default used is omit (no credentials required). name: a domstring specifying an identifying name for the sharedworkerglobalscope representing the scope of the worker, which is mainly useful for debugging purposes. re
turn value the created worker. exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following cod...
SharedWorker.port - Web APIs
syntax myworker.port; value a messageport object. example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. ...
SharedWorker - Web APIs
ol, host and port). constructors sharedworker() creates a shared web worker that executes the script at the specified url. properties inherits properties from its parent, eventtarget, and implements properties from abstractworker. abstractworker.onerror is an eventlistener that is called whenever an errorevent of type error bubbles through the worker. sharedworker.port read only re
turns a messageport object used to communicate with and control the shared worker. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to pe...
SharedWorkerGlobalScope.applicationCache - Web APIs
important: application cache is deprecated as of firefox 44, and is no longer available in insecure contexts from firefox 60 onwards (bug 1354175, currently nightly/beta only). don't use it to make offline websites — consider using service workers instead. the applicationcache read-only property of the sharedworkerglobalscope interface re
turns the applicationcache object for the worker (see using the application cache). syntax var nameobj = self.applicationcache; value an applicationcache. example if a shared worker has an appcache associated with it, you can re
turn a reference to the cache using self.applicationcache from inside the shared worker. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the da...
SharedWorkerGlobalScope.name - Web APIs
the name read-only property of the sharedworkerglobalscope interface re
turns the name that the sharedworker was (optionally) given when it was created. this is the name that the sharedworker() constructor can pass to get a reference to the sharedworkerglobalscope. syntax var nameobj = self.name; value a domstring. example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", re
turnable by running self.name from inside the shared worker. specifications specification status comment html living standardthe definition of 'name' in that specification. living standard ...
Slottable: assignedSlot - Web APIs
syntax var slotelement = elementinstance.assignedslot value an htmlslotelement instance, or null if the element is not assigned to a slot, or if the associated shadow root was attached with its mode set to closed (see element.attachshadow for further details). examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text. ...
Slottable - Web APIs
methods none. specifications specification status comment domthe definition of 'slottable' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
SourceBuffer.abort() - Web APIs
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. ...
SourceBuffer.appendBuffer() - Web APIs
the appendbuffer() method of the sourcebuffer interface appends media segment data from an arraybuffer or arraybufferview object to the sourcebuffer. syntax sourcebuffer.appendbuffer(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. re
turn value undefined. exceptions none. example tbd. specifications specification status comment media source extensionsthe definition of 'appendbuffer()' in that specification. recommendation initial definition. ...
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 re
turns 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. re
turn 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...
Storage.removeItem() - Web APIs
a key name, will remove that key from the given storage object if it exists. the storage interface of the web storage api provides access to a particular domain's session or local storage. if there is no item associated with the given key, this method will do nothing. syntax storage.removeitem(keyname); parameters keyname a domstring containing the name of the key you want to remove. re
turn value undefined. example the following function creates three data items inside local storage, then removes the image data item. function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'mycat.png'); localstorage.removeitem('image'); } we can do the same for the session storage. function populatest...
Storage.setItem() - Web APIs
thod of the storage interface, when passed a key name and value, will add that key to the given storage object, or update that key's value if it already exists. syntax storage.setitem(keyname, keyvalue); parameters keyname a domstring containing the name of the key you want to create/update. keyvalue a domstring containing the value you want to give the key you are creating/updating. re
turn value undefined. exceptions setitem() may throw an exception if the storage is full. particularly, in mobile safari (since ios 5) it always throws when the user enters private mode. (safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) hence developers should make sure to always catch possible exceptions f...
Storage - Web APIs
terface of the web storage api provides access to a particular domain's session or local storage. it allows, for example, the addition, modification, or deletion of stored data items. to manipulate, for instance, the session storage for a domain, a call to window.sessionstorage is made; whereas for local storage the call is made to window.localstorage. properties storage.length read only re
turns an integer representing the number of data items stored in the storage object. methods storage.key() when passed a number n, this method will re
turn the name of the nth key in the storage. storage.getitem() when passed a key name, will re
turn that key's value. storage.setitem() when passed a key name and value, will add that key to the storage, or update that key's value if it alrea...
StorageEstimate - Web APIs
these values are only estimates for several reasons, including both performance and preventing storage capacity data from being used for fingerprinting purposes. see the individual property pages for details. ...
StorageManager.persist() - Web APIs
the persist() method of the storagemanager interface requests permission to use persistent storage, and re
turns a promise that resolves to true if permission is granted and box mode is persistent, and false otherwise. syntax navigator.storage.persist().then(function(persistent) { ... }) parameters none. re
turn value a promise that resolves to a boolean. example if (navigator.storage && navigator.storage.persist) navigator.storage.persist().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persist' in that specificat...
StorageManager.persisted() - Web APIs
the persisted() method of the storagemanager interface re
turns a promise that resolves to true if box mode is persistent for your site's storage. syntax navigator.storage.persisted().then(function(persistent) { ... }) parameters none. re
turns a promise that resolves to a boolean. example if (navigator.storage && navigator.storage.persist) navigator.storage.persisted().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persisted' in that specification. living standard initial definition. ...
StorageManager - Web APIs
the storagemanager interface of the the storage api provides an interface for managing persistance permissions and estimating available storage. you can get a reference to this interface using either navigator.storage or workernavigator.storage. methods storagemanager.estimate() secure context re
turns a promise that resolves to a storageestimate object containing usage and quota numbers for your origin. storagemanager.persist() secure context re
turns a promise that resolves to true if the user agent is able to persist your site's storage. storagemanager.persisted() secure context re
turns a promise that resolves to true if persistence has already been granted for your site's storage. specifications specification status comment storagethe definition of 'st...
StorageQuota.queryInfo - Web APIs
the queryinfo() property of the storagequota interface re
turns a storageinfo object containting the current data usage and available quota information for the application. syntax storagequota.queryinfo().then(function(storageinfo) { ... }) parameters none. re
turns a reference to a storageinfo object. specifications specification status comment quota management apithe definition of 'queryinfo()' in that specification. obsolete initial definition. ...
StorageQuota.requestPersistentQuota - Web APIs
the requestpersistentquota() property of the storagequota interface requests persistent storage for the requesting application and re
turns a promise to an instance of storageinfo. there is no guarantee that the requested space will be granted by the user agent. syntax storagequota.requestpersistentquota().then(function(storageinfo) { ... }) parameters none. re
turns a reference to a storageinfo object. specifications specification status comment quota management apithe definition of 'requestpersistentquota()' in that specification. obsolete initial definition. ...
StorageQuota - Web APIs
the storagequota property of the navigator interface of the quota management api provides means to query and request storage usage and quota information. you can get a reference to this interface using navigator.storagequota. properties storagequota.supportedtypes read only re
turns a list of the available storage types. methods storagequota.queryinfo re
turns a storageinfo object containting the current data usage and available quota information for the application. storagequota.requestpersistentquota requests persistent storage for the requesting application and re
turns a promise to an instance of storageinfo. there is no guarantee that the requested space will be granted by the user agent. specifications specification status comment quota manag...
Storage API - Web APIs
e, and should be less than the available space on the device to help prevent overruns. user agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space. to determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate() method, which re
turns a promise that, when resolved, receives a storageestimate that contains these figures. for example: navigator.storage.estimate().then(estimate => { // estimate.quota is the estimated quota // estimate.usage is the estimated number of bytes used }); specifications specification status comment storage living standard initial definition. ...
StylePropertyMap.append() - Web APIs
the append() method of the stylepropertymap interface adds a new css declaration to the stylepropertymap with the given property and value. syntax stylepropertymap.append(property,value) parameters property an identifier indicating the stylistic feature (e.g. font, width, background color) to add. value the value the given property should have. re
turn value undefined. example // tbd specifications specification status comment css typed om level 1the definition of 'append()' in that specification. working draft initial definition. ...
StylePropertyMap.clear() - Web APIs
the clear() method of the stylepropertymap interface removes all declarations in the stylepropertymap. syntax stylepropertmap.clear() parameters none. re
turn value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'clear()' in that specification. working draft initial definition. ...
StylePropertyMap.delete() - Web APIs
the delete() method of the stylepropertymap interface removes the css declaration with the given property. syntax stylepropertymap.delete(property) parameters property an identifier indicating the stylistic feature (e.g. font, width, background color) to remove. re
turn value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'delete()' in that specification. working draft initial definition. ...
SyncEvent.tag - Web APIs
this is the value passed in the tag parameter of the syncevent() constructor. syntax var tag = syncevent.tag value the developer-defined identifier for this syncevent. ...
SyncManager.getTags() - Web APIs
the syncmanager.gettags method of the syncmanager interface re
turns a list of developer-defined identifiers for syncmanager registrations. syntax syncmanager.gettags().then(function(tags[]) { ... }) re
turns a promise that resolves to an array of domstrings containing developer-defined identifiers for syncmanager registrations. parameters none. ...
SyncManager.register() - Web APIs
parameters options optional an object that sets options for an instance of syncregistration. the available options are: allowonbattery: a boolean that determines whether synchronization is allowed when the user agent is on a battery-powered device. the default is true. id: the unique identifier of the specified syncregistration object. ...
SyncManager - Web APIs
the syncmanager interface of the the serviceworker api provides an interface for registering and listing sync registrations. properties none. methods syncmanager.register create a new sync registration and re
turn a promise. syncmanager.gettags re
turn a list of developer-defined identifiers for syncmanager registration. specifications specification status comment web background synchronizationthe definition of 'syncmanager' in that specification. living standard initial definition. ...
TaskAttributionTiming.containerId - Web APIs
a container is the iframe, embed or object etc. that is being implicated, on the whole, for a long task. syntax var containerid = taskattributiontiming.containerid; value a domstring containing the containers id attribute. specifications specification status comment long tasks api 1the definition of 'containerid' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
TaskAttributionTiming.containerName - Web APIs
a container is the iframe, embed or object etc. that is being implicated, on the whole, for a long task. syntax var containername = taskattributiontiming.containername; value a domstring containing the container's name attribute. ...
TaskAttributionTiming.containerSrc - Web APIs
a container is the iframe, embed or object etc. that is being implicated, on the whole, for a long task. syntax var containersrc = taskattributiontiming.containersrc; value a domstring containing the container's src attribute. ...
TaskAttributionTiming.containerType - Web APIs
syntax var containertype = taskattributiontiming.containertype; value a domstring containing the container's type, one of iframe, embed, or object. specifications specification status comment long tasks api 1the definition of 'containertype' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Text() - Web APIs
syntax text1 = new text(); // create an empty text node text2 = new text("this is a text node"); example let text = new text("test"); specifications specification status comment domthe definition of 'text()' in that specification. ...
HTMLSlotElement.assignedSlot - Web APIs
syntax var htmlslotelement = text.assignedslot value a htmlslotelement object. specifications specification status comment domthe definition of 'assignedslot' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Text.isElementContentWhitespace - Web APIs
note: you may simply replace it with /\s+/.test(text.data), /\s+/.test(text.nodevalue), or /\s+/.test(text.textcontent). putting any property that represents the textual content of the text node into test() should do the same work just like the three example above. the text.iselementcontentwhitespace read-only property re
turns a boolean flag indicating whether or not the text node's content consists solely of whitespace. syntax b = textnode.iselementcontentwhitespace; example in the example below, we create a node with mixed display and whitespace characters and the attribute is false. var tn = document.createtextnode("hello world"); tn.iselementcontentwhitespace; /* evaluates to false */ for a node that is all whitespace characters, the iselementcontentwhitespace evaluates to tru...
Text.replaceWholeText() - Web APIs
the text.replacewholetext() method replaces the text of the node and all of its logically adjacent text nodes with the specified text. the replaced nodes are removed, including the current node, unless it was the recipient of the replacement text. a domexception with the value no_modification_err is thrown if one of the text nodes being replaced is read only. this method re
turns the text node which received the replacement text, or null if the replacement text is an empty string. the re
turned node is the current node unless the current node is read only, in which case the re
turned node is a newly created text node of the same type which has been inserted at the location of the replacement. syntax replacementnode = textnode.replacewholetext(content) example see the example for the te...
TextDecoder() - Web APIs
if the value for utflabel is unknown, or is one of the two values leading to a 'replacement' decoding algorithm ( "iso-2022-cn" or "iso-2022-cn-ext"), a domexception with the "typeerror" value is thrown. syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder. ...
TextDecoder.prototype.decode() - Web APIs
syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. ...
TextDecoder.prototype.encoding - Web APIs
it can be one of the following values: the recommended encoding for the web: 'utf-8'. the legacy single-byte encodings: 'ibm866', 'iso-8859-2', 'iso-8859-3', 'iso-8859-4', 'iso-8859-5', 'iso-8859-6', 'iso-8859-7', 'iso-8859-8'', 'iso-8859-8i', 'iso-8859-10', 'iso-8859-13', 'iso-8859-14', 'iso-8859-15', 'iso-8859-16', 'koi8-r', 'koi8-u', 'macintosh', 'windows-874', 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254', 'windows-1255', 'windows-1256', 'windows-1257', 'windows-1258', or 'x-mac-cyrillic'. ...
TextTrackList.length - Web APIs
a value of 0 indicates that there are no text tracks in the media. syntax var trackcount = texttracklist.length; value a number indicating how many text tracks are included in the texttracklist. each track can be accessed by treating the texttracklist as an array of objects of type texttrack. example this snippet gets the number of text tracks in the first media element found in the dom by queryselector(). ...
TextTrackList - Web APIs
d, indicating that a new text track has been added to the media element. onchange an event handler to be called when the change event occurs. onremovetrack an event handler to call when the removetrack event is sent, indicating that a text track has been removed from the media element. methods this interface also inherits methods from its parent interface, eventtarget. gettrackbyid() re
turns the texttrack found within the texttracklist whose id matches the specified string. if no match is found, null is re
turned. events addtrack fired when a new text track has been added to the media element. also available via the onaddtrack property. change fired when a text track has been made active or inactive. also available via the onchange property. removetrack fired when a new t...
TimeRanges.end() - Web APIs
exceptions index_size_err a domexception thrown if the specified index doesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. ...
TimeRanges.length - Web APIs
syntax length = timeranges.length; example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification status comment html living standardthe definition of 'timeranges.length()' in that specification. ...
TimeRanges.start() - Web APIs
exceptions index_size_err a domexception thrown if the specified index doesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. ...
TimeRanges - Web APIs
ng and ending time offset. you reference each time range by using the start() and end() methods, passing the index number of the time range you want to retrieve. the term "normalized timeranges object" indicates that ranges in such an object are ordered, don't overlap, aren't empty, and don't touch (adjacent ranges are folded into one bigger range). properties timeranges.length read only re
turns an unsigned long representing the number of time ranges represented by the time range object. methods timeranges.start() re
turns the time for the start of the range with the specified index. timeranges.end() re
turns the time for the end of the specified range. specifications specification status comment html living standardthe definition of 'timeranges' in ...
msManipulationViewsEnabled - Web APIs
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 msmanipulationviewsenabled read-only property re
turns true if manipulation features are support available, such as touch panning and zooming using css rules. this proprietary property is specific to internet explorer and microsoft edge. value re
turns true if manipulation features are support available, such as touch panning and zooming using css rules. example using a json file: { msmanipulationviewsenabled: true, } see also touch api microsoft api extensions ...
Touch.clientX - Web APIs
example this example illustrates using the touch object's touch.clientx and touch.clienty properties. the touch.clientx property is the horizontal coordinate of a touch point relative to the browser's viewport excluding any scroll offset. the touch.clienty property is the vertical coordinate of the touch point relative to the browser's viewport excluding any scroll offset . ...
Touch.clientY - Web APIs
example this example illustrates using the touch object's touch.clientx and touch.clienty properties. the touch.clientx property is the horizontal coordinate of a touch point relative to the browser's viewport excluding any scroll offset. the touch.clienty property is the vertical coordinate of the touch point relative to the browser's viewport excluding any scroll offset . ...
Touch.pageX - Web APIs
example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. ...
Touch.pageY - Web APIs
example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. ...
Touch.screenX - Web APIs
example this example illustrates how to access the touch object's touch.screenx and touch.screeny properties. the touch.screenx property is the horizontal (x) coordinate of a touch point relative to the screen in css pixels. the touch.screeny property is the vertical coordinate of a touch point relative to the screen in css pixels. in following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface. ...
Touch.screenY - Web APIs
example the touch.screenx example includes an example of this property's usage. specifications specification status comment touch events – level 2 draft non-stable version. ...
TouchEvent.altKey - Web APIs
summary a boolean value indicating whether or not the alt (alternate) key is enabled when the touch event is created. if the alt key is enabled, the attribute's value is true. otherwise, it is false. this property is read only . syntax var altenabled = touchevent.altkey; re
turn value altenabled true if the alt key is enabled for this event; and false if the alt is not enabled. example this example illustrates how to access the touchevent key modifier properties: touchevent.altkey, touchevent.ctrlkey, touchevent.metakey and touchevent.shiftkey. in following code snippet, the touchstart event handler logs the state of the event's modifier keys. someelement.addeventlistener('touchstart', function(e) { // log the state of this event's modifier keys console.log("altkey = " + e...
TouchEvent.changedTouches - Web APIs
touch points that became active with the current event. for the touchmove event, it is a list of the touch points that have changed since the last event. for the touchend event, it is a list of the touch points that have been removed from the surface (that is, the set of touch points corresponding to fingers no longer touching the surface). syntax var changes = touchevent.changedtouches; re
turn value changes a touchlist whose touch objects include all the touch points that contributed to this touch event. example this example illustrates the touchevent object's touchevent.changedtouches property. the touchevent.changedtouches property is a touchlist object that contains one touch object for each touch point which contributed to the event. in following code snippet, the touchmove...
TrackDefaultList - Web APIs
the trackdefaultlist interface represents a simple container list for multiple trackdefault objects. the trackdefaultlist associated with a particular sourcebuffer can be retrieved using the sourcebuffer.trackdefaults property. constructor trackdefaultlist() constructs and re
turns a new trackdefaultlist object. properties inherits properties from its parent interface, eventtarget. trackdefaultlist.length read only re
turns the number of trackdefault objects in the list. methods inherits properties from its parent interface, eventtarget. trackdefaultlist.trackdefault() this getter allows the trackdefault objects in the list to be accessed with an array operator (i.e. [].) examples tbd. ...
TransitionEvent() - Web APIs
syntax transitionevent = new transitionevent(type, {propertyname: apropertyname, elapsedtime : afloat, pseudoelement: apseudoelementname}); arguments the transitionevent() constructor also inherits arguments from event(). type is a domstring representing the name of the type of the transitionevent. it is case-sensitive and can only be: 'transitionend'. propertyname optional is a domstring containing the value of the property-name css property associated with the transition. it defaults to "". ...
TreeWalker.currentNode - Web APIs
the treewalker.currentnode property represents the node on which the treewalker is currently pointing at. syntax node = treewalker.currentnode; treewalker.currentnode = node; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); root = treewalker.currentnode; // the root element as it is the first element! specifications specification status comment domthe definition of 'treewalker.currrentnode' in that specification. living standard no change from document object model (dom) level 2 traversal and range specification document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.cu...
TreeWalker.filter - Web APIs
the treewalker.filter read-only property re
turns a nodefilter that is the filtering object associated with the treewalker. when creating the treewalker, the filter object is passed in as the third parameter, and its method nodefilter.acceptnode() is called on every single node to determine whether or not to accept it. syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification. living standard no change from document object mo...
TreeWalker.firstChild() - Web APIs
the treewalker.firstchild() method moves the current node to the first visible child of the current node, and re
turns the found child. it also moves the current node to this child. if no such child exists, re
turns null and the current node is not changed. syntax node = treewalker.firstchild; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // re
turns the first child of the root element, or null if none specifications specification status comment domthe definition of 'treewalker.firstchild' in that specification. living standard no change from document object model (dom) level 2 travers...
TreeWalker.lastChild() - Web APIs
the treewalker.lastchild() method moves the current node to the last visible child of the current node, and re
turns the found child. it also moves the current node to this child. if no such child exists, re
turns null and the current node is not changed. syntax node = treewalker.lastchild(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // re
turns the last visible child of the root element specifications specification status comment domthe definition of 'treewalker.lastchild' in that specification. living standard no change from document object model (dom) level 2 traversal and range ...
TreeWalker.nextNode() - Web APIs
the treewalker.nextnode() method moves the current node to the next visible node in the document order, and re
turns the found node. it also moves the current node to this one. if no such node exists, re
turns null and the current node is not changed. syntax node = treewalker.nextnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // re
turns the first child of root, as it is the next node in document order specifications specification status comment domthe definition of 'treewalker.nextnode' in that specification. living standard no change from document object model (dom) level 2 tra...
TreeWalker.nextSibling() - Web APIs
the treewalker.nextsibling() method moves the current node to its next sibling, if any, and re
turns the found sibling. if there is no such node, re
turn null and the current node is not changed. syntax node = treewalker.nextsibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // re
turns null if the first child of the root element has no sibling specifications specification status comment domthe definition of 'treewalker.nextsibling' in that specification. living standard no change from document object model (dom) level 2 traversal and range specificatio...
TreeWalker.parentNode() - Web APIs
the treewalker.parentnode() method moves the current node to the first visible ancestor node in the document order, and re
turns the found node. if no such node exists, or if it is above the treewalker's root node, re
turns null and the current node is not changed. syntax node = treewalker.parentnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // re
turns null as there is no parent specifications specification status comment domthe definition of 'treewalker.parentnode' in that specification. living standard no change from document object model (dom) level 2 traversal and range sp...
TreeWalker.previousNode() - Web APIs
the treewalker.previousnode() method moves the current node to the previous visible node in the document order, and re
turns the found node. it also moves the current node to this one. if no such node exists,or if it is before that the root node defined at the object construction, re
turns null and the current node is not changed. syntax node = treewalker.previousnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // re
turns null as there is no parent specifications specification status comment domthe definition of 'treewalker.previousnode' in that specification. living standard ...
TreeWalker.previousSibling() - Web APIs
the treewalker.previoussibling() method moves the current node to its previous sibling, if any, and re
turns the found sibling. if there is no such node, re
turn null and the current node is not changed. syntax node = treewalker.previoussibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { re
turn nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // re
turns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification. living standard no change from document object model (dom) level 2 traversal and range specification document object...
TypeInfo - Web APIs
the obsolete typeinfo interface was intended to be used to describe a dom data type by keying its name to a namespace within the document's schema. properties typeinfo.typename read only re
turns a domstring indicating the type's name. typeinfo.typenamespace read only re
turns a domstring indicating the type's namespace within the schema. methods typeinfo.isderivedfrom() re
turns a boolean. constants constant value derivation_restriction 1 derivation_extension 2 derivation_union 4 derivation_list 8 specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'typeinfo' in that specification. obsolete initial definitio...
UIEvent.pageX - Web APIs
this property was never part of any standard, and was only implemented across a subset of browsers, and only for a limited number of versions. a standardized version of pagex was added to the mouseevent interface, however, and is well-supported. you should not expect to find pagex on any non-mouse events. do not look for pagex on any non-mouse events in new code and update existing code as soon as possible. syntax var pos = event.pagex value an integer value, in pixels, indicating the x coordinate at which the mouse pointer was located when the event occurred. ...
sourceCapabilities - Web APIs
when a single user interaction with an input device generates a series of different input events, the sourcecapabilities property for all of them will point to the same instance of inputdevicecapabilities. for example, when a user lifts their finger off of a touchscreen, several uievents may be generated including touchend, mousedown, click, and focus. all of these events must have the same sourcecapabilities representing the touchscreen. ...
UIEvent.view - Web APIs
in browsers, this is the window object the event happened in. syntax var view = event.view; view is a reference to an abstractview object. specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'uievent' in that specification. obsolete from document object model (dom) level 2 events specification, changed the type of view from abstractview to windowproxy. document object model (dom) level 2 events specificationthe definition of 'uievent' in that specification. ...
URL() - Web APIs
if the given base url or the resulting url are not valid urls, the javascript typeerror exception is thrown. note: this feature is available in web workers. syntax const url = new url(url [, base]) parameters url a usvstring representing an absolute or relative url. if url is a relative url, base is required, and will be used as the base url. if url is an absolute url, a given base will be ignored. base optional a usvstring representing the base url to use in case url is a relative url. if not specified, it defaults to ''. note: you can still use an existing url object for the base, which stringifies itself to the object's href property. ...
URL.createObjectURL() - Web APIs
esents the specified file object or blob object. to release an object url, call revokeobjecturl(). note: this feature is available in web workers. note: this feature is not available in service workers due to its potential to create memory leaks. syntax const objecturl = url.createobjecturl(object) parameters object a file, blob, or mediasource object to create an object url for. re
turn value a domstring containing an object url that can be used to reference the contents of the specified source object. examples see using object urls to display images. usage notes memory management each time you call createobjecturl(), a new object url is created, even if you've already created one for the same object. each of these must be released by calling url.revokeobjecturl() when ...
URL.searchParams - Web APIs
note: this feature is available in web workers. syntax const urlsearchparams = url.searchparams value a urlsearchparams object. examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith". ...
URL.toJSON() - Web APIs
the tojson() method of the url interface re
turns a usvstring containing a serialized version of the url, although in practice it seems to have the same effect as url.tostring(). note: this feature is available in web workers. syntax const href = url.tojson() re
turn value a usvstring. examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should re
turn the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification. living standard initial definition. ...
URL.toString() - Web APIs
the url.tostring() stringifier method re
turns a usvstring containing the whole url. it is effectively a read-only version of url.href. note: this feature is available in web workers. syntax const href = url.tostring() re
turn value a usvstring. examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should re
turn the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification. living standard initial definition. ...
URLSearchParams.append() - Web APIs
specified key/value pair as a new search parameter. as shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. note: this feature is available in web workers. syntax urlsearchparams.append(name, value) parameters name the name of the parameter to append. value the value of the parameter to append. re
turn value void. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); //query string is now: 'foo=1&bar=2&foo=4' specifications specification status comment urlthe definition of 'append()' in that specification. living standard initial definiti...
URLSearchParams.delete() - Web APIs
the delete() method of the urlsearchparams interface deletes the given search parameter and all its associated values, from the list of all search parameters. note: this feature is available in web workers. syntax urlsearchparams.delete(name) parameters name the name of the parameter to be deleted. re
turn value void examples let url = new url('https://example.com?foo=1&bar=2&foo=3'); let params = new urlsearchparams(url.search.slice(1)); // delete the foo parameter. params.delete('foo'); //query string is now: 'bar=2' specifications specification status comment urlthe definition of 'delete()' in that specification. living standard initial definition. ...
URLSearchParams.entries() - Web APIs
the entries() method of the urlsearchparams interface re
turns an iterator allowing iteration through all key/value pairs contained in this object. the key and value of each pair are usvstring objects. note: this feature is available in web workers. syntax searchparams.entries(); parameters none. re
turn value re
turns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification. living standard initial definition...
URLSearchParams.forEach() - Web APIs
the foreach() method of the urlsearchparams interface allows iteration through all values contained in this object via a callback function. note: this feature is available in web workers. syntax searchparams.foreach(callback); parameters callback a callback function that is executed against each parameter, with the param value provided as its parameter. re
turn value void. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification. living standar...
URLSearchParams.has() - Web APIs
the has() method of the urlsearchparams interface re
turns a boolean that indicates whether a parameter with the specified name exists. note: this feature is available in web workers. syntax var hasname = urlsearchparams.has(name) parameters name the name of the parameter to find. re
turn value a boolean. examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); params.has('bar') === true; //true specifications specification status comment urlthe definition of 'has()' in that specification. living standard initial definition. ...
URLSearchParams.keys() - Web APIs
the keys() method of the urlsearchparams interface re
turns an iterator allowing iteration through all keys contained in this object. the keys are usvstring objects. note: this method is available in web workers. syntax searchparams.keys(); parameters none. re
turn value re
turns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification. living standard initial definition. ...
URLSearchParams.sort() - Web APIs
the urlsearchparams.sort() method sorts all key/value pairs contained in this object in place and re
turns undefined. the sort order is according to unicode code points of the keys. this method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). note: this feature is available in web workers. syntax searchparams.sort(); parameters none. re
turn value undefined. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' i...
URLSearchParams.toString() - Web APIs
the tostring() method of the urlsearchparams interface re
turns a query string suitable for use in a url. note: this method re
turns the query string without the question mark. this is different from window.location.search, which includes it. note: this feature is available in web workers. syntax urlsearchparams.tostring() parameters none. re
turn value a domstring, without the question mark. (re
turns an empty string if no search parameters have been set.) examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter. params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new url('https://example.com?foo=1&bar=2')...
URLSearchParams.values() - Web APIs
the values() method of the urlsearchparams interface re
turns an iterator allowing iteration through all values contained in this object. the values are usvstring objects. note: this feature is available in web workers. syntax searchparams.values(); parameters none. re
turn value re
turns an iterator. examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification. living standard initial definition. ...
URLUtilsReadOnly.origin - Web APIs
d url, that is, for http and https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified). for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. syntax string = object.origin; examples // on this page, re
turns the origin var result = self.location.origin; // re
turns:'https://developer.mozilla.org:443' specifications specification status comment urlthe definition of 'urlutilsreadonly.origin' in that specification. living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to con...
URLUtilsReadOnly.port - Web APIs
living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
URL API - Web APIs
are settable; you can write new values to them to alter the url represented by the object. for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url. after executing the code snippet above, the value re
turned by addr.href is https://someguy@mysite.com/login. this is true for any of the writable properties. queries the search property on a url contains the query string portion of the url. for example, if the url is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. you can also look up the values of individual parameters with the urlse...
USB - Web APIs
the usb interface of the webusb api provides attributes and methods for finding and connecting usb devices from a web page. properties none. event handlers usb.onconnect an event handler called whenever a previously paired device is connected. usb.ondisconnect an event handler called whenever a paired device is disconnected. methods usb.getdevices() re
turns a promise that resolves with an array of usbdevice objects for paired attached devices. usb.requestdevice() re
turns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. specifications specification status comment webusbthe definition of 'usb' in that specification. draft initial definition. ...
USBConfiguration.configurationName - Web APIs
this is equal to the value of the string descriptor with the index provided in the iconfiguration field of the configuration descriptor defining this configuration. syntax var name = usbconfiguration.configurationname value the name provided by the device to describe this configuration. ...
USBDevice.clearHalt() - Web APIs
the clearhalt() method of the usbdevice interface re
turns a promise that resolves when a halt condition is cleared. a halt condition is when a data tranfer to or from the device has a status of 'stall', which requires the web page (the host system, in usb terminology) to clear that condition. see the for details. syntax var promise = usbdevice.clearhalt(direction, endpointnumber) parameters direction indicates whether the devices input or output should be cleared. valid values are 'in' or 'out'. endpointnumber indicates the number of the endpoint to clear. the promise will reject if an invalid endpoint is supplied. re
turn value a promise. example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer. what data can be pas...
USBDevice.close() - Web APIs
the close() method of the usbdevice interface re
turns a promise that resolves when all open interfaces are released and the device session has ended. syntax var promise = usbdevice.close() parameters none. re
turn value a promise. specifications specification status comment webusbthe definition of 'close()' in that specification. draft initial definition. ...
USBDevice.configuration - Web APIs
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. ...
USBDevice.isochronousTransferIn() - Web APIs
the isochronoustransferin() method of the usbdevice interface re
turns a promise that resolves with a usbisochronousintransferresult when time sensitive information has been transmitted received from the usb device. syntax var promise = usbdevice.isochronoustransferin(endpointnumber, packetlengths) parameters endpointnumber the number of a device-specific endpoint (buffer). packetlengths an array of lengths for the packets being received. re
turn value a promise that resolves with a usbisochronousintransferresult specifications specification status comment webusbthe definition of 'isochronoustransferin()' in that specification. draft initial definition. ...
USBDevice.isochronousTransferOut() - Web APIs
the isochronoustransferout() method of the usbdevice interface re
turns a promise that resolves with a usbisochronousouttransferresult when time sensitive information has been transmitted to the usb device. syntax var promise = usbdevice.isochronoustransferout(endpointnumber, data, packetlengths) parameters endpointnumber the number of a device-specific endpoint (buffer). data a typedarray containing the data to send to the device. packetlengths an array of lengths for the packets being transfered. re
turn value a promise that resolves with a usbisochronousouttransferresult. specifications specification status comment webusbthe definition of 'isochronoustransferout()' in that specification. draft initial definition. ...
USBDevice.open() - Web APIs
the open() method of the usbdevice interface re
turns a promise that resolves when a device session has started. syntax var promise = usbdevice.open() parameters none. re
turn value a promise. specifications specification status comment webusbthe definition of 'open()' in that specification. draft initial definition. ...
USBDevice.releaseInterface() - Web APIs
the releaseinterface() method of the usbdevice interface re
turns a promise that resolves when a cliamed interface is released from exclusive access. syntax var promise = usbdevice.releaseinterface(interfacenumber) parameters interfacenumber the device-specific index of the currently-claimed interface. re
turn value a promise. specifications specification status comment webusbthe definition of 'releaseinterface()' in that specification. draft initial definition. ...
USBDevice.reset() - Web APIs
the reset() method of the usbdevice interface re
turns a promise that resolves when the device is reset and all app operations canceled and their promises rejected. syntax var promise = usbdevice.reset() parameters none. re
turn value a promise. specifications specification status comment webusbthe definition of 'reset()' in that specification. draft initial definition. ...
USBDevice.selectAlternateInterface() - Web APIs
the selectalternateinterface() method of the usbdevice interface re
turns a promise that resolves when the specified alternative endpoint is selected. syntax var promise = usbdevice.selectalternateinterface(interfacenumber, alternatesetting) parameters interfacenumber the index of one of the interfaces supported by the device. interfaces are device-specific. alternatesetting the configuration of the selected interface. re
turn value a promise. specifications specification status comment webusbthe definition of 'selectalternateinterface()' in that specification. draft initial definition. ...
USBDevice.selectConfiguration() - Web APIs
the selectconfiguration() method of the usbdevice interface re
turns a promise that resolves when the specified configuration is selected. syntax var promise = usbdevice.selectconfiguration(configurationvalue) parameters configurationvalue the number of a device-specific configuration. re
turn value a promise. specifications specification status comment webusbthe definition of 'selectconfiguration' in that specification. draft initial definition. ...
USBDevice.transferIn() - Web APIs
the transferin() method of the usbdevice interface re
turns a promise that resolves with a usbtransferinresult when bulk or interrupt data is received from the usb device. syntax var promise = usbdevice.transferin(endpointnumber, length) parameters endpointnumber the number of a device-specific endpoint (buffer). length the maximum number of bytes that will be read back from the device. the actual data is in the usbintransferresult in the resolved promise. re
turn value a promise that resolves with a usbtransferinresult. specifications specification status comment webusbthe definition of 'transferin()' in that specification. draft initial definition. ...
USBDevice.transferOut() - Web APIs
the transferout() method of the usbdevice interface re
turns a promise that resolves with a usbtransferoutresult when bulk or interrupt data is sent to the usb device. syntax var promise = usbdevice.transferout(endpointnumber, data) parameters endpointnumber the number of a device-specific endpoint (buffer). data a typedarray containing the data to send to the device. re
turn value a promise that resolves with a usbtransferoutresult. specifications specification status comment webusbthe definition of 'transferout()' in that specification. draft initial definition. ...
USBInTransferResult - Web APIs
des the result from a call to the transferin() and controltransferin() methods of the usbdevice interface. it represents the result from requesting a transfer of data from the usb device to the usb host. constructor usbintransferresult.usbintransferresult() creates a new usbintransferresult object with the provided status and data fields. properties usbintransferresult.dataread only re
turns a dataview object containing the data received from the usb device, if any. usbintransferresult.statusread only re
turns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on the control endpoint does not need to be cleared. a stall on a bulk or interrupt endpoint...
USBIsochronousInTransferPacket - Web APIs
e. it represents the status of an individual packet from a request to transfer data from the usb device to the usb host over an isochronous endpoint. constructor usbisochronousintransferpacket.usbisochronousintransferpacket() creates a new usbisochronousintransferpacket object with the provided status and data fields. properties usbisochronousintransferpacket.dataread only read only re
turns a dataview object containing the data received from the usb device in this packet, if any. usbisochronousintransferpacket.statusread only read only re
turns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on an isochronous endpoint does not need to be cleared. ...
USBIsochronousOutTransferPacket - Web APIs
esents the status of an individual packet from a request to transfer data from the usb host to the usb device over an isochronous endpoint. constructor usbisochronousouttransferpacket.usbisochronousouttransferpacket() creates a new usbisochronousouttransferpacket object with the provided status and byteswritten fields. properties usbisochronousouttransferpacket.byteswrittenread only re
turns the number of bytes from the packet that were sent to the device. usbisochronousouttransferpacket.statusread only re
turns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on an isochronous endpoint does not need to be cleared. specifications spe...
USBIsochronousOutTransferResult - Web APIs
o the isochronoustransferout() method of the usbdevice interface. it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbisochronousouttransferresult.usbisochronousouttransferresult() creates a new usbisochronousouttransferresult object with the provided packet field. properties usbisochronousouttransferresult.packetsread only re
turns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device. specifications specification status comment webusbthe definition of 'usbisochronousouttransferresult' in that specification. draft initial definition. ...
USBOutTransferResult - Web APIs
call to the transferout() and controltransferout() methods of the usbdevice interface. it represents the result from requesting a transfer of data from the usb host to the usb device. constructor usbouttransferresult.usbouttransferresult() creates a new usbouttransferresult object with the provided status and byteswritten fields. properties usbouttransferresult.byteswrittenread only re
turns the number of bytes from the transfer request that were sent to the device. usbouttransferresult.statusread only re
turns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on a bulk or interrupt endpoint must be cleared by calling clearhalt() before transferout()...
USVString - Web APIs
usvstring is equivalent to domstring except for not allowing unpaired surrogate codepoints. unpaired surrogate codepoints present in usvstring are converted by the browser to unicode 'replacement character' u+fffd, (�). ...
UserDataHandler - Web APIs
accept, in its third argument, a handler which will be called when the object is cloned, imported, deleted, renamed, or adopted. per the specification, exceptions should not be thrown in a userdatahandler. in both document.importnode() and node.clonenode(), although user data is not copied over, the handler will be called. properties none. methods handle (operation, key, data, src, dst) (no re
turn value) this method is a callback which will be called if a node is being cloned, imported, renamed and as well, if deleted or adopted. operation (unsigned short) is an operation type integer (see below). key (domstring) is the user key. data (domuserdata) is the user data. src (node) is the source node (null if being deleted). dst (node) is the destination node (if any, or null). consta...
VRStageParameters - Web APIs
webvr api represents the values describing the the stage area for devices that support room-scale experiences. this interface is accessible through the vrdisplay.stageparameters property. properties vrstageparameters.sittingtostandingtransform read only contains a matrix that transforms the sitting-space view matrices of vrframedata to standing-space. vrstageparameters.sizex read only re
turns the width of the play-area bounds in meters. vrstageparameters.sizey read only re
turns the depth of the play-area bounds in meters. examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === ...
VTTRegion - Web APIs
properties vttregion.id a domstring that identifies the region. vttregion.width a double representing the width of the region, as a percentage of the video. vttregion.lines a double representing the height of the region, in number of lines. vttregion.regionanchorx a double representing the region anchor x offset, as a percentage of the region. ...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
syntax value = videoplaybackquality.droppedvideoframes; value an unsigned 64-bit value indicating the number of frames that have been dropped since the last time the media in the <video> element was loaded or reloaded. this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. ...
VideoPlaybackQuality.totalFrameDelay - Web APIs
obsolete since gecko 30 (firefox 30 / thunderbird 30 / seamonkey 2.27 / firefox os 1.4)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the videoplaybackquality.totalframedelay read-only property re
turns a double containing the sum of the frame delay since the creation of the associated htmlvideoelement. the frame delay is the difference between a frame's theoretical presentation time and its effective display time. syntax value = videoplaybackquality.totalframedelay; example var videoelt = document.getelementbyid('my_vid'); var quality = videoelt.getvideoplaybackquality(); alert(quality.totalframedelay); ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
syntax value = videoplaybackquality.totalvideoframes; value the total number of frames that the <video> element has displayed or dropped since the media was loaded into it. essentially, this is the number of frames the element would have presented had no problems occurred. this value is reset when the media is reloaded or replaced. example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped. ...
VideoPlaybackQuality - Web APIs
properties the videoplaybackquality interface doesn't inherit properties from any other interfaces. creationtime read only a domhighrestimestamp containing the time in miliseconds between the start of the navigation and the creation of the object. droppedvideoframes read only an unsigned long giving the number of video frames dropped since the creation of the associated htmlvideoelement. totalvideoframes read only an unsigned long giving the number of video frames created and dropped since the creation of the associated htmlvideoelement. ...
WEBGL_compressed_texture_astc - Web APIs
available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: astc compression is typically available on mali arm gpus, intel gpus, and nividia tegra chips. this extension is available to both, webgl1 and webgl2 contexts. methods this extension exposes one new methods. ext.getsupportedprofiles() re
turns an array of strings containing the names of the astc profiles supported by the implementation. constants the compressed texture formats are exposed by 28 constants and can be used in two functions: compressedteximage2d() and compressedtexsubimage2d(). constants blocks bits per pixel arraybuffer bytelength bytes if height and width are 512 ext.compressed_rgba_a...
WEBGL_debug_renderer_info - Web APIs
wser, this extension might only be available to privileged contexts. generally, the graphics driver information should only be used in edge cases to optimize your webgl content or to debug gpu problems. the webglrenderingcontext.getparameter() method can help you to detect which features are supported and the failifmajorperformancecaveat context attribute lets you control if a context should be re
turned at all, if the performance would be dramatically slow. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: depending on the privacy settings of the browser, this extension might only be available to privileged contexts or not work at all. in firefox, if privacy.resistfingerp...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
the webgl_debug_shaders.gettranslatedshadersource() method is part of the webgl api and allows you to debug a translated shader. syntax gl.getextension('webgl_debug_shaders').gettranslatedshadersource(shader); parameters shader a webglshader to get the translated source from. re
turn value a string containing the translated shader source. an empty string is re
turned, if: no source has been defined or, webglrenderingcontext.compileshader() has not yet been called or, the translation for the shader failed. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.fragment_shader); gl.shadersource(shader, 'void main() { gl_fragcolor = vec4(gl_fragcoord.x, 0.0, 0.0, 1.0); }'); gl.compileshader(shader); var src ...
WEBGL_debug_shaders - Web APIs
are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: depending on the privacy settings of the browser, this extension might only be available to privileged contexts. this extension is available to both, webgl1 and webgl2 contexts. methods webgl_debug_shaders.gettranslatedshadersource() re
turns the translated shader source. specifications specification status comment webgl_debug_shadersthe definition of 'webgl_debug_shaders' in that specification. recommendation initial definition. ...
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
examples see webgl_draw_buffers for more context with this example code. ext.drawbufferswebgl([ ext.color_attachment0_webgl, // gl_fragdata[0] ext.color_attachment1_webgl, // gl_fragdata[1] ext.color_attachment2_webgl, // gl_fragdata[2] ext.color_attachment3_webgl // gl_fragdata[3] ]); specifications specification status comment webgl_draw_buffer...
WEBGL_draw_buffers - Web APIs
ext.max_color_attachments_webgl a glint indicating the maximum number of framebuffer color attachment points. ext.max_draw_buffers_webgl a glint indicating the maximum number of draw buffers. methods this extension exposes one new method. ext.drawbufferswebgl() defines the draw buffers to which all fragment colors are written. (when using webgl2, this method is avai...
WakeLock - Web APIs
examples the following asynchronous function requests a wakelocksentinel object. ...
WaveShaperNode.WaveShaperNode() - Web APIs
tions dictionary. context a reference to an audiocontext. options optional options are as follows: curve: the shaping curve used for the waveshaping effect. the input signal is nominally within the range [-1;1]. oversample: specifies what type of oversampling (if any) should be used when applying the shaping curve. valid values are 'none', '2x', or '4x'. the default is 'none'. re
turn value a new waveshapernode object instance. specifications specification status comment web audio apithe definition of 'waveshapernode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://gi...
WaveShaperNode.curve - Web APIs
); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } re
turn curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe definition of 'curve' in that specification. working draft ...
WaveShaperNode.oversample - Web APIs
); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } re
turn curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe definition of 'oversample' in that specification. working draft ...
WaveShaperNode - Web APIs
); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } re
turn curve; }; ... distortion.curve = makedistortioncurve(400); distortion.oversample = '4x'; specifications specification status comment web audio apithe definition of 'waveshapernode' in that specification. working draft ...
WebGL2RenderingContext.beginQuery() - Web APIs
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. query a webglquery object for which to start the querying. re
turn value none. examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ... specifications specification status comment webgl 2.0the definition of 'beginquery' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glbeginquery' in that specification. standard man page of the (similar...
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
l2renderingcontext.begintransformfeedback() method of the webgl 2 api starts a transform feedback operation. syntax void gl.begintransformfeedback(primitivemode); parameters primitivemode a glenum specifying the output type of the primitives that will be recorded into the buffer objects that are bound for transform feedback. possible values: gl.points gl.lines gl.triangles re
turn value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); specifications specification status comment webgl 2.0the definition of 'begintransformfeedback' in that specification. editor's draft initial de...
WebGL2RenderingContext.bindBufferBase() - Web APIs
en webglbuffer to a given binding point (target) at a given index. syntax void gl.bindbufferbase(target, index, buffer); parameters target a glenum specifying the target for the bind operation. possible values: gl.transform_feedback_buffer gl.uniform_buffer index a gluint specifying the index of the target. buffer a webglbuffer which to bind to the binding point (target). re
turn value none. examples gl.bindbufferbase(gl.transform_feedback_buffer, 0, buffer); specifications specification status comment webgl 2.0the definition of 'bindbufferbase' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glbindbufferbase' in that specification. standard man page of the (similar) ope...
WebGL2RenderingContext.bindBufferRange() - Web APIs
target a glenum specifying the target for the bind operation. possible values: gl.transform_feedback_buffer gl.uniform_buffer index a gluint specifying the index of the target. buffer a webglbuffer which to bind to the binding point (target). offset a glintptr specifying the starting offset. size a glsizeiptr specifying the amount of data that can be read from the buffer. re
turn value none. examples gl.bindbufferrange(gl.transform_feedback_buffer, 1, buffer, 0, 4); specifications specification status comment webgl 2.0the definition of 'bindbufferrange' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glbindbufferrange' in that specification. standard man page of the (sim...
WebGL2RenderingContext.bindSampler() - Web APIs
the webgl2renderingcontext.bindsampler() method of the webgl 2 api binds a passed webglsampler object to the texture unit at the passed index. syntax void gl.bindsampler(unit, sampler); parameters unit a gluint specifying the index of the texture unit to which to bind the sampler to. sampler a webglsampler object to bind. re
turn value none. examples var sampler = gl.createsampler(); gl.bindsampler(0, sampler); specifications specification status comment webgl 2.0the definition of 'bindsampler' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glbindsampler' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.bindTransformFeedback() - Web APIs
the webgl2renderingcontext.bindtransformfeedback() method of the webgl 2 api binds a passed webgltransformfeedback object to the current gl state. syntax void gl.bindtransformfeedback(target, transformfeedback); parameters target a glenum specifying the target (binding point). must be gl.transform_feedback. transformfeedback a webgltransformfeedback object to bind. re
turn value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); specifications specification status comment webgl 2.0the definition of 'bindtransformfeedback' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glbindtransformfeedback...
WebGL2RenderingContext.blitFramebuffer() - Web APIs
0, dstx1, dsty1 a glint specifying the bounds of the destination rectangle. mask a glbitfield specifying a bitwise or mask indicating which buffers are to be copied. possible values: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit filter a glenum specifying the interpolation to be applied if the image is stretched. possible values: gl.nearest gl.linear re
turn value none. examples gl.blitframebuffer(0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height, gl.color_buffer_bit, gl.nearest); specifications specification status comment webgl 2.0the definition of 'blitframebuffer' in that specification. editor's draft initial definition for webgl. opengl es 3.0th...
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
and stencil buffers (used with clearbufferfi). drawbuffer a glint specifying the draw buffer to clear. values an array of glint, gluint or glfloat values or an int32array, uint32array or float32array specifying the values to clear to. depth a glfloat specifying the value to clear a depth render buffer to. stencil a glint specifying the value to clear the stencil render buffer to. re
turn value none. examples gl.clearbufferiv(gl.color, 0, new int32array([r, g, b, a])); gl.clearbufferuiv(gl.color, 0, new uint32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, new float32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, [0.0, 0.0, 0.0, 0.0]); gl.clearbufferfi(gl.depth_stencil, 0, 1.0, 0); specifications specification status comment webgl 2.0the defi...
WebGL2RenderingContext.clientWaitSync() - Web APIs
ync(sync, flags, timeout); parameters sync a webglsync object on which to wait on. flags a glbitfield specifying a bitwise combination of flags controlling the flushing behavior. may be gl.sync_flush_commands_bit. timeout a glint64 specifying a timeout (in nanoseconds) for which to wait for the sync object to become signaled. must not be larger than gl.max_client_wait_timeout_webgl. re
turn value a glenum indicating the sync object's status. gl.already_signaled: indicates that the sync object was signaled when this method was called. gl.timeout_expired: indicates that the timeout time passed and that the sync object did not become signaled. gl.condition_satisfied: indicates that the sync object was signaled before the timeout expired. gl.wait_failed: indicates that an error o...
WebGL2RenderingContext.compressedTexSubImage3D() - Web APIs
chthrough_alpha1_etc2 gl.compressed_srgb8_punchthrough_alpha1_etc2 imagesize a glint specifying the number of bytes to read from the buffer bound to gl.pixel_unpack_buffer. offset a glint specifying the offset in bytes from which to read from the buffer bound to gl.pixel_unpack_buffer. srcdata an arraybufferview that be used as a data store for the compressed image data in memory. re
turn value none. examples gl.compressedtexsubimage3d(gl.texture_3d, 0, 0, 0, 512, 512, 512, gl.compressed_r11_eac, texturedata); specifications specification status comment webgl 2.0the definition of 'compressedtexsubimage3d' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glcompressedtexsubimage3d' in tha...
WebGL2RenderingContext.copyBufferSubData() - Web APIs
d for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer operations. gl.pixel_unpack_buffer: buffer used for pixel transfer operations. readoffset writeoffset a glintptr specifying the byte offset from which to start reading from or writing to the buffer. size a glsizei in bytes specifying the size of the data to be copied from readtarget to writetarget. re
turn value none. examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data = new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer, new float32...
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
he y offset within the texture image. zoffset a glint specifying the z offset within the texture image. x a glint specifying the x coordinate of the lower left corner where to start copying. y a glint specifying the y coordinate of the lower left corner where to start copying. width a glsizei specifying the width of the texture. height a glsizei specifying the height of the texture. re
turn value none. examples gl.copytexsubimage3d(gl.texture_3d, 0, 0, 0, 0, 0, 0, 16, 16); specifications specification status comment webgl 2.0the definition of 'copytexsubimage3d' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glcopytexsubimage3d' in that specification. standard man page of the (similar) open...
WebGL2RenderingContext.createVertexArray() - Web APIs
the webgl2renderingcontext.createvertexarray() method of the webgl 2 api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data. syntax webglvertexarrayobject gl.createvertexarray(); parameters none. re
turn value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data. examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ... // calls to bindbuffer or vertexattribpointer // which will be "recorded" in the vao // ... specifications specification status comment webgl 2.0the definition of 'createvertexarray' in that specification. editor's draft initia...
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. instancecount a glsizei specifying the number of instances of the range of elements to execute. re
turn value none. examples gl.drawarraysinstanced(gl.points, 0, 8, 4); specifications specification status comment webgl 2.0the definition of 'drawarraysinstanced' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gldrawarraysinstanced' in that specification. standard man page of the (similar) opengl ap...
WebGL2RenderingContext.drawBuffers() - Web APIs
meters buffers an array of glenum specifying the buffers into which fragment colors will be written. possible values are: gl.none: fragment shader output is not written into any color buffer. gl.back: fragment shader output is written into the back color buffer. gl.color_attachment{0-15}: fragment shader output is written in the nth color attachment of the current framebuffer. re
turn value none. exceptions if buffers contains not one of the accepted values, a gl.invalid_enum error is thrown. examples gl.drawbuffers([gl.none, gl.color_attachment1]); specifications specification status comment webgl 2.0the definition of 'drawbuffers' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition ...
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. instancecount a glsizei specifying the number of instances of the set of elements to execute. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count or instancecount are negative, a gl.invalid_value error is thrown. examples gl.drawelementsinstanced(gl.points, 2, gl.unsigned_short, 0, 4); specifications specificat...
WebGL2RenderingContext.drawRangeElements() - Web APIs
ximum array index contained in offset. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short gl.unsigned_int offset a glintptr specifying an offset in the element array buffer. must be a valid multiple of the size of the given type. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count is negative, a gl.invalid_value error is thrown. examples gl.drawrangeelements(gl.points, 0, 7, 8, gl.unsigned_byte, 0); specifications specification status com...
WebGL2RenderingContext.endQuery() - Web APIs
s_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. re
turn value none. examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ... gl.endquery(gl.any_samples_passed); specifications specification status comment webgl 2.0the definition of 'endquery' in that specification. editor's draft initial definition. opengl es 3.0the definition of 'glendquery' in that specification. sta...
WebGL2RenderingContext.endTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'endtransformfeedback' in that specification. ...
WebGL2RenderingContext.fenceSync() - Web APIs
erts it into the gl command stream. syntax webglsync gl.fencesync(condition, flags); parameters condition a glenum specifying the condition that must be met to set the sync object's state to signaled. must be gl.sync_gpu_commands_complete. flags a glbitfield specifying a bitwise combination of flags controlling the behavior of the sync object. must be 0 (exists for extensions only). re
turn value a webglsync object. examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); specifications specification status comment webgl 2.0the definition of 'fencesync' in that specification. editor's draft initial definition for webgl. opengl es 3.0the defini...
WebGL2RenderingContext.framebufferTextureLayer() - Web APIs
ches the texture to the framebuffer's depth buffer. gl.stencil_attachment: attaches the texture to the framebuffer's stencil buffer. gl.depth_stencil_attachment: depth and stencil buffer. texture a webgltexture object whose image to attach. level a glint specifying the mipmap level of the texture image to attach. layer a glint specifying the layer of the texture image to attach. re
turn value none. examples gl.framebuffertexturelayer(gl.framebuffer, gl.color_attachment0, texture, 0, 8); specifications specification status comment webgl 2.0the definition of 'framebuffertexturelayer' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glframebuffertexturelayer' i...
WebGL2RenderingContext.getActiveUniformBlockName() - Web APIs
ingcontext.getactiveuniformblockname() method of the webgl 2 api retrieves the name of the active uniform block at a given index within a webglprogram. syntax domstring gl.getactiveuniformblockname(program, uniformblockindex); parameters program a webglprogram containing the uniform block. uniformblockindex a gluint specifying the index of the uniform block to whose name to retrieve. re
turn value a domstring indicating the active uniform block name. examples var blockname = gl.getactiveuniformblockname(program, 0); specifications specification status comment webgl 2.0the definition of 'getactiveuniformblockname' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glgetactiveuniformblockname' ...
WebGL2RenderingContext.getBufferSubData() - Web APIs
gl.pixel_unpack_buffer: buffer used for pixel transfer operations. srcbyteoffset a glintptr specifying the byte offset from which to start reading from the buffer. dstdata an arraybuffer or sharedarraybuffer to which to write the buffer data. srcoffset optional a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. re
turn value none. exceptions an invalid_value error is generated if: offset + re
turneddata.bytelength would extend beyond the end of the buffer re
turneddata is null offset is less than zero. an invalid_operation error is generated if: zero is bound to target target is transform_feedback_buffer, and any transform feedback object is currently active. examples var buffer = gl.createbuffer...
WebGL2RenderingContext.getIndexedParameter() - Web APIs
the webgl2renderingcontext.getindexedparameter() method of the webgl 2 api re
turns indexed information about a given target. syntax any gl.getindexedparameter(target, index); parameters target a glenum specifying the target for which to re
turn information. possible values: gl.transform_feedback_buffer_binding: re
turns a webglbuffer. gl.transform_feedback_buffer_size: re
turns a glsizeiptr. gl.transform_feedback_buffer_start: re
turns a glintptr. gl.uniform_buffer_binding: re
turns a webglbuffer. gl.uniform_buffer_size: re
turns a glsizeiptr. gl.uniform_buffer_start: re
turns a glintptr. index a gluint specifying the index of the target that is queried. re
turn value depends on the requested information (as specified with target). examples var binding = gl.g...
WebGL2RenderingContext.getQuery() - Web APIs
the webgl2renderingcontext.getquery() method of the webgl 2 api re
turns the currently active webglquery for the target, or null. syntax webglquery gl.getquery(target, pname); 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. pname a glenum specifying the query object target. must be gl.current_query. re
turn value a webglquery object. ...
WebGL2RenderingContext.getQueryParameter() - Web APIs
the webgl2renderingcontext.getqueryparameter() method of the webgl 2 api re
turns parameter information of a webglquery object. syntax any gl.getqueryparameter(query, pname); parameters query a webglquery object. pname a glenum specifying which information to re
turn. possible values: gl.query_result: re
turns a gluint containing the query result. gl.query_result_available: re
turns a glboolean indicating whether or not a query result is available. re
turn value depends on the pname parameter, either a gluint or a glboolean. examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); var result = gl.getqueryparameter(query, gl.query_result); specifications specification status comment webgl 2.0the definition of ...
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
the webgl2renderingcontext.getuniformblockindex() method of the webgl 2 api retrieves the index of a uniform block within a webglprogram. syntax gluint gl.getuniformblockindex(program, uniformblockname); parameters program a webglprogram containing the uniform block. uniformname a domstring specifying the name of the uniform block to whose index to retrieve. re
turn value a gluint indicating the uniform block index. examples // assuming a shader with the following declaration: // uniform ubodata { // mat4 foo; // } instancename; // use the block name, not the instance name: var blockindex = gl.getuniformblockindex(program, 'ubodata'); specifications specification status comment webgl 2.0the definition of 'getuniformblockindex' in that speci...
WebGL2RenderingContext.getUniformIndices() - Web APIs
the webgl2renderingcontext.getuniformindices() method of the webgl 2 api retrieves the indices of a number of uniforms within a webglprogram. syntax sequence<gluint> gl.getuniformindices(program, uniformnames); parameters program a webglprogram containing uniforms whose indices to query. uniformnames an array of domstring specifying the names of the uniforms to query. re
turn value an array of gluint containing the uniform indices. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); specifications specification status comment webgl 2.0the definition of 'getuniformindices' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glgetuniformind...
WebGL2RenderingContext.invalidateFramebuffer() - Web APIs
ray of glenum specifying the attachment points to invalidate. possible values: gl.color_attachment{0-15}: invalidates one of the framebuffer's color buffers. gl.depth_attachment: invalidates the framebuffer's depth buffer. gl.stencil_attachment: invalidates the framebuffer's stencil buffer. gl.depth_stencil_attachment: invalidates both the framebuffer's depth and stencil buffer. re
turn value none. examples gl.invalidateframebuffer(gl.read_framebuffer, [gl.color_attachment0, gl.color_attachment1]); specifications specification status comment webgl 2.0the definition of 'invalidateframebuffer' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glinvalidateframebuf...
WebGL2RenderingContext.invalidateSubFramebuffer() - Web APIs
tencil_attachment: invalidates both the framebuffer's depth and stencil buffer. x a glint specifying the left origin of the pixel rectangle to invalidate. y a glint specifying the bottom origin of the pixel rectangle to invalidate. width a glsizei specifying the width of the pixel rectangle to invalidate. height a glsizei specifying the height of the pixel rectangle to invalidate. re
turn value none. examples gl.invalidatesubframebuffer(gl.read_framebuffer, [gl.color_attachment0, gl.color_attachment1], 0, 0, 256, 256); specifications specification status comment webgl 2.0the definition of 'invalidatesubframebuffer' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.isQuery() - Web APIs
examples gl must be a webgl2renderingcontext. webglquery objects are not available in webgl 1. var query = gl.createquery(); // ... gl.isquery(query); specifications specification status comment webgl 2.0the definition of 'isquery' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.isSampler() - Web APIs
examples gl must be a webgl2renderingcontext. webglsampler objects are not available in webgl 1. var sampler = gl.createsampler(); // ... gl.issampler(sampler); specifications specification status comment webgl 2.0the definition of 'issampler' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.isSync() - Web APIs
examples gl must be a webgl2renderingcontext. webglsync objects are not available in webgl 1. var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); // ... gl.issync(sync); specifications specification status comment webgl 2.0the definition of 'issync' in that specification. editor's draft initial definition. ...
WebGL2RenderingContext.readBuffer() - Web APIs
r as the source for pixels for subsequent calls to copyteximage2d, copytexsubimage2d, copytexsubimage3d or readpixels. syntax void gl.readbuffer(src); parameters src a glenum specifying a color buffer. possible values: gl.back: reads from the back color buffer. gl.none: reads from no color buffer. gl.color_attachment{0-15}: reads from one of the 16 color attachment buffers. re
turn value none. examples gl.readbuffer(gl.color_attachment0); specifications specification status comment webgl 2.0the definition of 'readbuffer' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glreadbuffer' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
re_wrap_r: a glenum specifying the texture wrapping function for the texture coordinate r. gl.texture_wrap_s: a glenum specifying the texture wrapping function for the texture coordinate s. gl.texture_wrap_t: a glenum specifying the texture wrapping function for the texture coordinate t. param a glint (samplerparameteri) or a glfloat (samplerparameterf) specifying a value for pname. re
turn value none. examples var sampler = gl.createsampler(); gl.samplerparameteri(sampler, gl.texture_mag_filter, gl.nearest); specifications the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasaf...
WebGL2RenderingContext.texImage3D() - Web APIs
source one of the following objects can be used as a pixel source for the texture: arraybufferview, imagebitmap, imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement. offset a glintptr byte offset into the webglbuffer's data store. used to upload data to the currently bound webgltexture from the webglbuffer bound to the pixel_unpack_buffer target. re
turn value none. examples gl.teximage3d(gl.texture_3d, 0, // level gl.rgba, // internalformat 1, // width 1, // height 1, // depth ...
WebGL2RenderingContext.texStorage2D() - Web APIs
r11_eac gl.compressed_rg11_eac gl.compressed_signed_rg11_eac gl.compressed_rgb8_etc2 gl.compressed_rgba8_etc2_eac gl.compressed_srgb8_etc2 gl.compressed_srgb8_alpha8_etc2_eac gl.compressed_rgb8_punchthrough_alpha1_etc2 gl.compressed_srgb8_punchthrough_alpha1_etc2 width a glsizei specifying the width of the texture. height a glsizei specifying the height of the texture. re
turn value none. examples gl.texstorage2d(gl.texture_2d, 1, gl.rgb8, 256, 256); specifications specification status comment webgl 2.0the definition of 'texstorage2d' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gltexstorage2d' in that specification. standard man page of the (similar) opengl es 3.0...
WebGL2RenderingContext.texStorage3D() - Web APIs
_rg11_eac gl.compressed_rgb8_etc2 gl.compressed_rgba8_etc2_eac gl.compressed_srgb8_etc2 gl.compressed_srgb8_alpha8_etc2_eac gl.compressed_rgb8_punchthrough_alpha1_etc2 gl.compressed_srgb8_punchthrough_alpha1_etc2 width a glsizei specifying the width of the texture. height a glsizei specifying the height of the texture. depth a glsizei specifying the depth of the texture. re
turn value none. examples gl.texstorage3d(gl.texture_3d, 1, gl.rgb8, 256, 256, 256); specifications specification status comment webgl 2.0the definition of 'texstorage3d' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gltexstorage3d' in that specification. standard man page of the (similar) opengl e...
WebGL2RenderingContext.texSubImage3D() - Web APIs
gl.unsigned_short_5_5_5_1, or ext.half_float_oes. a float32array must be used if type is gl.float. imagebitmap, imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement. offset a glintptr byte offset into the webglbuffer's data store. used to upload data to the currently bound webgltexture from the webglbuffer bound to the pixel_unpack_buffer target. re
turn value none. examples gl.texsubimage3d(gl.texture_3d, 0, 0, 0, 0, image.width, image.height, 1, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 2.0the definition of 'texsubimage3d' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gltexsubimage2d' in that specificatio...
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
es to record in webgltransformfeedback buffers. syntax void gl.transformfeedbackvaryings(program, varyings, buffermode); parameters program a webglprogram. varyings an array of domstring specifying the the names of the varying variables to use. buffermode a glenum specifying the mode to use when capturing the varying variables. either gl.interleaved_attribs or gl.separate_attribs. re
turn value none. examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); var transformfeedbackoutputs = ['gl_position', 'anotheroutput']; gl.transformfeedbackvaryings(shaderprog, transformfeedbackoutputs, gl.interleaved_attribs); gl.linkprogram(shaderprog); specifications specificati...
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
location a webgluniformlocation object containing the location of the uniform attribute to modify. data, v0, v1, v2, v3 a new value to be used for the uniform variable. possible types: a number for unsigned integer values (methods with ui), for integer values (methods with i), or for floats (methods with f). a uint32array for unsigned integer vector methods (methods with uiv). re
turn value none. specifications specification status comment webgl 2.0the definition of 'uniform' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gluniform' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.uniformBlockBinding() - Web APIs
niform blocks. syntax void gl.uniformblockbinding(program, uniformblockindex, uniformblockbinding); parameters program a webglprogram containing the active uniform block whose binding to assign. uniformblockindex a gluint specifying the index of the active uniform block within the program. uniformblockbinding a gluint specifying the binding point to which to bind the uniform block. re
turn value none. examples gl.uniformblockbinding(program, 0, 1); specifications specification status comment webgl 2.0the definition of 'uniformblockbinding' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gluniformblockbinding' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
ation, transpose, data, optional srcoffset, optional srclength); void gl.uniformmatrix4fv(location, transpose, data, optional srcoffset, optional srclength); parameters location a webgluniformlocation object containing the location of the uniform attribute to modify. transpose a glboolean specifying whether to transpose the matrix. must be false. data a float32array of float values. re
turn value none. examples gl.uniformmatrix2x3fv(loc, false, [1, 2, 3, 4, 5, 6]); specifications specification status comment webgl 2.0the definition of 'uniformmatrix' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'gluniformmatrix' in that specification. standard man page of the (similar) opengl api.
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
raysinstanced() and gl.drawelementsinstanced(). note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too. syntax void gl.vertexattribdivisor(index, divisor); parameters index a gluint specifying the index of the generic vertex attributes. divisor a gluint specifying the number of instances that will pass between updates of the generic attribute. re
turn value none. examples gl.vertexattribdivisor(0, 2); specifications specification status comment webgl 2.0the definition of 'vertexattribdivisor' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glvertexattribdivisor' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.vertexAttribI4[u]i[v]() - Web APIs
ertexattribi4ui(index, v0, v1, v2, v3); void gl.vertexattribi4iv(index, value); void gl.vertexattribi4uiv(index, value); parameters index a gluint specifying the position of the vertex attribute to be modified. v0, v1, v2, v3 an integer number for the vertex attribute value. value a uint32array/int32array or sequences of gluint/ glint for integer vector vertex attribute values. re
turn value none. examples gl.vertexattribi4i(a_foobar, 10); specifications specification status comment webgl 2.0the definition of 'vertexattribi' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glvertexattribi' in that specification. standard man page of the (similar) opengl api. ...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
specifying the data type of each component in the array. must be one of: gl.byte, gl.unsigned_byte, gl.short, gl.unsigned_short, gl.int, or gl.unsigned_int. stride a glsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array. must be a multiple of type. re
turn value none. description very similar to webglrenderingcontext.vertexattribpointer(). the main difference is that while values specified by vertexattribpointer are always interpreted as floating-point values in the shader (even if they were originally specified as integers in the buffer), this method allows specifying values which are interpreted as integers in the shader. examples linear bl...
WebGL2RenderingContext.waitSync() - Web APIs
the webgl2renderingcontext.waitsync() method of the webgl 2 api re
turns immediately, but waits on the gl server until the given webglsync object is signaled. the method is a no-op in the absence of the possibility of synchronizing between multiple gl contexts. syntax void gl.waitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on. flags a glbitfield specifying a bitwise combination of flags controlling the flushing behavior. must be 0 (exists for extensions only). timeout a glint64 specifying a timeout the server should wait before continuing. must be gl.timeout_ignored. re
turn value none. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.waitsync(sync, 0, gl.timeout_ignored); specifications specificat...
WebGLActiveInfo.name - Web APIs
the read-only webglactiveinfo.name property represents the name of the requested data re
turned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.name; var activeuniform = gl.getactiveuniform(program, index); activeuniform.name; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.name' in that specification. recommendation initial definition. ...
WebGLActiveInfo.size - Web APIs
the read-only webglactiveinfo.size property is a number representing the size of the requested data re
turned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.size; var activeuniform = gl.getactiveuniform(program, index); activeuniform.size; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.size' in that specification. recommendation initial definition. ...
WebGLActiveInfo.type - Web APIs
the read-only webglactiveinfo.type property represents the type of the requested data re
turned by calling the getactiveattrib() or getactiveuniform() methods. examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.type; var activeuniform = gl.getactiveuniform(program, index); activeuniform.type; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.type' in that specification. recommendation initial definition. ...
WebGLRenderingContext.bindAttribLocation() - Web APIs
ex to an attribute variable. syntax void gl.bindattriblocation(program, index, name); parameters program a webglprogram object to bind. index a gluint specifying the index of the generic vertex to bind. name a domstring specifying the name of the variable to bind to the generic vertex index. this name cannot start with "webgl_" or "_webgl_", as these are reserved for use by webgl. re
turn value none. examples gl.bindattriblocation(program, colorlocation, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'bindattriblocation' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glbindattriblocation' in that specification. standard man page of the (similar) opengl a...
WebGLRenderingContext.bindBuffer() - Web APIs
.copy_write_buffer: buffer for copying from one buffer object to another. gl.transform_feedback_buffer: buffer for transform feedback operations. gl.uniform_buffer: buffer used for storing uniform blocks. gl.pixel_pack_buffer: buffer used for pixel transfer operations. gl.pixel_unpack_buffer: buffer used for pixel transfer operations. buffer a webglbuffer to bind. re
turn value none. exceptions only one target can be bound to a given webglbuffer. an attempt to bind the buffer to another target will throw an invalid_operation error and the current buffer binding will remain the same. a webglbuffer which has been marked for deletion with deletebuffer cannot be (re-)bound. an attempt to do so will generate an invalid_operation error, and the current binding will ...
WebGLRenderingContext.bindFramebuffer() - Web APIs
epth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. framebuffer a webglframebuffer object to bind. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. examples binding a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, framebuffer); getting current bindings to check the current ...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
() method of the webgl api binds a given webglrenderbuffer to a target, which must be gl.renderbuffer. syntax void gl.bindrenderbuffer(target, renderbuffer); parameters target a glenum specifying the binding point (target). possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. renderbuffer a webglrenderbuffer object to bind. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.renderbuffer. examples binding a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.bindrenderbuffer(gl.renderbuffer, renderbuffer); getting current bindings to check the current renderbuffer binding, query the renderb...
WebGLRenderingContext.bindTexture() - Web APIs
enum specifying the binding point (target). possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. texture a webgltexture object to bind. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.texture_2d, gl.texture_cube_map, gl.texture_3d, or gl.texture_2d_array. examples binding a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); getting current bindings to check the current texture ...
WebGLRenderingContext.blendColor() - Web APIs
set the source and destination blending factors. syntax void gl.blendcolor(red, green, blue, alpha); parameters red a glclampf for the red component in the range of 0 to 1. green a glclampf for the green component in the range of 0 to 1. blue a glclampf for the blue component in the range of 0 to 1. alpha a glclampf for the alpha component (transparency) in the range of 0 to 1. re
turn value none. examples to set the blend color, use: gl.blendcolor(0, 0.5, 1, 1); to get the blend color, query the blend_color constant which re
turns a float32array. gl.getparameter(gl.blend_color); // float32array[0, 0.5, 1, 1] specifications specification status comment webgl 1.0the definition of 'blendcolor' in that specification. recommendation initial defi...
WebGLRenderingContext.bufferData() - Web APIs
e source for webgl drawing and image specification commands. gl.stream_copy: the contents are intended to be specified once by reading data from webgl, and used at most a few times as the source for webgl drawing and image specification commands. srcoffset a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. re
turn value none. exceptions a gl.out_of_memory error is thrown if the context is unable to create a data store with the given size. a gl.invalid_value error is thrown if size is negative. a gl.invalid_enum error is thrown if target or usage are not one of the allowed enums. examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buf...
WebGLRenderingContext.bufferSubData() - Web APIs
perations. dstbyteoffset a glintptr specifying an offset in bytes where the data replacement will start. srcdata optional an arraybuffer, sharedarraybuffer or one of the arraybufferview typed array types that will be copied into the data store. srcoffset a gluint specifying the element index offset where to start reading the buffer. length optional a gluint defaulting to 0. re
turn value none. exceptions a gl.invalid_value error is thrown if the data would be written past the end of the buffer or if data is null. a gl.invalid_enum error is thrown if target is not one of the allowed enums. examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, b...
WebGLRenderingContext.canvas - Web APIs
the webglrenderingcontext.canvas property is a read-only reference to the htmlcanvaselement or offscreencanvas object that is associated with the context. it might be null if it is not associated with a <canvas> element or an offscreencanvas object. syntax gl.canvas; re
turn value either a htmlcanvaselement or offscreencanvas object or null. examples canvas element given this <canvas> element: <canvas id="canvas"></canvas> you can get back a reference to it from the webglrenderingcontext using the canvas property: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.canvas; // htmlcanvaselement offscreen canvas example using the experimental offscreencanvas object. var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('we...
WebGLRenderingContext.clear() - Web APIs
o preset values. the preset values can be set by clearcolor(), cleardepth() or clearstencil(). the scissor box, dithering, and buffer writemasks can affect the clear() method. syntax void gl.clear(mask); parameters mask a glbitfield bitwise or mask that indicates the buffers to be cleared. possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit re
turn value none. exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. gl.clear(gl.depth_buffer_bit); gl.clear(gl.depth_buffer_bit | gl.color_buffer_bit); to get the current clear values, query the color_clear_value, depth_clear_value, and stencil_clear_value constants. gl.getparameter(gl.color_clea...
WebGLRenderingContext.clearColor() - Web APIs
d when the color buffers are cleared. default value: 0. green a glclampf specifying the green color value used when the color buffers are cleared. default value: 0. blue a glclampf specifying the blue color value used when the color buffers are cleared. default value: 0. alpha a glclampf specifying the alpha (transparency) value used when the color buffers are cleared. default value: 0. re
turn value none. examples gl.clearcolor(1, 0.5, 0.5, 3); to get the current clear color, query the color_clear_value constant which re
turns a float32array. gl.getparameter(gl.color_clear_value); // float32array[1, 0.5, 0.5, 1] specifications specification status comment webgl 1.0the definition of 'clearcolor' in that specification. recommendation initial definiti...
WebGLRenderingContext.clearDepth() - Web APIs
the webglrenderingcontext.cleardepth() method of the webgl api specifies the clear value for the depth buffer. this specifies what depth value to use when calling the clear() method. the value is clamped between 0 and 1. syntax void gl.cleardepth(depth); parameters depth a glclampf specifying the depth value used when the depth buffer is cleared. default value: 1. re
turn value none. examples gl.cleardepth(0.5); to get the current depth clear value, query the depth_clear_value constant. gl.getparameter(gl.depth_clear_value); // 0.5 specifications specification status comment webgl 1.0the definition of 'cleardepth' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcleardepthf' in that specificati...
WebGLRenderingContext.colorMask() - Web APIs
en a glboolean specifying whether or not the green color component can be written into the frame buffer. default value: true. blue a glboolean specifying whether or not the blue color component can be written into the frame buffer. default value: true. alpha a glboolean specifying whether or not the alpha (transparency) component can be written into the frame buffer. default value: true. re
turn value none. examples gl.colormask(true, true, true, false); to get the current color mask, query the color_writemask constant which re
turns an array. gl.getparameter(gl.color_writemask); // [true, true, true, false] specifications specification status comment webgl 1.0the definition of 'colormask' in that specification. recommendation initial definition. ...
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
ray. border a glint specifying the width of the border. must be 0. imagesize a glsizei specifying the number of bytes to read from the buffer bound to gl.pixel_unpack_buffer. offset a glintptr specifying the offset in bytes from which to read from the buffer bound to gl.pixel_unpack_buffer. pixels an arraybufferview that be used as a data store for the compressed image data in memory. re
turn value none. examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_s3tc_dxt5_ext, 512, 512, 0, texturedata); gl.texparam...
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
n_rgtc2_ext ext.compressed_signed_red_green_rgtc2_ext imagesize a glsizei specifying the number of bytes to read from the buffer bound to gl.pixel_unpack_buffer. offset a glintptr specifying the offset in bytes from which to read from the buffer bound to gl.pixel_unpack_buffer. pixels an arraybufferview that be used as a data store for the compressed image data in memory. re
turn value none. examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); gl.compressedtexsubimage2d(gl.texture_2d, 0, 256, 256, 512, 512, ext.compressed_rgba_s3tc_dxt5_ext, texturedata); specifications specification status comment webgl...
WebGLRenderingContext.copyTexImage2D() - Web APIs
onent is a luminance/alpha component. x a glint specifying the x coordinate of the lower left corner where to start copying. y a glint specifying the y coordinate of the lower left corner where to start copying. width a glsizei specifying the width of the texture. height a glsizei specifying the height of the texture. border a glint specifying the width of the border. must be 0. re
turn value none. examples gl.copyteximage2d(gl.texture_2d, 0, gl.rgba, 0, 0, 512, 512, 0); specifications specification status comment webgl 1.0the definition of 'copyteximage2d' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcopyteximage2d' in that specification. standard man page of the (similar) opengl a...
WebGLRenderingContext.copyTexSubImage2D() - Web APIs
fset within the texture image. yoffset a glint specifying the vertical offset within the texture image. x a glint specifying the x coordinate of the lower left corner where to start copying. y a glint specifying the y coordinate of the lower left corner where to start copying. width a glsizei specifying the width of the texture. height a glsizei specifying the height of the texture. re
turn value none. examples gl.copytexsubimage2d(gl.texture_2d, 0, 0,0, 0, 0, 16, 16); specifications specification status comment webgl 1.0the definition of 'copytexsubimage2d' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcopytexsubimage2d' in that specification. standard man page of the (similar) opengl a...
WebGLRenderingContext.disable() - Web APIs
er. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. re
turn value none. examples gl.disable(gl.dither); to check if a capability is disabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // false specifications specification status comment webgl 1.0the definition of 'disable' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'gldi...
WebGLRenderingContext.drawArrays() - Web APIs
p: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if first or count are negative, a gl.invalid_value error is thrown. if gl.current_program is null, a gl.invalid_operation error is thrown. examples gl.drawarrays(gl.points, 0, 8); specifications specification status comment webgl 1.0the definition of 'drawarray...
WebGLRenderingContext.drawElements() - Web APIs
the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying a byte offset in the element array buffer. must be a valid multiple of the size of the given type. re
turn value none. exceptions if mode is not one of the accepted values, a gl.invalid_enum error is thrown. if offset is not a valid multiple of the size of the given type, a gl.invalid_operation error is thrown. if count is negative, a gl.invalid_value error is thrown. examples gl.drawelements(gl.points, 8, gl.unsigned_byte, 0); specifications specification status comment ...
WebGLRenderingContext.enable() - Web APIs
the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. re
turn value none. examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // true specifications specification status comment webgl 1.0the definition of 'enable' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glenable...
WebGLRenderingContext.finish() - Web APIs
the webglrenderingcontext.finish() method of the webgl api blocks execution until all previously called commands are finished. syntax void gl.finish(); parameters none. re
turn value none. specifications specification status comment webgl 1.0the definition of 'finish' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glfinish' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.flush() - Web APIs
the webglrenderingcontext.flush() method of the webgl api empties different buffer commands, causing all commands to be executed as quickly as possible. syntax void gl.flush(); parameters none. re
turn value none. specifications specification status comment webgl 1.0the definition of 'flush' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glflush' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl renderbuffertarget a glenum specifying the binding point (target) for the render buffer. possible values: gl.renderbuffer: buffer data storage for single images in a renderable internal format. renderbuffer a webglrenderbuffer object to attach. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. a gl.invalid_enum error is thrown if renderbuffertarget is not gl.renderbuffer. a gl.invalid_enum error is thrown if attachment is not one of the allowed enums. examples gl.framebufferrenderbuffer(gl.framebuffer, gl.color_attachment0, gl.renderbuffer, re...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
of the cube. gl.texture_cube_map_negative_y: image for the negative y face of the cube. gl.texture_cube_map_positive_z: image for the positive z face of the cube. gl.texture_cube_map_negative_z: image for the negative z face of the cube. texture a webgltexture object whose image to attach. level a glint specifying the mipmap level of the texture image to be attached. must be 0. re
turn value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer. attachment is not one of the accepted attachment points. textarget is not one of the accepted texture targets. a gl.invalid_value error is thrown if level is not 0. a gl.invalid_operation error is thrown if texture isn't 0 or the name of an existing texture object. examples gl.fra...
WebGLRenderingContext.frontFace() - Web APIs
the webglrenderingcontext.frontface() method of the webgl api specifies whether polygons are front- or back-facing by setting a winding orientation. syntax void gl.frontface(mode); parameters mode a glenum type winding orientation. the default value is gl.ccw. possible values: gl.cw: clock-wise winding. gl.ccw: counter-clock-wise winding. re
turn value none. examples gl.frontface(gl.cw); specifications specification status comment webgl 1.0the definition of 'frontface' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glfrontface' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.generateMipmap() - Web APIs
ng the binding point (target) of the active texture whose mipmaps will be generated. possible values: gl.texture_2d: a two-dimensional texture. gl.texture_cube_map: a cube-mapped texture. when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture. gl.texture_2d_array: a two-dimensional array texture. re
turn value none. examples gl.generatemipmap(gl.texture_2d); specifications specification status comment webgl 1.0the definition of 'generatemipmap' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glgeneratemipmap' in that specification. standard man page of the (similar) opengl es 2.0 api. o...
WebGLRenderingContext.getActiveAttrib() - Web APIs
the webglrenderingcontext.getactiveattrib() method of the webgl api re
turns a webglactiveinfo object containing size, type, and name of a vertex attribute. it is generally used when querying unknown attributes either for debugging or generic library creation. syntax webglactiveinfo gl.getactiveattrib(program,index); parameters program a webglprogram containing the vertex attribute. index a gluint specifying the index of the vertex attribute to get. this value is an index 0 to n - 1 as re
turned by gl.getprogramparameter(program, gl.active_attributes). re
turn value a webglactiveinfo object. examples const numattribs = gl.getprogramparameter(program, gl.active_attributes); for (let i = 0; i < numattribs; ++i) { const info = gl.getactiveattrib(program, i); console.log('name:', ...
WebGLRenderingContext.getAttachedShaders() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getattachedshaders(program); specifications specification status comment webgl 1.0the definition of 'getattachedshaders' in that specification. ...
WebGLRenderingContext.getShaderParameter() - Web APIs
the webglrenderingcontext.getshaderparameter() method of the webgl api re
turns information about the given shader. syntax any gl.getshaderparameter(shader, pname); parameters shader a webglshader to get parameter information from. pname a glenum specifying the information to query. possible values: gl.delete_status: re
turns a glboolean indicating whether or not the shader is flagged for deletion. gl.compile_status: re
turns a glboolean indicating whether or not the last shader compilation was successful. gl.shader_type: re
turns a glenum indicating whether the shader is a vertex shader (gl.vertex_shader) or fragment shader (gl.fragment_shader) object. re
turn value re
turns the requested shader information (as specified with pname). examples gl.getshaderparameter(shader...
WebGLRenderingContext.getShaderSource() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'getshadersource' in that specification. recommendation initial definition. ...
WebGLRenderingContext.readPixels() - Web APIs
t gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev pixels an arraybufferview object to read data into. the array type must match the type of the type parameter. uint8array for gl.unsigned_byte. uint16array for gl.unsigned_short_5_6_5, gl.unsigned_short_4_4_4_4, or gl.unsigned_short_5_5_5_1. float32array for gl.float. dstoffset optional offset. defaults to 0. re
turn value none. exceptions a gl.invalid_enum error is thrown if format or type is not an accepted value. a gl.invalid_operation error is thrown if type is gl.unsigned_short_5_6_5 and format is not gl.rgb. type is gl.unsigned_short_4_4_4_4 and format is not gl.rgba. type does not match the typed array type of pixels. a gl.invalid_framebuffer_operation error is thrown if the cur...
WebGLRenderingContext.renderbufferStorage() - Web APIs
ion: ext.srgb8_alpha8_ext: 8-bit srgb and alpha. when using a webgl 2 context and the ext_color_buffer_float extension: gl.r16f gl.rg16f gl.rgba16f gl.r32f gl.rg32f gl.rgba32f gl.r11f_g11f_b10f width a glsizei specifying the width of the renderbuffer in pixels. height a glsizei specifying the height of the renderbuffer in pixels. re
turn value none. examples gl.renderbufferstorage(gl.renderbuffer, gl.rgba4, 256, 256); specifications specification status comment webgl 1.0the definition of 'renderbufferstorage' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glrenderbufferstorage' in that specification. standard man page of the op...
WebGLRenderingContext.sampleCoverage() - Web APIs
) method of the webgl api specifies multi-sample coverage parameters for anti-aliasing effects. syntax void gl.samplecoverage(value, invert); parameters value a glclampf which sets a single floating-point coverage value clamped to the range [0,1]. the default value is 1.0. invert a glboolean which sets whether or not the coverage masks should be inverted. the default value is false. re
turn value none. examples multi-sampling is disabled by default. to enable or disable multi-sampling, use the enable() and disable() methods with the argument gl.sample_coverage and gl.sample_alpha_to_coverage. gl.enable(gl.sample_coverage); gl.samplecoverage(0.5, false); to check the sample coverage values, query the sample_coverage_value and sample_coverage_invert constants. gl.getparameter(g...
WebGLRenderingContext.shaderSource() - Web APIs
the webglrenderingcontext.shadersource() method of the webgl api sets the source code of a webglshader. syntax void gl.shadersource(shader, source); parameters shader a webglshader object in which to set the source code. source a domstring containing the glsl source code to set. re
turn value none. examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'shadersource' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glshadersource' in that specification. standard man page of the (similar) opengl api. ...
WebGLRenderingContext.stencilFunc() - Web APIs
k). gl.always: always pass. ref a glint specifying the reference value for the stencil test. this value is clamped to the range 0 to 2n -1 where n is the number of bitplanes in the stencil buffer. the default value is 0. mask a gluint specifying a bit-wise mask that is used to and the reference value and the stored stencil value when the test is done. the default value is all 1. re
turn value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfunc(gl.less, 0, 0b1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter(). gl.getparamet...
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
k). gl.always: always pass. ref a glint specifying the reference value for the stencil test. this value is clamped to the range 0 to 2n -1 where n is the number of bitplanes in the stencil buffer. the default value is 0. mask a gluint specifying a bit-wise mask that is used to and the reference value and the stored stencil value when the test is done. the default value is all 1. re
turn value none. examples the stencil testing is disabled by default. to enable or disable stencil testing, use the enable() and disable() methods with the argument gl.stencil_test. gl.enable(gl.stencil_test); gl.stencilfuncseparate(gl.front, gl.less, 0.2, 1110011); to get the current stencil function, reference value, or other stencil information, query the following constants with getparameter...
WebGLRenderingContext.stencilMask() - Web APIs
isabling of both the front and back writing of individual bits in the stencil planes. the webglrenderingcontext.stencilmaskseparate() method can set front and back stencil writemasks to different values. syntax void gl.stencilmask(mask); parameters mask a gluint specifying a bit mask to enable or disable writing of individual bits in the stencil planes. by default, the mask is all 1. re
turn value none. examples gl.stencilmask(110101); to get the current stencil masks, query the stencil_writemask, stencil_back_writemask, or stencil_bits constants. gl.getparameter(gl.stencil_writemask); // 110101 gl.getparameter(gl.stencil_back_writemask); // 110101 gl.getparameter(gl.stencil_bits); // 0 specifications specification status comment webgl 1.0the definiti...
WebGLRenderingContext.stencilMaskSeparate() - Web APIs
to one value at the same time. syntax void gl.stencilmaskseparate(face, mask); parameters face a glenum specifying whether the front and/or back stencil writemask is updated. the possible values are: gl.front gl.back gl.front_and_back mask a gluint specifying a bit mask to enable or disable writing of individual bits in the stencil planes. by default, the mask is all 1. re
turn value none. examples gl.stencilmaskseparate(gl.front, 110101); to get the current stencil masks, query the stencil_writemask, stencil_back_writemask, or stencil_bits constants. gl.getparameter(gl.stencil_writemask); // 110101 gl.getparameter(gl.stencil_back_writemask); // 110101 gl.getparameter(gl.stencil_bits); // 0 specifications specification status comment web...
WebGLRenderingContext.stencilOp() - Web APIs
est fails. the default value is gl.keep. zfail a glenum specifying the function to use when the stencil test passes, but the depth test fails. the default value is gl.keep. zpass a glenum specifying the function to use when both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. the default value is gl.keep. re
turn value none. constants gl.keep keeps the current value. gl.zero sets the stencil buffer value to 0. gl.replace sets the stencil buffer value to the reference value as specified by webglrenderingcontext.stencilfunc(). gl.incr increments the current stencil buffer value. clamps to the maximum representable unsigned value. gl.incr_wrap increments the current stencil buffer value. wraps ...
WebGLRenderingContext.stencilOpSeparate() - Web APIs
est fails. the default value is gl.keep. zfail a glenum specifying the function to use when the stencil test passes, but the depth test fails. the default value is gl.keep. zpass a glenum specifying the function to use when both the stencil test and the depth test pass, or when the stencil test passes and there is no depth buffer or depth testing is disabled. the default value is gl.keep. re
turn value none. constants gl.keep keeps the current value. gl.zero sets the stencil buffer value to 0. gl.replace sets the stencil buffer value to the reference value as specified by webglrenderingcontext.stencilfunc(). gl.incr increments the current stencil buffer value. clamps to the maximum representable unsigned value. gl.incr_wrap increments the current stencil buffer value. wraps ...
WebGLRenderingContext.texImage2D() - Web APIs
nt or ext.unsigned_int_24_8_webgl. a float32array must be used if type is gl.float. imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement, imagebitmap. offset (webgl 2 only) a glintptr byte offset into the webglbuffer's data store. used to upload data to the currently bound webgltexture from the webglbuffer bound to the pixel_unpack_buffer target. re
turn value none. examples gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 1.0the definition of 'teximage2d' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'glteximage2d' in that specification. standard man page of the (simi...
WebGLRenderingContext.texParameter[fi]() - Web APIs
re_max_level maximum texture mipmap array level any int values. gl.texture_max_lod texture maximum level-of-detail value any float values. gl.texture_min_lod texture minimum level-of-detail value any float values. gl.texture_wrap_r wrapping function for texture coordinate r gl.repeat (default value), gl.clamp_to_edge, gl.mirrored_repeat. re
turn value none. examples gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear_mipmap_nearest); specifications specification status comment webgl 1.0the definition of 'texparameter[fi]' in that specification. recommendation initial definition for webgl. opengl es 2.0the definitio...
WebGLRenderingContext.texSubImage2D() - Web APIs
rt_5_5_5_1, or ext.half_float_oes. a float32array must be used if type is gl.float. imagedata, htmlimageelement, htmlcanvaselement, htmlvideoelement, imagebitmap. offset (webgl 2 only) a glintptr byte offset into the webglbuffer's data store. used to upload data to the currently bound webgltexture from the webglbuffer bound to the pixel_unpack_buffer target. re
turn value none. examples gl.texsubimage2d(gl.texture_2d, 0, 0, 0, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 1.0the definition of 'texsubimage2d' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition of 'gltexsubimage2d' in that specification. standard man page of the...
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
e used for the uniform variable. possible types: a floating point number for floating point values (methods with "f"). a sequence of floating point numbers (for example a float32array or an array of numbers) for floating point vector methods (methods with "fv"). an integer number for integer values (methods with "i"). an int32array for integer vector methods (methods with "iv"). re
turn value none. examples gl.uniform1f(u_alpha, 0.8); specifications specification status comment webgl 1.0the definition of 'uniform' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gluniform' in that specification. standard main page of the opengl api. ...
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
tion, transpose, value); parameters location a webgluniformlocation object containing the location of the uniform attribute to modify. the location is obtained using getuniformlocation(). transpose a glboolean specifying whether to transpose the matrix. must be false. value a float32array or sequence of glfloat values. the values are assumed to be supplied in column major order. re
turn value undefined examples gl.uniformmatrix2fv(loc, false, [2,1, 2,2]); specifications specification status comment webgl 1.0the definition of 'uniformmatrix' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gluniform' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.useProgram() - Web APIs
the webglrenderingcontext.useprogram() method of the webgl api sets the specified webglprogram as part of the current rendering state. syntax void gl.useprogram(program); parameters program a webglprogram to use. re
turn value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'useprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gluseprogram' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.validateProgram() - Web APIs
the webglrenderingcontext.validateprogram() method of the webgl api validates a webglprogram. it checks if it is successfully linked and if it can be used in the current webgl state. syntax void gl.validateprogram(program); parameters program a webglprogram to validate. re
turn value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.validateprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'va...
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
.vertexattrib1fv(index, value); void gl.vertexattrib2fv(index, value); void gl.vertexattrib3fv(index, value); void gl.vertexattrib4fv(index, value); parameters index a gluint specifying the position of the vertex attribute to be modified. v0, v1, v2, v3 a floating point number for the vertex attribute value. value a float32array for floating point vector vertex attribute values. re
turn value none. description while vertex attributes are usually used to specify values which are different for each vertex (using vertexattribpointer), it can be useful to specify a constant value. for example, if you have a shader which has a color vertex attribute, but you want to draw everything in a single color, you can use vertexattrib to achieve that without creating a buffer filled with on...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
larger than 255. if stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not interleaved but each attribute is in a separate block, and the next vertex' attribute follows immediately after the current vertex. offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array. must be a multiple of the byte length of type. re
turn value none. exceptions a gl.invalid_value error is thrown if offset is negative. a gl.invalid_operation error is thrown if stride and offset are not multiples of the size of the data type. a gl.invalid_operation error is thrown if no webglbuffer is bound to the array_buffer target. when using a webgl 2 context, a gl.invalid_operation error is thrown if this vertex attribute is defined as ...
WebGLShader - Web APIs
createshader (gl, sourcecode, type) { // compiles either a shader of type gl.vertex_shader or gl.fragment_shader var shader = gl.createshader( type ); gl.shadersource( shader, sourcecode ); gl.compileshader( shader ); if ( !gl.getshaderparameter(shader, gl.compile_status) ) { var info = gl.getshaderinfolog( shader ); throw 'could not compile webgl program. \n\n' + info; } re
turn shader; } see webglprogram for information on attaching the shaders. examples creating a vertex shader note that there are many other strategies for writing and accessing shader source code strings. these example are for illustration purposes only. var vertexshadersource = 'attribute vec4 position;\n' + 'void main() {\n' + ' gl_position = position;\n' + '}\n'; //use the createshad...
WebGLShaderPrecisionFormat.rangeMax - Web APIs
the read-only webglshaderprecisionformat.rangemax property re
turns the base 2 log of the absolute value of the maximum value that can be represented. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemax; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemax; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemax' in that specification. recommendation initial definition. ...
WebGLShaderPrecisionFormat.rangeMin - Web APIs
the read-only webglshaderprecisionformat.rangemin property re
turns the base 2 log of the absolute value of the minimum value that can be represented. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemin; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemin; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemin' in that specification. recommendation initial definition. ...
WebGLShaderPrecisionFormat - Web APIs
the webglshaderprecisionformat interface is part of the webgl api and represents the information re
turned by calling the webglrenderingcontext.getshaderprecisionformat() method. properties webglshaderprecisionformat.rangemin read only the base 2 log of the absolute value of the minimum value that can be represented. webglshaderprecisionformat.rangemax read only the base 2 log of the absolute value of the maximum value that can be represented. webglshaderprecisionformat.precision read only the number of bits of precision that can be represented. for integer formats this value is always 0. examples a webglshaderprecisionformat object is re
turned by the webglrenderingcontext.getshaderprecisionformat() method. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcont...
Basic scissoring - Web APIs
the drawing buffer to be identical to the size of the // canvas html element, as determined by css. canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; re
turn; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // enable scissoring operation and define the position and // size of the scissoring area. gl.enable(gl.scissor_test); gl.scissor(40, 20, 60, 130); // clear the drawing buffer solid yellow. gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }, false); the source code of this example is al...
Canvas size and WebGL - Web APIs
as.width = firstcanvas.clientwidth; firstcanvas.height = firstcanvas.clientheight; [firstcanvas, secondcanvas].foreach(function(canvas) { var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; re
turn; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github. « previousnext » ...
Creating 3D objects using WebGL - Web APIs
thus the cube is described as a collection of 12 triangles. drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buf...
Lighting in WebGL - Web APIs
0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, // right 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // left -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0 ]; gl.bufferdata(gl.array_buffer, new float32array(vertexnormals), gl.static_draw); ... re
turn { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata(). then we add the code to drawscene() to bind the normals array to a shader...
Using shaders to apply color in WebGL - Web APIs
itbuffers() function: function initbuffers(){ ... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); re
turn { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color. then a new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer. to use these colors, the vertex shader needs to be updated to pull the appropriate color from the ...
WebRTC coding guide - Web APIs
how do you create a web application that uses two-way video or data streams without having to do all the hard work of compressing frames, building streams, and so forth by yourself? this coding guide will explain in depth how webrtc works, and will dive into actual code that uses webrtc to do useful things. there are no subpages at this time. ...
Lifetime of a WebRTC session - Web APIs
chnologies you can come up with. you could even use email as the signaling channel. it’s also worth noting that the channel for performing signaling doesn’t even need to be over the network. one peer can output a data object that can be printed out, physically carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be re
turned on foot, and so forth, until the webrtc peer connection is open. it'd be very high latency but it could be done. information exchanged during signaling there are three basic types of information that need to be exchanged during signaling: control messages used to set up, open, and close the communication channel, and to handle errors. information needed in order to set up the connection: ...
WebSocket() - Web APIs
syntax var awebsocket = new websocket(url [, protocols]); parameters url the url to which to connect; this should be the url to which the websocket server will respond. protocols optional either a single protocol string or an array of protocol strings. these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). if you don't specify a protocol string, an empty string is assumed. exceptions thrown security_err the port to which the connection is being attempted is being blocked. ...
WebSocket.binaryType - Web APIs
syntax var binarytype = awebsocket.binarytype; value a domstring: "blob" if blob objects are used. "arraybuffer" if arraybuffer objects are used. specifications specification status comment html living standardthe definition of 'websocket: binarytype' in that specification. ...
WebSocket.bufferedAmount - Web APIs
this value resets to zero once all queued data has been sent. this value does not reset to zero when the connection is closed; if you keep calling send(), this will continue to climb. syntax var bufferedamount = awebsocket.bufferedamount; value an unsigned long. ...
WebSocket.extensions - Web APIs
this is currently only the empty string or a list of extensions as negotiated by the connection. syntax var extensions = awebsocket.extensions; value a domstring. specifications specification status comment html living standardthe definition of 'websocket: extensions' in that specification. ...
WebSocket.protocol - Web APIs
syntax var protocol = awebsocket.protocol; value a domstring. specifications specification status comment html living standardthe definition of 'websocket: protocol' in that specification. ...
WebSocket.readyState - Web APIs
syntax var readystate = awebsocket.readystate; value one of the following unsigned short values: value state description 0 connecting socket has been created. the connection is not yet open. 1 open the connection is open and ready to communicate. 2 closing the connection is in the process of closing. 3 closed the connection is closed or couldn't be opened. specifications specification status comment html living standardthe definition of 'websocket: readystate' in that specification. ...
WebSocket.send() - Web APIs
inary frame; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes. exceptions thrown invalid_state_err the connection is not currently open. syntax_err the data is a string that has unpaired surrogates. note: gecko's implementation of the send() method differs somewhat from the specification in gecko 6.0; gecko re
turns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in gecko 8.0. as of gecko 11.0, support for arraybuffer is implemented but not blob data types. specifications specification status comment html living standardthe definition of 'websocket: send' in that spec...
WebSocket.url - Web APIs
syntax var url = awebsocket.url; value a domstring. specifications specification status comment html living standardthe definition of 'websocket: url' in that specification. ...
WebSocket - Web APIs
the websocket object provides the api for creating and managing a websocket connection to a server, as well as for sending and receiving data on the connection. to construct a websocket, use the websocket() constructor. constructor websocket(url[, protocols]) re
turns a newly created websocket object. constants constant value websocket.connecting 0 websocket.open 1 websocket.closing 2 websocket.closed 3 properties websocket.binarytype the binary data type used by the connection. websocket.bufferedamount read only the number of bytes of queued data. websocket.extensions read only the extensions selected by the server. websocket.onclose an event listener to be called when the connection is closed. websocket.
Writing WebSocket client applications - Web APIs
code as defined in rfc 6455, section 7.4 through the closeevent. examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver. a custom protocol of "protocolone" is named in the request for the socket in this example, though this can be omitted. var examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on re
turn, examplesocket.readystate is connecting. the readystate will become open once the connection is ready to transfer data. if you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols: var examplesocket = new websocket("wss://www.example.com/socketserver", ["protocolone", "protocoltwo"]); once the connection is established (that is, rea...
Writing a WebSocket server in C# - Web APIs
yping the full namespace every time. tcplistener constructor: tcplistener(system.net.ipaddress localaddr, int port) localaddr specifies the ip of the listener, and port specifies the port. to create an ipaddress object from a string, use the parse static method of ipaddress. methods: start() system.net.sockets.tcpclient accepttcpclient() waits for a tcp connection, accepts it and re
turns it as a tcpclient object. here's a barebones server implementation: using system.net.sockets; using system.net; using system; class server { public static void main() { tcplistener server = new tcplistener(ipaddress.parse("127.0.0.1"), 80); server.start(); console.writeline("server has started on 127.0.0.1:80.{0}waiting for a connection...", environment.newlin...
Writing WebSocket servers - Web APIs
can decide on extension/subprotocol requests here; see miscellaneous for details. the sec-websocket-accept header is important in that the server must derive it from the sec-websocket-key that the client sent to it. to get it, concatenate the client's sec-websocket-key and the string "258eafa5-e914-47da-95ca-c5ab0dc85b11" together (it's a "magic string"), take the sha-1 hash of the result, and re
turn the base64 encoding of that hash. note: this seemingly overcomplicated process exists so that it's obvious to the client whether the server supports websockets. this is important because security issues might arise if the server accepts a websockets connection but interprets the data as a http request. so if the key was "dghlihnhbxbszsbub25jzq==", the sec-websocket-accept header's value is "s...
WebXR application life cycle - Web APIs
iate interface to the user to allow them to activate it. when the user requests the activation of webxr functionality by engaging with the user interface enabled above, request an xrsession using the desired mode. this is done by calling navigator.xr.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar. if the promise re
turned by requestsession() resolves, use the new xrsession to manage the webxr session for the duration of the webxr experience. this will involve managing inputs, animations, and rendering. call the xrsession method requestanimationframe() to schedule the first frame render for the xr device. if your scene is complex, you should consider creating a worker—or using one that you've previousl...
Keyframe Formats - Web APIs
element.animate(), keyframeeffect.keyframeeffect(), and keyframeeffect.setkeyframes() all accept objects formatted to represent a set of keyframes. there are several options to this format, which are explained below. syntax there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over. this is the canonical format re
turned by the getkeyframes() method. element.animate([ { // from opacity: 0, color: "#fff" }, { // to opacity: 1, color: "#000" } ], 2000); offsets for each keyframe can be specified by providing an offset value. element.animate([ { opacity: 1 }, { opacity: 0.1, offset: 0.7 }, { opacity: 0 } ], 2000); note: ...
Using the Web Animations API - Web APIs
y done. we could do that by setting her animation.currenttime to 4 seconds, like so: alicechange.currenttime = 4000; but while working on this animation, we might change alice’s duration a lot. wouldn’t it be better if we set her currenttime dynamically, so we don’t have to make two updates at a time? we can, in fact, do so by referencing alicechange’s animation.effect property, which re
turns an object containing all the details of the effect(s) active on alice: alicechange.currenttime = alicechange.effect.getcomputedtiming().duration / 2; effect lets us access the animation’s keyframes and timing properties — alicechange.effect.getcomputedtiming() points to alice’s timing object (which is of type computedeffecttiming) — this contains her computedeffecttiming.duration. we c...
Controlling multiple parameters with ConstantSourceNode - Web APIs
use a sine wave as the audio waveform. set the oscillator's frequency to the desired value; in this case, oscnode1 is set to a middle c, while oscnode2 and oscnode3 round out the chord by playing the e and g notes. connect the new oscillator to the corresponding gain node. once all three oscillators have been created, they're started by calling each one's constantsourcenode.start() method in
turn, and playing is set to true to track that the tones are playing. stopping the oscillators stopping the oscillators when the user toggles the play state to pause the tones is as simple as stopping each node. function stoposcillators() { oscnode1.stop(); oscnode2.stop(); oscnode3.stop(); playing = false; } each node is stopped by calling its constantsourcenode.stop() method, then playin...
Visualizations with Web Audio API - Web APIs
you need to create a new array to receive the data before invoking one. the first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard javascript array won't do — you need to use a float32array or uint8array array, depending on what data you are handling. so for example, say we are dealing with an fft size of 2048. we re
turn the analysernode.frequencybincount value, which is half the fft, then call uint8array() with the frequencybincount as its length argument — this is how many data points we will be collecting, for that fft size. analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); to actually retrieve the data and copy it into our array, we then ...
Web Bluetooth API - Web APIs
bluetoothadvertisingdata provides advertising data about a particular bluetooth device. bluetoothcharacteristicproperties provides properties of a particular bluetoothremotegattcharacteristic. bluetoothdevice represents a bluetooth device inside a particular script execution environment. ...
Web Workers API - Web APIs
indexeddb. see functions and classes available to workers for more details. data is sent between workers and the main thread via a system of messages — both sides send their messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data property). the data is copied rather than shared. workers may in
turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. in addition, workers may use xmlhttprequest for network i/o, with the exception that the responsexml and channel attributes on xmlhttprequest always re
turn null. in addition to dedicated workers, there are other types of worker: shared workers are workers that can be utilized by multiple scripts...
WheelEvent() - Web APIs
syntax var wheelevent = new wheelevent(typearg, wheeleventinit); properties typearg is a domstring representing the name of the event. wheeleventinit optional is a wheeleventinit dictionary, having the following fields: "deltax", optional and defaulting to 0.0, is a double representing the horizontal scroll amount in the deltamode unit. "deltay", optional and defaulting to 0.0, is a double representing the vertical scroll amount in the deltamode unit. "deltaz", optional and defaulting to 0.0, is a double representing the scroll amount for the z-axis in the deltamode unit. ...
WheelEvent.deltaMode - Web APIs
permitted values are: constant value description dom_delta_pixel 0x00 the delta values are specified in pixels. dom_delta_line 0x01 the delta values are specified in lines. dom_delta_page 0x02 the delta values are specified in pages. ...
WheelEvent - Web APIs
family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">wheelevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor wheelevent() creates a wheelevent object. properties this interface inherits properties from its ancestors, mouseevent, uievent, and event. wheelevent.deltaxread only re
turns a double representing the horizontal scroll amount. wheelevent.deltayread only re
turns a double representing the vertical scroll amount. wheelevent.deltazread only re
turns a double representing the scroll amount for the z-axis. wheelevent.deltamoderead only re
turns an unsigned long representing the unit of the delta* values' scroll amount. permitted values are: constant ...
Window.applicationCache - Web APIs
important: application cache is deprecated as of firefox 44, and is no longer available in insecure contexts from firefox 60 onwards (bug 1354175, currently nightly/beta only). don't use it to offline websites — consider using service workers instead. re
turns a reference to the application cache object for the window. syntax cache = window.applicationcache parameters cache is an object reference to an offlineresourcelist. specification html 5wd ...
window.cancelAnimationFrame() - Web APIs
the window.cancelanimationframe() method cancels an animation frame request previously scheduled through a call to window.requestanimationframe(). syntax window.cancelanimationframe(requestid); parameters requestid the id value re
turned by the call to window.requestanimationframe() that requested the callback. examples var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.msrequestanimationframe; var cancelanimationframe = window.cancelanimationframe || window.mozcancelanimationframe; var start = window.mozanimationstarttime; // only supported in ff. other browsers can use something like date.now(). var myreq; function step(timestamp) { var progress = timestamp -...
Window.clearImmediate() - Web APIs
this method clears the action specified by window.setimmediate. this method is not expected to become standard, and is only implemented by recent builds of internet explorer and node.js 0.10+. it meets resistance both from gecko (firefox) and webkit (google/apple). syntax window.clearimmediate( immediateid ) where immediateid is a id re
turned by window.setimmediate. examples let immediateid = setimmediate(() => { // run some code } document.getelementbyid("button") .addeventlistener(() => { clearimmediate(immediateid); }); specifications specification status comment efficient script yielding the definition of 'setimmediate' in that specification. editor's draft initial definition. ...
Window.close() - Web APIs
hod closes the current window, or the window on which it was called. this method can only be called on windows that were opened by a script using the window.open() method. if the window was not opened by a script, an error similar to this one appears in the console: scripts may not close windows that were not opened by script. note also that close() has no effect when called on window objects re
turned by htmliframeelement.contentwindow. syntax window.close(); examples closing a window opened with window.open() this example shows a method which opens a window and a second one which closes the window; this demonstrates how to use window.close() to close a window opened by calling window.open(). //global var to store a reference to the opened window var openedwindow; function op...
Window.confirm() - Web APIs
the window.confirm() method displays a modal dialog with an optional message and two buttons: ok and cancel. syntax result = window.confirm(message); parameters message a string you want to display in the alert dialog. re
turn value a boolean indicating whether ok (true) or cancel (false) was selected. if a browser is ignoring in-page dialogs, then the re
turned value is always false. example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not ov...
Window.console - Web APIs
these methods are intended for debugging purposes only and should not be relied on for presenting information to end users. examples logging to console the first example logs text to the console. console.log("an error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough examples. specifications specification status comment console api living standard initial definition. ...
Window.content - Web APIs
n a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. note: since firefox 57 (initially nightly-only), both the content and _content variants are only available to chrome (privileged) code, and not available to the web anymore. re
turns a window object for the primary content window. this is useful in xul windows that have a <browser> (or tabbrowser or <iframe>) with type="content-primary" attribute on it — the most famous example is firefox main window, browser.xul. in such cases, content re
turns a reference to the window object for the document currently displayed in the browser. it is a shortcut for browserref.contentwindo...
Window.controllers - Web APIs
syntax controllers = window.controllers controllers is an object of type xulcontrollers (nsicontrollers). specification xul-specific. not part of specification. by default, a window's controller contains the code that supports the global window commands. chrome code can add controllers (to be used in conjunction with the godocommand and goupdatecommand functions in globaloverlay.js). however, the added controllers must be explicitly removed when the window is unloaded, as this is not done automatically. ...
Window.convertPointFromNodeToPage() - Web APIs
given a point specified in a particular dom node's coordinate system, the window method convertpointfromnodetopage() re
turns a point which specifies the same position in the page's coordinate system. this method is non-standard and should not be used. please review the browser compatibility section before using this method, as it's not widely supported (nor is the point object it uses). syntax point = window.convertpointfromnodetopage(node, nodepoint); parameters node the node in whose coordinate system the point specified by nodepoint is described. nodepoint a point object describing a point in node's coordinate system; this point will be converted to the page's coordinate system. re
turn value a point object specifying a point in the page's coordinate system. specifications...
Window.convertPointFromPageToNode - Web APIs
given a point specified in the page's coordinate system, the window method convertpointfrompagetonode() re
turns a point object specifying the same location in the coordinate system of the specified dom node. please review the browser compatibility section before using this method, as it's not widely supported (nor is the point object it uses). syntax point = window.convertpointfrompagetonode(node, pagepoint); parameters node the node into whose coordinate system the point is to be converted. pagepoint a point object specifying a point in the coordinate system of the page, which is to be converted into the node's coordinate system. re
turn value a point object describing the specified location in the node's coordinate system. specifications this method was specified in the de...
Window.customElements - Web APIs
the customelements read-only property of the window interface re
turns a reference to the customelementregistry object, which can be used to register new custom elements and get information about previously registered custom elements. examples the most common example you'll see of this property being used is to get access to the customelementregistry.define() method to define and register a new custom element, e.g.: let customelementregistry = window.customelements; customelementregistry.define('my-custom-element', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') ...
Window.directories - Web APIs
obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)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. summary re
turned the window personalbar toolbar object. use the window.personalbar instead. syntax var dirbar = window.directories; parameters dirbar is an object of the type barprop. example <script> function dirs() { alert(window.directories); } </script> specification not part of specification. ...
Window.document - Web APIs
example console.log(window.document.title); specifications specification status comment html living standardthe definition of 'window.document' in that specification. living standard html5the definition of 'window.document' in that specification. ...
Window.external - Web APIs
however, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec. methods the external object has the following methods: method description addsearchprovider(descriptionurl) dummy function; does nothing. see autodiscovery of search plugins. issearchproviderinstalled() dummy function; does nothing. ...
Window.find() - Web APIs
r which to search. acasesensitive boolean. if true, specifies a case-sensitive search. abackwards boolean. if true, specifies a backward search. awraparound boolean. if true, specifies a wrap around search. awholeword unimplemented boolean. if true, specifies a whole word search. this is not implemented; see bug 481513. asearchinframes boolean. if true, specifies a search in frames. re
turns true if the string is found; otherwise, false. example javascript findstring = function findtext(text) { alert("string \x22" + text + "\x22 found? " + window.find(text)); } html <p>apples, bananas, and oranges.</p> <button type="button" onclick='findstring("apples")'>search for apples</button> <button type="button" onclick='findstring("banana")'>search for banana</button> <button type="b...
Window.focus() - Web APIs
makes a request to bring the window to the front. it may fail due to user settings and the window isn't guaranteed to be frontmost before this method re
turns. syntax window.focus() example if (clicked) { window.focus(); } specification specification status comment html living standardthe definition of 'window.focus()' in that specification. living standard ...
Window.forward() - Web APIs
moves the window one document forward in history. this was a firefox-specific method and was removed in firefox 31. note: use the standard window.history.forward() method instead. syntax window.forward(); parameters none re
turn value undefined. example function goforward() { if (cangoforward) { window.forward(); } } specification this is not part of any specification. ...
Window.frameElement - Web APIs
note: despite this property's name, it works for documents embedded within any embedding point, including <object>, <iframe>, or <embed>. syntax const frameel = window.frameelement value the element which the window is embedded into. if the window isn't embedded into another document, or if the document into which it's embedded has a different origin, the value is null instead. ...
Window.frames - Web APIs
re
turns the window itself, which is an array-like object, listing the direct sub-frames of the current window. syntax framelist = window.frames; framelist is a list of frame objects. it is similar to an array in that it has a length property and its items can be accessed using the [i] notation. framelist === window evaluates to true. each item in the window.frames pseudo-array represents the window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame dom element (i.e., window.frames[0] is the same thing as document.getelementsbytagname("iframe")[0].contentwindow). for more details about the re
turned value, refer to this thread on mozilla.dev.platform. example var frames = window.frames; // or // var frames = window.parent.frames; for (var i = 0; i < ...
Window.fullScreen - Web APIs
played in full screen mode or not. syntax isinfullscreen = windowref.fullscreen; with chrome privileges, the property is read-write, otherwise it is read-only. bear in mind that if you try to set this property without chrome privileges, it will not throw an exception and instead just silently fail. this is to prevent scripts designed to set this property in internet explorer from breaking. re
turn value isinfullscreen a boolean. possible values: true: the window is in full screen mode. false: the window is not in full screen mode. notes switching between regular window and full screen will fire the "resize" event on the corresponding window. example if (window.fullscreen) { // it's fullscreen! } else { // not fullscreen! } ...
Window.history - Web APIs
see manipulating the browser history for examples and details. in particular, that article explains security features of the pushstate() and replacestate() methods that you should be aware of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. ...
Window.home() - Web APIs
obsolete since gecko 31 (firefox 31 / thunderbird 31 / seamonkey 2.28)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the window.home() method re
turns the window to the home page. syntax window.home(); example function gohome() { window.home(); } specification dom level 0. not part of specification. ...
Window.length - Web APIs
syntax framescount = window.length; framescount is the number of frames. example if (window.length) { // this is a document with subframes } specifications specification status comment html living standardthe definition of 'window.length' in that specification. living standard html5the definition of 'window.length' in that specification. ...
Window.locationbar - Web APIs
syntax objref = window.locationbar example the following complete html example shows how the visible property of the locationbar object is used. <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>various dom tests</title> <script> var visible = window.locationbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.locationbar' in that specification. living standard html5the definition of 'window.locationbar' in that specification. ...
Window.matchMedia() - Web APIs
the window interface's matchmedia() method re
turns a new mediaquerylist object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query. syntax mqlist = window.matchmedia(mediaquerystring) parameters mediaquerystring a string specifying the media query to parse into a mediaquerylist. re
turn value a new mediaquerylist object for the media query. use this object's properties and events to detect matches and to monitor for changes to those matches over time. usage notes you can use the re
turned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. to perform a one-time, instantaneous check to see if t...
Window.menubar - Web APIs
syntax objref = window.menubar example the following complete html example demonstrates how the visible property of the menubar object is used. <html> <head> <title>various dom tests</title> <script> var visible = window.menubar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.menubar' in that specification. living standard html5the definition of 'window.menubar' in that specification. ...
Window.mozAnimationStartTime - Web APIs
this value should be used instead of, for example, date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another. ...
Window.navigator - Web APIs
the window.navigator read-only property re
turns a reference to the navigator object, which has methods and properties about the application running the script. syntax navigatorobject = window.navigator examples example #1: browser detect and re
turn a string var sbrowser, susrag = navigator.useragent; // the order matters here, and this may report false positives for unlisted browsers. if (susrag.indexof("firefox") > -1) { sbrowser = "mozilla firefox"; // "mozilla/5.0 (x11; ubuntu; linux x86_64; rv:61.0) gecko/20100101 firefox/61.0" } else if (susrag.indexof("samsungbrowser") > -1) { sbrowser = "samsung internet"; // "mozilla/5.0 (linux; android 9; samsung sm-g955f build/ppr1.180610.011) applewebkit/537.36 (khtml, like gecko) samsungbrowser/9.4 chrome/67.0.3396.87 mobile safari/...
Privileged features - Web APIs
titlebar). dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. they are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. on mac systems, dialog windows have a different window border and they may get
turned into a sheet. modal if on, the new window is said to be modal. the user cannot re
turn to the main window until the modal window is closed. a typical modal window is created by the alert() function. the exact behavior of modal windows depends on the platform and on the mozilla release version. note: as of gecko 1.9, the internet explorer equivalent to this feature is the window.showmodaldi...
Window.opener - Web APIs
the window interface's opener property re
turns a reference to the window that opened the window using open(). in other words, if window a opens window b, b.opener re
turns a. syntax const openerwindow = window.opener value a window referring to the window that opened the current window (using window.open(), or by a link with target attribute set). if this window was not opened by being linked to or created by another, re
turns null. in modern browsers, a rel="noopener noreferrer" attribute on the originating <a> element will prevent the window.opener reference from being set, in which case this property will re
turn null. specifications specification status comment html living standardthe definition of 'window.opener' in that specification. living standard...
Window.orientation - Web APIs
its only possible values are -90, 0, 90, and 180. positive values are clockwise; negative values are counterclockwise. specifications specification status comment compatibility standardthe definition of 'window.orientation' in that specification. ...
Window.outerHeight - Web APIs
notes to change the size of a window, see window.resizeby() and window.resizeto(). to get the inner height of a window, i.e. the height of the page being displayed, see window.innerheight. graphical example the following figure shows the difference between outerheight and innerheight. ...
Window.outerWidth - Web APIs
it represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles. notes to change the size of a window, see window.resizeby() and window.resizeto(). to get the inner width of a window, i.e. the width of the page being displayed, see window.innerwidth. specification specification status comment css object model (cssom) view modulethe definition of 'window.outerwidth' in that specification. ...
Window.pageYOffset - Web APIs
the read-only window property pageyoffset is an alias for scrolly; as such, it re
turns the number of pixels the document is currently scrolled along the vertical axis (that is, up or down) with a value of 0.0, indicating that the top edge of the document is currently aligned with the top edge of the window's content area. there is slightly better support for pageyoffset than for scrolly in older browsers, but if you're not concerned about browsers more than a handful of years old, you can use either one. the corresponding pagexoffset property, which re
turns the number of pixels scrolled along the horizontal axis (left and right), is an alias for scrollx. syntax yoffset = window.pageyoffset; value a floating-point number specifying the number of pixels the document is scrolled verticall...
Window: pageshow event - Web APIs
the pageshow event is sent to a window when the browser displays the window's document due to navigation. this includes: initially loading the page navigating to the page from another page in the same window or tab restoring a frozen page on mobile oses re
turning to the page using the browser's forward or back buttons during the initial page load, the pageshow event fires after the load event. bubbles no cancelable no interface pagetransitionevent event handler property onpageshow examples this example sets up event handlers for events listed in the array events. the handler, eventlogger(), logs the type of event that occurred to the console, and includes the value of the persisted flag on pageshow and pagehide events. javasc...
Window.performance - Web APIs
it serves as the point of exposure for the performance timeline api, the high resolution time api, the navigation timing api, the user timing api, and the resource timing api. syntax performancedata = window.performance; value a performance object offering access to the performance and timing-related information offered by the apis it exposes. specifications specification status comment high resolution timethe definition of 'window.performance' in that specification. ...
Window.personalbar - Web APIs
syntax objref =window.personalbar example fixme: https://bugzilla.mozilla.org/show_bug.cgi?id=790023 the following complete html example shows the way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window. due to deprecation of enableprivilege this functionality can not be used in web pages. enableprivilege is disabled in firefox 15 and will be removed in firefox 17. ...
Window.pkcs11 - Web APIs
obsolete since gecko 29 (firefox 29 / thunderbird 29 / seamonkey 2.26)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. summary re
turns the pkcs11 object, which is used to install drivers and other software associated with the pkcs11 protocol. if pkcs11 isn't supported, this property re
turns null. note: this property has been re
turned null since gecko 1.9.0.14 (firefox 3.0.14) and removed in gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)) for security reasons. for more information on installing pkcs11 modules, see installing pkcs11 modules. see bug 326628 for details on why the property was removed. syntax objref = window.pkcs11 example window.pkcs11.addmodule(smod, ...
Window: popstate event - Web APIs
tain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string re
turned by its document.title attribute. if the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so. the entry is now said to have "persisted user state." this information the browser might add to the history session entry may include, for instance, the document's scroll position, the values of form inputs, and other such data. if ne...
Window.print() - Web APIs
syntax window.print() specification specification status comment html living standardthe definition of 'print()' in that specification. living standard browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
Window.requestAnimationFrame() - Web APIs
on will progress in a frame, otherwise the animation will run faster on high refresh rate screens. check the example below for a way to do this. syntax window.requestanimationframe(callback); parameters callback the function to call when it's time to update your animation for the next repaint. the callback function is passed one single argument, a domhighrestimestamp similar to the one re
turned by performance.now(), indicating the point in time when requestanimationframe() starts to execute callback functions. re
turn value a long integer value, the request id, that uniquely identifies the entry in the callback list. this is a non-zero value, but you may not make any other assumptions about its value. you can pass this value to window.cancelanimationframe() to cancel the refresh cal...
window.requestIdleCallback() - Web APIs
meout elapses. you can call requestidlecallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. a timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. syntax var handle = window.requestidlecallback(callback[, options]) re
turn value an id which can be used to cancel the callback by passing it into the window.cancelidlecallback() method. parameters callback a reference to a function that should be called in the near future, when the event loop is idle. the callback function is passed an idledeadline object describing the amount of time available and whether or not the callback has been run because the timeout peri...
Window: resize event - Web APIs
bubbles no cancelable no interface uievent event handler property onresize in some earlier browsers it was possible to register resize event handlers on any html element. it is still possible to set onresize attributes or use addeventlistener() to set a handler on any element. however, resize events are only fired on the window object (i.e. re
turned by document.defaultview). only handlers registered on the window object will receive resize events. there is a proposal to allow all elements to be notified of resize changes. see resize observer to read the draft document, and github issues to read the on-going discussions. examples window size logger the following example reports the window size each time it is resized. bear in mind that ...
Window.screen - Web APIs
the screen object, implementing the screen interface, is a special object for inspecting properties of the screen on which the current window is being rendered. syntax let screenobj = window.screen; example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screen' in that specification. ...
Window.scrollMaxX - Web APIs
syntax xmax = window.scrollmaxx xmax is the number of pixels. example // scroll to right edge of the page let maxx = window.scrollmaxx; window.scrollto(maxx, 0); notes do not use this property to get the total document width, which is not equivalent to window.innerwidth + window.scrollmaxx, because window.innerwidth includes the width of any visible vertical scrollbar, thus the result would exceed the total document width by the width of any visible vertical scrollbar. instead use document.body.scrollwidth. see also window.scrollmaxy. ...
Window.scrollMaxY - Web APIs
syntax ymax = window.scrollmaxy ymax is the number of pixels. example // scroll to the bottom of the page let maxy = window.scrollmaxy; window.scrollto(0, maxy); notes do not use this property to get the total document height, which is not equivalent to window.innerheight + window.scrollmaxy, because window.innerheight includes the width of any visible horizontal scrollbar, thus the result would exceed the total document height by the width of any visible horizontal scrollbar. instead use document.body.scrollheight. see also window.scrollmaxx and window.scrollto. ...
Window.scrollbars - Web APIs
syntax objref = window.scrollbars example the following complete html example shows how the visible property of the scrollbars object is used. <!doctype html> <html> <head> <title>various dom tests</title> <script> let visiblescrollbars = window.scrollbars.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> specifications specification status comment html living standardthe definition of 'window.scrollbars' in that specification. ...
Window.self - Web APIs
it can be used with dot notation on a window object (that is, window.self) or standalone (self). the advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in web workers. by using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to workerglobalscope.self). example uses of window.self like the following could just as well be replaced by window. ...
Window.sidebar - Web APIs
obsolete since firefox 23 (only present in seamonkey). end users can use the "load this bookmark in the sidebar" option instead. also see creating a firefox sidebar. addpersistentpanel(title, contenturl, "") adds a sidebar panel, which is able to work in the background. addsearchprovider(descriptionurl) dummy function; does nothing. see autodiscovery of search plugins. ...
Window.speechSynthesis - Web APIs
syntax var synth = window.speechsynthesis; value a speechsynthesis object. examples in our basic speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis. after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want. ...
Worker.terminate() - Web APIs
example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated. ...
WorkerGlobalScope.console - Web APIs
the console read-only property of the workerglobalscope interface re
turns a console object providing access to the browser console for the worker. syntax var consoleobj = self.console; value a console object. example this property allows you to have access to a browser console for debugging purposes, inside a worker. so for example you could call console.log('test'); inside a worker (which would basically be the equivalent of self.console.log('test');, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), to re
turn a test message out to the browser console. if you are calling console.log() from a dedicatedworkerglobalscope or other worker scope that acts on a single loaded window, that tab's web console will receive the logs. however, ...
WorkerGlobalScope.dump() - Web APIs
example to write an output from your worker to your computer's terminal, you first have to run an instance of firefox started from your command line/terminal. ...
WorkerGlobalScope.importScripts() - Web APIs
the importscripts() method of the workerglobalscope interface synchronously imports one or more scripts into the worker's scope. syntax self.importscripts('foo.js'); self.importscripts('foo.js', 'bar.js', ...); parameters a comma-separated list of domstring objects representing the scripts to be imported. these paths are relative to html document base url. re
turn value none. exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e. text/javascript). example if you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importscripts('foo.js'); importscripts() and self.importscripts() are effectively equivalent — both represent importscripts(...
WorkerGlobalScope.self - Web APIs
most of the time it is a specific scope like dedicatedworkerglobalscope, sharedworkerglobalscope, or serviceworkerglobalscope. syntax var selfref = self; value a global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
WorkerNavigator.permissions - Web APIs
syntax permissionsobj = self.permissions value a permissions object. examples self.navigator.permissions.query({name:'notifications'}).then(function(result) { if (result.state === 'granted') { shownotification(); } else if (result.state === 'prompt') { requestnotificationpermission() } }); specification specification status comment permissions working draft initial definition. browser support the compatibility table on this page is generated from structured data. ...
Worklet.addModule() - Web APIs
ng containing the url of a javascript file with the module to add. options optional an object with any of the following options: credentials: a requestcredentials value that indicates whether to send credentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. re
turn value a promise that resolves once the module from the given url has been added. the promise doesn't re
turn any value. exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler. aborterror the specified script is invalid or could not be loaded. syntaxerror the specified moduleurl is invalid. examples audioworklet example ...
WritableStream.abort() - Web APIs
the abort() method of the writablestream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. syntax var promise = writablestream.abort(reason); parameters reason a domstring providing a human-readable reason for the abort. re
turn value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... // abort the stream later on, when required writablestream.abort(); spec...
WritableStream.locked - Web APIs
the locked read-only property of the writablestream interface re
turns a boolean indicating whether the writablestream is locked to a writer. syntax var locked = writablestream.locked; value a boolean indicating whether or not the writable stream is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); writablestream.locked // should re
turn true, as the stream has been locked to a writer specifications specification status comment streamsthe definition of 'locked' in that specification. living standard initial definition. ...
WritableStreamDefaultController.error() - Web APIs
the error() method of the writablestreamdefaultcontroller interface causes any future interactions with the associated stream to error. this method is rarely used, since usually it suffices to re
turn a rejected promise from one of the underlying sink’s methods. however, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. syntax writablestreamdefaultcontroller.error(e); parameters e a domstring representing the error you want future interactions to fail with. re
turn value undefined. exceptions typeerror the stream you are trying to error is not a writablestream. examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // ...
WritableStreamDefaultWriter.abort() - Web APIs
the abort() method of the writablestreamdefaultwriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. if the writer is active, the abort() method behaves the same as that for the associated stream (writablestream.abort()). if not, it re
turns a rejected promise. syntax var promise = writablestreamdefaultwriter.abort(reason); parameters reason optional a domstring representing a human-readable reason for the abort. re
turn value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new ...
WritableStreamDefaultWriter.closed - Web APIs
syntax var closed = writablestreamdefaultwriter.closed; value a promise. examples const writablestream = new writablestream({ start(controller) { }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); .. ...
WritableStreamDefaultWriter.ready - Web APIs
syntax var promise = writablestreamdefaultwriter.ready; value a promise. example the following example shows two uses of the ready property. the first uses ready to ensure that the writablestream is done writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. ...
WritableStreamDefaultWriter.releaseLock() - Web APIs
of the writablestreamdefaultwriter interface releases the writer's lock on the corresponding stream. after the lock is released, the writer is no longer active. if the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. syntax writablestreamdefaultwritere.releaselock() parameters none. re
turn value undefined. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // release writer's lock on the stream when desired writer.releaselock(); specifications specification status comment streamsthe definition of...
XDomainRequest.responseText - Web APIs
note: this property is valid during the xdomainrequest.onprogress and xdomainrequest.onload events. syntax var response = xdr.responsetext; this sets response to contain the response body of the request, as a string. ...
XDomainRequest - Web APIs
tion of http access control (cors) that worked in internet explorer 8 and 9. it was removed in internet explorer 10 in favor of using xmlhttprequest with proper cors; if you are targeting internet explorer 10 or later, or wish to support any other browser, you need to use standard http access control. this interface can send both get and post requests. syntax var xdr = new xdomainrequest(); re
turns a new xdomainrequest object, which can then be used to make and manage these requests. properties xdomainrequest.timeout gets or sets the amount of time until a request times out. xdomainrequest.responsetext gets the response body as a string. methods xdomainrequest.open() opens the request, specifing the method (get/post) and url. xdomainrequest.send() sends the request. post dat...
Synchronous and asynchronous requests - Web APIs
ty function loadfile declares (i) a target url to read (via an http get request), (ii) a function to execute on successful completion of the xhr operation, and (iii) an arbitrary list of additional arguments that are passed through the xhr object (via the arguments property) to the success callback function. line 1 declares a function invoked when the xhr operation completes successfully. it, in
turn, invokes the callback function specified in the invocation of the loadfile function (in this case, the function showmessage) which has been assigned to a property of the xhr object (line 11). the additional arguments (if any) supplied to the invocation of function loadfile are "applied" to the running of the callback function. line 5 declares a function invoked when the xhr operation fails to co...
XMLHttpRequest() - Web APIs
the object must be prepared by at least calling open() to initialize it before calling send() to send the request to the server. non-standard firefox syntax firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see bug 692677). ...
XMLHttpRequest.abort() - Web APIs
the xmlhttprequest.abort() method aborts the request if it has already been sent. when a request is aborted, its readystate is changed to xmlhttprequest.unsent (0) and the request's status code is set to 0. syntax xmlhttprequest.abort() parameters none. re
turn value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort(). var xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.send(); if (oh_noes_we_need_to_cancel_right_now_or_else) { xhr.abort(); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest: abort event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest: error event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest: load event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest: loadend event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest: loadstart event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest.open() - Web APIs
er[, 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 re
turn until the response is received. if true, notification of a completed transaction is provided using event listeners. this must be true if the multipart attribute is true, or an exception will be thrown. note: synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous xhr support on the main thre...
XMLHttpRequest.overrideMimeType() - Web APIs
le, to force a stream to be treated and parsed as "text/xml", even if the server does not report it as such. this method must be called before calling send(). syntax xmlhttprequest.overridemimetype(mimetype) parameters mimetype a domstring specifying the mime type to use instead of the one specified by the server. if the server doesn't specify a type, xmlhttprequest assumes "text/xml". re
turn value undefined. example this example specifies a mime type of "text/plain", overriding the server's stated type for the data being received. note: if the server doesn't provide a content-type header, xmlhttprequest assumes that the mime type is "text/xml". if the content isn't valid xml, an "xml parsing error: not well-formed" error occurs. you can avoid this by calling overridemimetype() t...
XMLHttpRequest: progress event - Web APIs
r.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); re
turn xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg').abort(); }); result specifi...
XMLHttpRequest.readyState - Web APIs
an xhr client exists in one of the following states: value state description 0 unsent client has been created. open() not called yet. 1 opened open() has been called. 2 headers_received send() has been called, and headers and status are available. 3 loading downloading; responsetext holds partial data. 4 done the operation is complete. unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet. opened open() method has been invoked. ...
XMLHttpRequest.response - Web APIs
syntax var body = xmlhttprequest.response; value an appropriate object based on the value of responsetype. you may attempt to request the data be provided in a specific format by setting the value of responsetype after calling open() to initialize the request but before calling send() to send the request to the server. ...
XMLHttpRequest.responseText - Web APIs
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"). ...
XMLHttpRequest.responseType - Web APIs
alue of text is used. syntax var type = xmlhttprequest.responsetype; xmlhttprequest.responsetype = type; value a string taken from the xmlhttprequestresponsetype enum which specifies what type of data the response contains. when setting responsetype to a particular value, the author should make sure that the server is actually sending a response compatible with that format. if the server re
turns data that is not compatible with the responsetype that was set, the value of response will be null. the values supported by responsetype are the following: "" an empty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document ...
XMLHttpRequest.responseXML - Web APIs
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. ...
XMLHttpRequest.sendAsBinary() - Web APIs
ly use the send() method, which now supports binary data in various forms. syntax xmlhttprequest.sendasbinary(binarystring); parameters binarystring a domstring which encodes the binary content to be sent. you can create the binary string using the filereader method readasbinarystring(). the string is converted to binary for transfer by removing the high-order byte of each character. re
turn value undefined. polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arrays. /*\ |*| |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() |*| \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest...
XMLHttpRequest.setRequestHeader() - Web APIs
y access-control-allow-headers in preflight response" exception when you send requests across domains. in this situation, you need to set up the access-control-allow-headers in your response header at server side. syntax xmlhttprequest.setrequestheader(header, value) parameters header the name of the header whose value is to be set. value the value to set as the body of the header. re
turn value undefined. specifications specification status comment xmlhttprequestthe definition of 'setrequestheader()' in that specification. living standard whatwg living standard ...
XMLHttpRequest.status - Web APIs
before the request completes, the value of status is 0. browsers also report a status of 0 in case of xmlhttprequest errors. ...
XMLHttpRequest.statusText - Web APIs
unlike xmlhttprequest.status which indicates a numerical status code, this property contains the text of the response status, such as "ok" or "not found". if the request's readystate is in unsent or opened state, the value of statustext will be an empty string. if the server response doesn't explicitly specify a status text, statustext will assume the default value "ok". ...
XMLHttpRequest.upload - Web APIs
it is an opaque object, but because it's also an xmlhttprequesteventtarget, event listeners can be attached to track its process. the following events can be triggered on an upload object and used to monitor the upload: event event listener description loadstart onloadstart the upload has begun. progress onprogress periodically delivered to indicate the amount of progress made so far. abort onabort the upload operation was aborted. error onerror the upload failed due to an error. load onload the upload completed successfully. ...
XMLHttpRequestEventTarget - Web APIs
l;} properties xmlhttprequesteventtarget.onabort contains the function to call when a request is aborted and the abort event is received by this object. xmlhttprequesteventtarget.onerror contains the function to call when a request encounters an error and the error event is received by this object. xmlhttprequesteventtarget.onload contains the function to call when an http request re
turns after successfully fetching content and the load event is received by this object. xmlhttprequesteventtarget.onloadstart contains the function that gets called when the http request first begins loading data and the loadstart event is received by this object. xmlhttprequesteventtarget.onprogress contains the function that is called periodically with information about the progress of the requ...
XMLHttpRequestResponseType - Web APIs
domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. deprecated values moz-chunked-arraybuffer a firefox-only value which instructs xmlhttprequest to deliver arraybuffer objects containing chunks of the incoming data. accessing response during a progress event re
turns the data received so far. outside the progress event handler, the value of response is always null. you shouldn't use this non-standard (and, as of firefox 68, entirely removed) api; instead, consider using the fetch api with readable streams, which offers a standard alternative to accessing the response in a streaming fashion. specifications specification status comment ...
XMLSerializer - Web APIs
the xmlserializer interface provides the serializetostring() method to construct an xml string representing a dom tree. methods serializetostring() re
turns the serialized subtree of a string. serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified. examples serializing xml into a string the first, basic, example just serializes an entire document into a string containing xml. var s = new xmlserializer(); var d = document; var str = s.serializetostring(d); savexml(str); this involves creating a new xmlserializer object, then passing the document to be serialized into serializetostring(), which re
turns the xml equivalent of the document. inserting nodes into a dom based on xml this example uses the el...
XPathEvaluator.createExpression() - Web APIs
be used for (repeated) evaluations of the xpath expression. syntax xpathexpression xpathevaluator.createexpression(expression, resolver); parameters expression a domstring representing representing the xpath expression to be created. resolver optional permits translation of all prefixes, including the xml namespace prefix, within the xpath expression into appropriate namespace uris. re
turn value a xpathexpression representing the compiled form of the xpath expression. exceptions invalid_expression_err if the expression is not legal according to the rules of the xpathevaluator, an xpathexception of type invalid_expression_err is raised. namespace_err if the expression contains namespace prefixes which cannot be resolved by the specified xpathnsresolver, a domexception of type ...
XPathEvaluator.createNSResolver() - Web APIs
el 3 method node.lookupnamespaceuri() in resolving the namespace uri from a given prefix using the current information available in the node's hierarchy at the time the method is called, also correctly resolving the implicit xml prefix. syntax xpathnsresolver xpathevaluator.creatensresolver(noderesolver); parameters noderesolver a node to be used as a context for namespace resolution. re
turn value an xpathnsresolver object which resolves namespaces with respect to the definitions in scope for a specified node. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.creatensresolver()' in that specification. recommendation initial definition ...
XPathEvaluator - Web APIs
he document interface. methods xpathevaluator.createexpression() creates a parsed xpath expression with resolved namespaces. xpathevaluator.creatensresolver() adapts any dom node to resolve namespaces allowing the xpath expression to be evaluated relative to the context of the node where it appeared within the document. xpathevaluator.evaluate() evaluates an xpath expression string and re
turns a result of the specified type if possible. example the following example shows the use of the xpathevaluator interface. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered...
XPathException - Web APIs
in the dom xpath api the xpathexception interface represents exception conditions that can be encountered while performing xpath operations. properties xpathexception.code read only re
turns a short that contains one of the error code constants. constants constant value description invalid_expression_err 51 if the expression has a syntax error or otherwise is not a legal expression according to the rules of the specific xpathevaluator or contains specialized extension functions or variables not supported by this implementation. type_err 52 if the expression cannot be converted to re
turn the specified type. specifications specification status comment document object model (dom) level 3 xpath specificationt...
XPathExpression.evaluate() - Web APIs
the evaluate() method of the xpathexpression interface executes an xpath expression on the given node or document and re
turns an xpathresult. syntax xpathresult node.evaluate(contextnode, type, result); parameters contextnode a node representing the context to use for evaluating the expression. type optional specifies the type of result to be re
turned by evaluating the expression. this must be one of the xpathresult.constants. result optional allows to specify a result object which may be reused and re
turned by this method. if this is specified as null or the implementation does not reuse the specified result, a new result object will be re
turned. re
turn value an xpathresult object representing the result of evaluating the xpath expression. exceptions invalid_expression_err ...
XPathExpression - Web APIs
this is useful when an expression will be reused in an application, because it is just compiled once and all namespace prefixes which occur within the expression are preresolved. objects of this type are created by calling xpathevaluator.createexpression(). methods xpathexpression.evaluate() evaluates the xpath expression on the given node or document. example the following example shows the use of the xpathexpression interface. ...
XPathNSResolver.lookupNamespaceURI() - Web APIs
the lookupnamespaceuri method looks up the namespace uri associated to the given namespace prefix within an xpath expression evaluated by the xpathevaluator interface. syntax domstring xpathnsresolver.lookupnamespaceuri(prefix); parameters prefix a domstring representing the prefix to look for. re
turn value a domstring representing the associated namespace uri or null if none is found. specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathnsresolver.lookupnamespaceuri()' in that specification. recommendation initial definition ...
XPathResult.invalidIteratorState - Web APIs
the read-only invaliditeratorstate property of the xpathresult interface signifies that the iterator has become invalid. it is true if xpathresult.resulttype is unordered_node_iterator_type or ordered_node_iterator_type and the document has been modified since this result was re
turned. note: this feature is available in web workers. syntax var iteratorstate = result.invaliditeratorstate; re
turn value a boolean value indicating whether the iterator has become invalid. example the following example shows the use of the invaliditeratorstate property. html <div>xpath example</div> <p>iterator state: <output></output></p> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); // invalidates the iterator state document.queryse...
XPathResult.resultType - Web APIs
constants result type defined constant value description any_type 0 a result set containing whatever type naturally results from evaluation of the expression. ...
XPathResult.snapshotLength - Web APIs
exceptions type_err in case xpathresult.resulttype is not unordered_node_snapshot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotlength property. ...
XRFrame.getViewerPose() - Web APIs
the getviewerpose() method, a member of the xrframe interface, re
turns a xrviewerpose object which describes the viewer's pose (position and orientation) relative to the specified reference space. see the getpose() method for a way to calculate a pose that represents the difference between two spaces. syntax var xrviewerpose = xrframe.getviewerpose(referencespace); parameters referencespace an xrreferencespace object specifying the space to use as the reference point or base for the computation of the viewer's current pose. re
turn value a xrviewerpose describing the viewer's position and orientation relative to the specified reference space. exceptions invalidstateerror a domexception indicating that getviewerpose() was not called within the context of a callback to...
XRFrame.session - Web APIs
syntax var xrsession = xrframe.session; value a xrsession object representing the webxr session for which this xrframe describes the object positions and orientations. ...
XRFrame - Web APIs
sition and orientation in space, and getpose() can be used to create an xrpose describing the relative position of one xrspace relative to another. properties session read only the xrsession that for which this xrframe describes the tracking details for all objects. the information about a specific object can be obtained by calling one of the methods on the object. methods getpose() re
turns an xrpose object representing the spatial relationship between the two specified xrspace objects. getviewerpose() re
turns an xrviewerpose describing the viewer's position and orientation in a given xrreferencespace. specifications specification status comment webxr device apithe definition of 'xrframe' in that specification. working draft initial definition...
XRFrameRequestCallback - Web APIs
the xrframerequestcallback is a callback function passed into xrsession.requestanimationframe (part of webxr api) to obtain the current time and the current xrframe. syntax function xrframerequestcallback(time, xrframe){ // process xrframe here } xrsession.requestanimationframe(xrframerequestcallback) parameters domhighrestimestamp a timestamp corresponding to the re
turned xrframe. xrframe an xrframe representing a snapshot of the state of all of the tracked objects for the xrsession. re
turn value none. specifications specification status comment webxr device apithe definition of 'xrframerequestcallback' in that specification. working draft initial definition. ...
XRInputSource.profiles - Web APIs
the profile stings are listed in order of specificity, with the most specific profile listed first. note: the profiles list is always empty when the webxr session is in inline mode. syntax let profilelist = xrinputsource.profiles; value an array of domstring objects, each describing one configuration profile for the input device represented by the xrinputsource object. each input profile specifies the preferred visual representation and behavior of the input source. ...
XRInputSourceArray.forEach() - Web APIs
index number, you can omit this. sourcelist optional the xrinputsourcearray object which is being processed. if you don't need this information, you may omit this. thisarg optional the value to be used for this while executing the callback. note that if you use arrow function notation (=>) to provide the callback, you can omit thisarg, since all arrow functions lexically bind this. re
turn value undefined. examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. let inputsources = xrsession.inputsources; inputsources.foreach((input) => { if (input.gamepad) { checkgamepad(input.gamepad); } else { if (input.targetraymode === "tracked-pointer" && input.handedness === player.handedness)...
XRInputSourceArray.length - Web APIs
syntax let inputsourcecount = xrinputsourcearray.length; value an integer value indicating the number of xrinputsource objects representing webxr input sources are includled in the array. examples in this example, a game that requires at least one input source uses length to check this before proceeding to allow the user to play the game. ...
XRInputSourceEvent() - Web APIs
the xrinputsourceevent() constructor creates and re
turns a new xrinputsourceevent object describing an event (state change) which has occurred on a webxr user input device represented by an xrinputsource. syntax newinputsourceevent = new xrinputsourceevent(type, eventinitdict); parameters type a domstring indicating which of the input source events the new object will represent. permitted values are listed under event types below. eventinitdict an object based on the xrinputsourceeventinit dictionary which contains the values to assign to the new event's properties. re
turn value a new xrinputsourceevent object representing the event described by the given type and eventinitdict. event types select sent to an xrsession when the sending input source has fully completed a ...
XRInputSourceEvent - Web APIs
xrinputsourceevent interface describes an event which has occurred on a webxr user input device such as a hand controller, gaze tracking system, or motion tracking system. more specifically, they represent a change in the state of an xrinputsource. to learn more about handling inputs in a webxr project, see the article inputs and input sources. constructor xrinputsourceevent() creates and re
turns a new xrinputsourceevent object whose properties match those provided in the eventinitdict dictionary provided. properties frame read only an xrframe object providing the needed information about the event frame during which the event occurred. this frame may have been rendered in the past rather than being a current frame. because this is an event frame, not an animation frame, you canno...
XRInputSourcesChangeEvent() - Web APIs
the xrinputsourceschangeevent() constructor creates and re
turns a new xrinputsourceschangeevent object, representing an update to the list of available webxr input devices. you won't typically call this constructor yourself, as these events are created and sent to you by the webxr system. syntax newinputsourceschangeevent = new xrinputsourceschangeevent(type, eventinitdict); parameters type a domstring indicating the type of event which has occurred. this string must always be inputsourceschange. eventinitdict an object conforming to the xrinputsourceschangeeventinit dictionary, prodividing the initial values for the event. re
turn value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided. event types inputsourceschange delive...
XRPermissionDescriptor.requiredFeatures - Web APIs
mitted values are: the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
XRPermissionStatus.granted - Web APIs
e enumerated type. the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the re
turned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is optimized for this use case. for devices with six deg...
XRPermissionStatus - Web APIs
properties in addition to the properties listed below, xrpermissionstatus includes the properties defined by its parent interface, permissionstatus. granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was called. ...
XRPose.transform - Web APIs
is a xrrigidtransform object providing the position and orientation of the pose relative to the base xrspace as specified when the pose was obtained by calling xrframe.getpose(). syntax let posetransform = xrpose.transform; value an xrrigidtransform which provides the position and orientation of the xrpose relative to the xrframe to which this xrpose is aligned. this is the same pose that's re
turned by the frame's getpose() method. example this handler for the xrsession event select handles events for tracked pointers. it determines the targeted object by passing the event frame's pose into a function called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a valu...
XRReferenceSpaceEvent() - Web APIs
eventinitdict an object based on the xrreferencespaceeventinit dictionary, containing data used to initialize the new event object. the properties of this object are: referencespace the xrreferencespace from which the event originated. transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the new coordiante system. re
turn value a new xrreferencespaceevent object, initialized as defined by the input parameters. specifications specification status comment webxr device apithe definition of 'xrreferencespaceevent()' in that specification. working draft initial definition. ...
XRReferenceSpaceEvent - Web APIs
the webxr device api interface xrreferencespaceevent represents an event sent to an xrreferencespace. currently, the only event that uses this type is the reset event. constructor xrreferencespaceevent() re
turns a new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary. properties in addition to inheriting the properties available on the parent interface, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event. transform read only an xrrigidtransform object indicating the position and orientation of the specified referencespace's native origin after the event, defined relative to the c...
XRRigidTransform.inverse - Web APIs
the read-only inverse property of the xrrigidtransform interface re
turns another xrrigidtransform object which is the inverse of its owning transform. that is, you can always get the inverse of any xrrigidtransform using its inverse property, instead of having to explicitly generate it. syntax let transforminverse = xrrigidtransform.inverse; value an xrrigidtransform which contains the inverse of the xrrigidtransform on which it's accessed. applying the inverse of a transform to any object previously transformed by the parent xrrigidtransform always undoes the transformation, resulting in the object re
turning to its previous pose. in other words, its position and orientation both re
turn to their prior configurations. examples in this example, the model view matrix for an object is comp...
XRRigidTransform.orientation - Web APIs
specifying the rotational component of the transform represented by the object. if you specify a quaternion whose length is not exactly 1.0 meters, it will be normalized for you. syntax let orientation = xrrigidtransform.orientation; value a dompointreadonly object which contains a unit quaternion providing the orientation component of the transform. as a unit quaternion, the length of the re
turned quaternion is always 1.0 meters. examples to create a reference space which is oriented to look straight up, positioned 2 meters off of ground level: xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -2}, {x: 0.0, y: 1.0, z: 0.0, w: 1.0}); ); the unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object should be facing directly along ...
XRSession.onsqueezeend - Web APIs
on the user's dominant hand. in response to the end of the squeeze operation, this code looks to see if there is an object currently being held by the user by checking to see if the variable user.heldobject contains a reference to an object representing the held item. if heldobject has an object reference, that object is passed to a function called cancelobjectdrag(), which would be written to re
turn the object to its original position. this takes care of the situation in which the drag is aborted or canceled. xrsession.onsqueezeend = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace; if (user.heldobject) { cancelobjectdrag(user.heldobject); } } }; this code presumes...
XRSession.renderState - Web APIs
the information provided covers the minimum and maximum distance at which to render objects, the vertical field of view to use when rendering the in the inline session mode, and the xrwebgllayer to render into for inline composition. while this property is read only, you can call the xrsession method updaterenderstate() to make changes. syntax var xrrenderstate = xrsession.renderstate; value an xrrenderstate object describing how to render the scene. ...
XRSession.requestAnimationFrame() - Web APIs
two parameters: time a domhighrestimestamp indicating the time offset at which the updated viewer state was received from the webxr device. xrframe an xrframe object describing the state of the objects being tracked by the session. this can be used to obtain the poses of the viewer and the scene itself, as well as other information needed to render a frame of an ar or vr scene. re
turn value an integer value which serves as a unique, non-zero id or handle you may pass to cancelanimationframe() if you need to remove the pending animation frame request. example the following example requests xrsession with "inline" mode so that it can be displayed in an html element (without the need for a separate ar or vr device). note: a real application should check that the device and t...
XRSession.updateRenderState() - Web APIs
dicating the default field of view, in radians, to be used when computing the projection matrix for an inline xrsession. the projection matrix calculation also takes into account the output canvas's aspect ratio. this property must not be specified for immersive sessions, so the value is null by default for immersive sessions. the default value is otherwise π * 0.5 (half of the value of pi). re
turn value none. exceptions this method may throw any of the following exceptions. these are true exceptions, since this method does not re
turn a promise. invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which up...
XRSessionEvent - Web APIs
the webxr device api's xrsessionevent interface describes an event which indicates the change of the state of an xrsession. these events occur, for example, when the session ends or the visibility of its context changes. constructor xrsessionevent() creates and re
turns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available. properties in addition to properties inherited from its parent interface, event, xrsessionevent provides the folllowing: session read only the xrsession to which the event refers. methods while xrsessionevent defines no methods, it inherits methods from its parent interface, event. session event types the following events are represented using the xrsessionevent interface, and are permitted values for it...
XRSessionInit - Web APIs
webxr device api dictionary xrsessioninit specifies required and/or optional features when requesting a new xrsession by calling the navigator.xr.requestsession() method. properties the following parameters are all optional. if none are included, the device will use a default feature configuration for all options. optionalfeatures optional an array of values identifying features which the re
turned xrsession may optionally support. at this time, all features are identified using strings from the xrreferencespacetype enumeration, but future updates to the webxr standard may add more features. requiredfeatures optional an array of values which the re
turned xrsession must support. these values currently must come from the enumerated type xrreferencespacetype. more features may be added in ...
XRView.eye - Web APIs
iew); } } for each of the views, the value of eye is checked and if it's either left or right, we check to see if the body.lefteye.injured or body.righteye.injured property is true; if so, we call a function updateinjury() on that eye to do things such as allow a bit of healing to occur, track the progress of a poison effect, or the like, as appropriate for the game's needs. updateinjury() re
turns true if the eye is still injured or false if the eye has been restored to health by the function,. if the result is false, indicating that the eye is now healthy, we render the scene for that eye. otherwise, we don't. specifications specification status comment webxr device apithe definition of 'xrview.eye' in that specification. working draft initial definiti...
XRView.transform - Web APIs
object that makes up the scene. each object's model view matrix is computed by multiplying its own matrix which describes the object's own position and orientation by the additional position and orientation adjustments needed to match the camera's movement. to convert the "camera focused" transform matrix into an "object focused" transform, we use the transform's inverse, thus taking the matrix re
turned by view.transform.inverse.matrix. the resulting model view matrix will apply all the transforms needed to move and rotate the object based on the relative positions of the object and the camera. this will simulate the movement of the camera even though we're actually moving the object. we then compute the normals for the model view matrix by inverting it, then transposing it. finally, we call...
XRWebGLLayer.antialias - Web APIs
's discretion and cannot be specified by the web site or web app. syntax let antialiasingsupported = xrwebgllayer.antialias; value a boolean value which is true if the webgl rendering layer's frame buffer is configured to support antialiasing. otherwise, this property is false. when the webxr compositor is enabled, this value corresponds to the value of the antialias property on the object re
turned by the webgl context's getcontentattributes() method. usage notes since this is a read-only property, you can set the antialiasing mode only when initially creating the xrwebgllayer, by specifying the antialias object in the xrwebgllayer() constructor's layerinit parameter. examples this snippet checks the value of antialias to see if it should perform additional work to attempt to compensa...
XRWebGLLayerInit.depth - Web APIs
lly affect the performance of rendering as well. the default value is true. usage notes this property differs from ignoredepthvalues in that a layer created with ignoredepthvalues set to true may still have a depth buffer, but will not make use of it. you can determine whether or not the depth buffer is being used by a given webgl rendering layer during your xr session by checking the value re
turned by xrwebgllayer.ignoredepthvalues. if this is true, then the depth buffer is either not present or is being ignored. if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a depth buffer. xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { depth: false ...
XRWebGLLayerInit - Web APIs
value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated. the default is true. framebufferscalefactor optional a floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. the static xrwebgllayer function xrwebgllayer.getnativeframebufferscalefactor() re
turns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. the default is 1.0. ignoredepthvalues optional a boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. the default is false. stencil optional a boolean value which, if true, requests that the new l...
msCachingEnabled - Web APIs
or may change in the future. the mscachingenabled method gets the current caching state for an xmlhttprequest. this proprietary method is specific to internet explorer and microsoft edge. syntax var cachestate = xmlhttprequest.mscachingenabled(); parameters cachestate[out, retval] type = boolean. if true, xmlhttprequest is cached to disk. if false, it is not written to disk. re
turn value type: boolean. if true, xmlhttprequest is cached to disk. if false, it is not written to disk. see also mscaching property microsoft api extensions ...
msGetPropertyEnabled - Web APIs
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 msgetpropertyenabled re
turns whether a given property in the style object is enabled. this proprietary method is specific to internet explorer browser. syntax var retval = style.msgetpropertyenabled(name); parameters name [in] type: string the name of the property to enable. re
turn value type: boolean if false, the property is not enabled. if true, the property is enabled. see also microsoft api extensions ...
msGetRegionContent - Web APIs
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 msgetregioncontent re
turns an array of range instances corresponding to the content from the region flow that is positioned in the region. this proprietary method is specific to internet explorer browser. syntax var retval = element.msgetregioncontent(); parameters retval [out, reval] type: msrangecollection the name of the property to enable. re
turn value type: boolean re
turned ranges are sorted by document position and do not overlap. if an element is not a region, this method thr...
msPutPropertyEnabled - Web APIs
ture. the msputpropertyenabled method sets whether a given property in the style object is enabled or disabled. this proprietary method is specific to internet explorer and microsoft edge. syntax var retval = style.msputpropertyenabled(propertyname, true); parameters name[in]: name of the property. (string) boolean[in]: true = enable the property. false = disable the property. re
turn value type = hresult: if this method succeeds, it re
turns s_ok. otherwise, it re
turns an hresult error code. see also css style declaration microsoft api extensions ...
msWriteProfilerMark - Web APIs
also be large incompatibilities between implementations and the behavior may change in the future. the mswriteprofilermark method writes a profiling event. this proprietary method is specific to internet explorer and microsoft edge. syntax window.mswriteprofilermark("start-render"); parameters bstrprofilermarkname[in] an event name. type = string. this parameter may be null. re
turn value type: hresult. if this method succeeds, it re
turns s_ok. otherwise, it re
turns an hresult error code. notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for ...
ARIA live regions - Accessibility
with aria-atomic="true", the screenreader announces "the set year is: changedvalue" advanced use case: roster a chat site would like to display a list of users currently logged in. display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload)...
ARIA Screen Reader Implementors Guide - Accessibility
tics allow for a different voice (in text-to-speech) or other varying presentational characteristics to set live changes apart. when no wai-aria markup is present, automatically present some changes unless the user configures all live changes to off. for example, automatically speak changes that are caused by the user's own input, as part of the context of that input. allow global settings to
turn off the presentation of live changes, present all live changes, use markup, or be "smart" (use heuristics) details for processing via platform accessibility apis we hope browser manufacturers will work to provide consistent implementations. the most complete implementation of live regions currently is in firefox 3. here is how wai-aria live regions are exposed in firefox 3. ...
Using the aria-describedby attribute - Accessibility
n the example below, a link that functions as a 'close' button on a dialog is described elsewhere in the document. the aria-describedby attribute is used to associate the description with the link. <button aria-label="close" aria-describedby="descriptionclose" onclick="mydialog.close()">x</button> ... <div id="descriptionclose">closing this window will discard any information entered and re
turn you back to the main page</div> working examples: checkbox example uses aria-describedby tooltip example uses aria-describedby notes the aria-describedby attributed is not designed to reference descriptions on an external resource—since it is an id, it must reference an element in the same dom document. used by aria roles all elements of the base markup related aria techniques ...
Using the slider role - Accessibility
. the application will programmatically update the value of aria-valuenow in response to user input. <label for="fader">volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to re
turn the output as it is updated by user input: function outputupdate(vol) { document.queryselector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semantically, a number. in these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. in the example below, the slider is used t...
ARIA: timer role - Accessibility
ocus inside the application container. set in response to keyboard or other application events that change focus or point of interaction. the timer role does not have a related html widget and xxx. the author of the timer must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including re
turning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web timers include clocks, stop watches and countdowns, such as ticketing websites, e-commerce sites, and event countdowns (see https://countingdownto.com/). as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. the clock i...
ARIA: application role - Accessibility
. set in response to keyboard or other application events that change focus or point of interaction. the application role does not have a related html widget and thus is completely free form. the author of the application must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including re
turning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web applications that use the application role properly are: google docs, sheets and slides ckeditor and tinymce wysiwyg web editors, like the one used on the mozilla developer network some parts of gmail accessibility concerns improperly using the application ...
ARIA: cell role - Accessibility
cell">france</td> <td role="cell">67 million</td> </tr> description the element with role="cell" is a cell within a row, optionally within a rowgroup, within a grid, table or treegrid within a static tabular structure. using native html <td> elements, whenever possible, is strongly encouraged. each element with role="cell" must be nested in a container element with role="row". that row, in
turn, can be nested within an element with role="rowgroup", and should be nested within a grid, table or treegrid. if a cell contains column or row header information, use the colheader or rowheader roles, respecitively. if the cell does not contain header information and is nested in a grid or treegrid, the role of gridcell may be more appropriate. a cell can contain a number of property attributes...
ARIA: document role - Accessibility
rsation view. gmail is a web application. when in gmail, most user agent interactions are usurped by the application. however, when the keyboard focus is set on the starting heading on a single conversation that contains the subject of the conversation, the screen reader user can use the reading mode commands to read through the messages, expand or collapse them, and manipulate them. once focus re
turns to the message list either by activating the back button or pressing an asociated keystroke, direct application interaction mode is invoked again, and the user can move to a different conversation in the list with the arrow keys. best practices always make sure an item with the document role is focusable, by setting the tabindex attribute with a value of 0. that will also include it in the tab...
ARIA: Navigation Role - Accessibility
n, omitting the term "navigation", as the screen reader will read both the role and the contents of the label. keyboard interactions none. required javascript features none. examples <div role="navigation" aria-label="customer service"> <ul> <li><a href="#">help</a></li> <li><a href="#">order tracking</li> <li><a href="#">shipping & delivery</a></li> <li><a href="#">re
turns</a></li> <li><a href="#">contact us</a></li> <li><a href="#">find a store</a></li> </ul> </div> accessibility concerns landmark roles are intended to be used sparingly, to identify larger overall sections of the document. using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. best practices prefer html ...
ARIA: rowgroup role - Accessibility
t be contained in, or owned by, elements with either the table or grid role. using the native <thead>, <tfoot> , and <tbody> html elements, whenever possible, is strongly encouraged. to create an aria table header, table footer or table body, add role="rowgroup" to the element. that rowgroup should be nested within a grid, table or treegrid, encompassing a group of one or more rows. each row, in
turn, contains child cells. these cells can be of different types, depending on whether they are column or row headers, or plain or grid cells. note: using the native html table element (<table>) along with the table header (<thead>), footer (<tfoot>), and body (<tbody>) elements whenever possible is strongly encouraged. associated wai-aria roles, states, and properties context roles role="ta...
ARIA: button role - Accessibility
ressed attribute would be omitted. keyboard interactions key function enter activates the button. space activates the button following button activation, focus is set depending on the type of action the button performs. for example, if clicking the button opens a dialog, the focus should move to the dialog. if the button closes a dialog, focus should re
turns to the button that opened the dialog unless the function performed in the dialog context logically leads to a different element. if the button alters the current context, then focus typically remains on the button, such as muting and unmuting an audio file. required javascript features required event handlers buttons can be operated by mouse, touch, and keyboard users. for native html <button...
HTML To MSAA - Accessibility
te_system_ readonly if @readonly attribute is used n/a "activate" n/a input @type=password role_system_ text n/a n/a state_system_ readonly if @readonly attribute is used state_system_ protected n/a "activate" n/a input type="checkbox" role_system_ checkbutton n/a n/a state_system_ marqueed used as state checkable state_system_ mixed for html 5 if intermediate property of dom element re
turns true state_system_ checked if checked property of dom element re
turns true n/a "check"/"uncheck"/"cycle" depending on state event_object_ statechange when state is changed input type="radio" role_system_ radiobutton n/a n/a state_system_ marqueed used as state checkable state_system_ checked if checked property of dom element re
turns true n/a "select" event_object_ statechange when state ...
Web accessibility for seizures and physical reactions - Accessibility
uery/#comment-1700170) */ transition-duration: 0.001ms !important; } } from w3.org's page on media queries 4: the update media feature is used to query the ability of the output device to modify the appearance of content once it has been rendered. it has the values of "none", "slow", and "fast". developmental & experimental features mdn navigator.donottrack from the documentation: "re
turns the user's do-not-track setting. this is "1" if the user has requested not to be tracked by web sites, content, or advertising" media queries level 5 environmentmq (planned in media queries level 5) light-level has three valid values: dim, normal, and washed. interestingly, the specification refrains from actually defining the three levels in terms of a measurment of lux, because devices wit...
Web Accessibility: Understanding Colors and Luminance - Accessibility
ng color & luminance methods that measures color exploring the rgb color space further, as it is the color space used by the data type <color>, note that there are actually multiple "versions" of the rgb color space, such as srgb, scrgb, and rgba. there are also different ways to refrence rgb: rgb decimal reference: 153, 0, 0 and an rgb percent reference: 60, 0, 0. window.getcomputedstyle() re
turns values using rgb decimal reference scale. for example, calling window.getcomputedstyle() on a div with a background-color: #990000; set re
turns the computed background color as rgb(153, 0, 0) -- the rgb decimal reference. window.getcomputedstyle() measures color in terms of rgb. css color module level 3 added hsl color values, stating "css3 adds numerical hue-saturation-lightness (hsl) colo...
Keyboard - Accessibility
then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option). note: one important exception to this rule is if the element has role="document" applied to it, inside an interactive context (such as role="application"). in such a case, focusing the nested document is the only way of re
turning assistive technology to a non-interactive state (often called "browse mode"). most interactive elements are focusable by default; you can make an element focusable by adding a tabindex=0 attribute value to it. however, you should only add tabindex if you have also made the element interactive, for example, by defining appropriate event handlers keyboard events. see also tabindex global h...
Perceivable - Accessibility
rative images should be implemented using css background images (see backgrounds). if you have to include an image via an <img> element, give it a blank alt (alt=""). otherwise, screenreaders may try to read out the filepath, etc. if you are including background video or audio that autoplays, make it as unobtrusive as possible. don't make it look/sound like content, and provide a control to
turn it off. ideally, don't include it at all. note: also see the wcag description for guideline 1.1: text alternatives. guideline 1.2 — providing text alternatives for time-based media time-based media refers to multimedia with a duration, such as audio and video. note that if the audio/video serves as an alternative to existing text content, you don't need to provide another text al...
:active - CSS: Cascading Style Sheets
l other link-related rules, as defined by the lvha-order: :link — :visited — :hover — :active. note: on systems with multi-button mice, css3 specifies that the :active pseudo-class must only apply to the primary button; on right-handed mice, this is typically the leftmost button. syntax :active examples active links html <p>this paragraph contains a link: <a href="#">this link will
turn red while you click on it.</a> the paragraph will get a gray background while you click on it or the link. </p> css a:link { color: blue; } /* unvisited links */ a:visited { color: purple; } /* visited links */ a:hover { background: yellow; } /* hovered links */ a:active { color: red; } /* active links */ p:active { background: #eee; } /* active paragraphs */ result ...
:nth-last-child() - CSS: Cascading Style Sheets
three elements */ tr:nth-last-child(-n+3) { background-color: pink; } /* selects every element starting from the second to last item */ tr:nth-last-child(n+2) { color: blue; } /* select only the last second element */ tr:nth-last-child(2) { font-weight: 600; } result quantity query a quantity query styles elements depending on how many of them there are. in this example, list items
turn red when there are at least three of them in a given list. this is accomplished by combining the capabilities of the nth-last-child pseudo-class and the general sibling combinator. html <h4>a list of four items (styled):</h4> <ol> <li>one</li> <li>two</li> <li>three</li> <li>four</li> </ol> <h4>a list of two items (unstyled):</h4> <ol> <li>one</li> <li>two</li> </ol> css /* if th...
:scope - CSS: Cascading Style Sheets
></p> result direct children a situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved element. ...
:visited - CSS: Cascading Style Sheets
butes are fill and stroke. the alpha component of the allowed styles will be ignored. the alpha component of the element's non-:visited state will be used instead, except when that component is 0, in which case the style set in :visited will be ignored entirely. although these styles can be change the appearance of colors to the end user, the window.getcomputedstyle method will lie and always re
turn the value of the non-:visited color. note: for more information on these limitations and the reasons behind them, see privacy and the :visited selector. syntax :visited examples properties that would otherwise have no color or be transparent cannot be modified with :visited. of the properties that can be set with this pseudo-class, your browser probably has a default value for color and c...
prefers-color-scheme - CSS: Cascading Style Sheets
if you have set privacy.resistfingerprinting to true, prefers-color-scheme preference is overridden to light. alternately, users can create the numeric preference ui.systemusesdarktheme to override the default behavior and re
turn light (value: 0), dark (value: 1), or no-preference (value: 2). (any other value causes firefox to re
turn light.) the prefers-color-scheme css media feature is used to detect if the user has requested the system use a light or dark color theme. syntax light indicates that user has notified the system that they prefer an interface that has a light theme, or has not expressed an active preference. dark indicates that user has notified the system that they prefer an interface that has a dark theme. examples the elements below have an initial color t...
prefers-reduced-motion - CSS: Cascading Style Sheets
known to the system. reduce indicates that user has notified the system that they prefer an interface that removes or replaces the types of motion-based animation that trigger discomfort for those with vestibular motion disorders. user preferences for firefox, the reduce request is honoured if: in gtk/gnome: gnome tweaks > general tab (or appearance, depending on version) > animations is
turned off. alternatively, add gtk-enable-animations = false to the [settings] block of the gtk 3 configuration file. in windows 10: settings > ease of access > display > show animations in windows. in windows 7: control panel > ease of access > make the computer easier to see >
turn off all unnecessary animations (when possible). in macos: system preferences > accessibility > display > ...
@media - CSS: Cascading Style Sheets
ecause media queries provide insights into the capabilities—and by extension, the features and design—of the device the user is working with, there is the potential that they could be abused to construct a "fingerprint" which identifies the device, or at least categorizes it to some degree of detail that may be undesirable to users. because of this potential, a browser may opt to fudge the re
turned values in some manner in order to prevent them from being used to precisely identify a computer. a browser might also offer additional measures in this area; for example, if firefox's "resist fingerprinting" setting is enabled, many media queries report default values rather than values representing the actual device state. formal syntax @media <media-query-list> { <group-rule-body> }where ...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
ting auto margins on the block. a margin of auto will absorb all available space in that dimension, therefore setting a left and right margin of auto, you can push a block into the center: .container { width: 20em; margin-left: auto; margin-right: auto; } in table layout, you have access to the vertical-align property to align the contents of a cell inside that cell. for many use cases,
turning the block container into a flex item will give you the alignment capability that you are looking for. in the example below, a container with a single item inside has been
turned into a flex container for the purpose of being able to use the alignment properties. reference css properties justify-content align-content justify-self align-self glossary entries alignment subject ali...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
lement. if an element is not a flex item, flex has no effect. values: see the flex reference for values and default spec: https://drafts.csswg.org/css-flexbox/#flex-property @mixin flex($fg: 1, $fs: 0, $fb: auto) { // set a variable to be used by box-flex properties $fg-boxflex: $fg; // box-flex only supports a flex-grow value so lets grab the // first item in the list and just re
turn that. @if type-of($fg) == 'list' { $fg-boxflex: nth($fg, 1); } -webkit-box: $fg-boxflex; -moz-box: $fg-boxflex; -webkit-flex: $fg $fs $fb; -ms-flex: $fg $fs $fb; flex: $fg $fs $fb; } flexbox justify content the justify-content property aligns flex items along the main axis of the current line of the flex container. this is done after any flexible lengths and any auto margins...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
ordinarily participate in flex layout. flex layout only applies to the direct children of a flex container. by adding display: contents to the wrapper around the nested elements, you can see that that item has disappeared from the layout, allowing the two sub-children to be laid out as if they were direct children of the flex container. you can try removing the display: contents line to see it re
turn. note that this only removes the box from the layout; the sub-children don’t become direct children in any other way. you can see that as i have used a direct child selector to add the background and borders to the flex items, this has not been applied to our nested children. they have been laid out as flex items, but as they are not direct children they do not get the other styling. warning...
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
deprioritized in the mobile source order can be moved into a sidebar in a desktop layout, for example. the key here is to keep testing, a very simple test is to tab around the document. does that order still make sense? check that you do not end up leaping from the top to the bottom of the layout in a peculiar way. if so that would be a sign that you need to address something about the layout. re
turning to the source if at any time in the design process you find yourself using grid to relocate the position of an element, consider whether you should re
turn to your document and make a change to the logical order too. the nice thing about using css grid layout is that you should be able to move an item in the source to match the logical order, without needing to make big changes to your layout.
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
> </li> </ul> </div> the example demonstrates the typical problem that we have with floated layouts: if additional content is added to any one card, the layout breaks. as a concession for older browsers, i have set a min-height on the items, and hope that my content editors won’t add too much content and make a mess of the layout! i then enhance the layout using grid. i can
turn my <ul> into a grid container with three column tracks. however, the width i have assigned to the list items themselves still applies, and it now makes those items a third of the width of the track: if i reset the width to auto, then this will stop the float behavior happening for older browsers. i need to be able to define the width for older browsers, and remove the width for grid supporting...
Consistent list indentation - CSS: Cascading Style Sheets
into a document as-is, there would be no apparent indentation and the markers would be in danger of falling off the left edge of the browser window. in order to avoid this and get some indentation, there are really only three options available to browser implementors. give each <li> element a left margin. give the <ul> element a left margin. give the <ul> element some left padding. as it
turns out, nobody seems to have used the first option. the second option was taken by internet explorer for windows and macintosh, and opera. the third was adopted by gecko, and by extension all the browsers that embed it. let's look at the two approaches for a moment. in internet explorer and opera, the lists are indented by setting a left margin of 40 pixels on the <ul> element. if we apply a backg...
Descendant combinator - CSS: Cascading Style Sheets
arent's parent's parent, etc) element matching the first selector. selectors that utilize a descendant combinator are called descendant selectors. /* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage re
turn, form feed, new line, and tab characters — between two selectors in the absence of another combinator. additionally, the white space characters of which the combinator is comprised may contain any number of css comments. syntax selector1 selector2 { /* property declarations */ } examples css li { list-style-type: disc; } li li { list-style-type: circle; } html <ul> <li> <di...
Center an element - CSS: Cascading Style Sheets
m into the center of another box horizontally and vertically. recipe download this example choices made to center one box inside another we make the containing box a flex container. then set align-items to center to perform centering on the block axis, and justify-content to center to perform centering on the inline axis. in the future we may be able to center elements without needing to
turn the parent into a flex container, as the box alignment properties used here are specified to apply to block layout too. however, support is currently limited for box alignment properties on block layout, so currently centering using flexbox is the most robust way to achieve this. ...
Column layouts - CSS: Cascading Style Sheets
a single row of items arranged as columns, with all heights being equal. multiple rows of columns lined up by row and column. the recipes you need to choose different layout methods in order to achieve your requirements. a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream filling each column in
turn. the columns must all be the same size, and you are unable to target an individual column or the content of an individual column. you can control the gaps between columns with the column-gap property, and add a rule between columns using column-rule. download this example use multicol when: you want your text to display in newspaper-like columns. you have a set of small items you want ...
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
battery or low-end phones or computers. syntax no-preference indicates that the user has made no preference known to the system. reduce indicates that user has notified the system that they prefer an interface that minimizes the amount of movement or animation, preferably to the point where all non-essential movement is removed. example this example has an annoying animation unless you
turn on reduce motion in your accessibility preferences. html <div class="animation">animated box</div> css .animation { -webkit-animation: vibrate 0.3s linear infinite both; animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { .animation { animation: none; } } high contrast mode the -ms-high-contrast css media feature is a microsoft extensi...
Privacy and the :visited selector - CSS: Cascading Style Sheets
ot of information about the user's identity. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. little white lies to preserve users' privacy, firefox and other browsers will lie to web applications under certain circumstances: the window.getcomputedstyle method, and similar functions such as element.queryselector, will always re
turn values indicating that a user has never visited any of the links on a page. if you use a sibling selector such as :visited + span, the adjacent element (span in this example) will be styled as if the link were unvisited. in rare scenarios, if you're using nested link elements and the element being matched is different from the link whose presence in history is being tested, the element will be ...
CSS reference - CSS: Cascading Style Sheets
tationtext-overflowtext-renderingtext-shadowtext-transformtext-underline-offsettext-underline-position<time><time-percentage><timing-function>top@top-centertouch-actiontransformtransform-box<transform-function>transform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functiontranslatetranslate()translate3d()translatex()translatey()translatez()
turnuunicode-bidiunicode-range (@font-face)unset<url>url()user-zoom (@viewport)v:validvar()vertical-alignvh@viewportviewport-fit (@viewport)visibility:visitedvmaxvminvwwwhite-spacewidowswidthwidth (@viewport)will-changeword-breakword-spacingword-wrapwriting-modexxzz-indexzoom (@viewport)others--* selectors the following are the various selectors, which allow styles to be conditional based on variou...
Shorthand properties - CSS: Cascading Style Sheets
d property, all, which applies its value to every property in the document. its purpose is to change the properties' inheritance model to one of: css provides four special universal property values for controlling inheritance. every css property accepts these values. inherit sets the property value applied to a selected element to be the same as that of its parent element. effectively, this "
turns on inheritance". initial sets the property value applied to a selected element to the initial value of that property. unset resets the property to its natural value, which means that if the property is naturally inherited it acts like inherit, otherwise it acts like initial. note: there is also a newer value, revert, which has limited browser support. note: see origin of css declaratio...
Specificity - CSS: Cascading Style Sheets
" style="color: red;">what color am i?</div> .foo[style*="color: red"] { color: firebrick !important; } many javascript frameworks and libraries add inline styles. using !important with a very targeted selector is one way to override these inline styles. b) overriding high specificity #someelement p { color: blue; } p.awesome { color: red; } how do you make awesome paragraphs always
turn red, even ones inside #someelement? without !important, the first rule will have more specificity and will win over the second rule. how to override !important a) add another css rule with !important, and either give the selector a higher specificity (adding a tag, id or class to the selector), or add a css rule with the same selector at a later point than the existing one. this works because i...
Viewport concepts - CSS: Cascading Style Sheets
ken on a browser with an address bar and bookmarks bar totalling 100px in height, but no chrome on the left or right of the window. the area within the innerheight and innerwidth is generally considered the layout viewport. the browser chrome is not considered part of the viewport. when zoomed in, both firefox and chrome report the new css pixel size for innerwidth and clientwidth. the values re
turned for the outerwidth and outerheight depend on the browser: firefox reports the new value in css pixels, but chrome re
turns the length in the default pixel size. when zoomed in you may get: document.documentelement.clientwidth /* 800 */ window.innerwidth /* 800 */ window.outerwidth /* 800 in firefox, 1200 in chrome */ document.documentelement.clientheight /* 533 */ window.innerheight /* 533 */...
Visual formatting model - CSS: Cascading Style Sheets
x before the emphasized section, the section wrapped in the <em> element, then a final anonymous inline box. as with the anonymous block boxes, these anonymous inline boxes cannot be styled independently in the way the <em> can; they just inherit the styles of their container. other formatting contexts also create anonymous boxes. grid layout behaves in the same way as the flexbox example above,
turning strings of text into a grid item with an anonymous box. multiple-column layout creates anonymous column boxes around the columns; these also cannot be styled or otherwise targetted. table layout will add anonymous boxes to create a proper table structure — for example adding an anonymous table row — if there was no box with display: table-row. line boxes line boxes are the boxes that wra...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
div>lorem</div> chrome safari edge media-play-button div{ color: black; -webkit-appearance: media-play-button; } <div>lorem</div> chrome safari edge media-overlay-play-button div{ color: black; -webkit-appearance: media-overlay-play-button; } <div>lorem</div> chrome safari media-re
turn-to-realtime-button div{ color: black; -moz-appearance: media-re
turn-to-realtime-button; -webkit-appearance: media-re
turn-to-realtime-button; } <div>lorem</div> safari media-rewind-button div{ color: black; -moz-appearance: media-rewind-button; -webkit-appearance: media-rewind-button; } <div>lorem</div> safari ...
<blend-mode> - CSS: Cascading Style Sheets
changes between blend modes are not interpolated. any change occurs immediately. examples blend mode comparison in the following example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient. below it we have a provided a <select> menu that allows you to change the background-blend-mode applied to the <div>, allowing you to co...
box-flex-group - CSS: Cascading Style Sheets
ious flex group. once there are no more flex groups, and there is still space remaining, the extra space is divided within the containing box according to the box-pack property. if the box would overflow after the preferred space of the children has been computed, then space is removed from flexible elements in a manner similar to that used when adding extra space. each flex group is examined in
turn and space is removed according to the ratio of the flexibility of each element. elements do not shrink below their minimum widths. syntax the box-flex-group property is specified as any positive <integer>. formal definition initial value1applies toin-flow children of box elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer> examples simple usage examp...
break-inside - CSS: Cascading Style Sheets
t. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the value of the element that appears the latest in the flow is used. thus, the break-before value has precedence over the break-after value, which in
turn has precedence over the break-inside value. if any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a corresponding avoid value. syntax the break-inside property is specifi...
calc() - CSS: Cascading Style Sheets
tanding wcag, guideline 1.4 explanations understanding success criterion 1.4.4 | w3c understanding wcag 2.0 usage with integers when calc() is used where an <integer> is expected, the value will be rounded to the nearest integer. for example: .modal { z-index: calc(3 / 2); } this will give .modal a final z-index value of 2. note: the chrome browser currently won’t accept some values re
turned by calc() when an integer is expected. this includes any division, even if it results in an integer. ie. z-index: calc(4 / 2); will not be accepted. examples positioning an object on screen with a margin calc() makes it easy to position an object with a set margin. in this example, the css creates a banner that stretches across the window, with a 40-pixel gap between both sides of the banne...
color - CSS: Cascading Style Sheets
translucent */ p { color: #ff000080; } p { color: rgba(255, 0, 0, 0.5); } p { color: hsla(0, 100%, 50%, 0.5); } specifications specification status comment css color module level 4the definition of 'color' in that specification. working draft adds commaless syntaxes for the rgb(), rgba(), hsl(), and hsla() functions. allows alpha values in rgb() and hsl(),
turning rgba() and hsla() into (deprecated) aliases for them. adds color keyword rebeccapurple. adds 4- and 8-digit hex color values, where the last digit(s) represents the alpha value. adds hwb(), device-cmyk(), and color() functions. css color module level 3the definition of 'color' in that specification. recommendation deprecates system-colors. adds svg colors. adds the r...
content - CSS: Cascading Style Sheets
string)' or 'counters(name, string, style)'. the generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. the counters are rendered in the indicated style (decimal by default). attr(x) the value of the element's attribute x as a string. if there is no attribute x, an empty string is re
turned. the case-sensitivity of attribute names depends on the document language. open-quote | close-quote these values are replaced by the appropriate string from the quotes property. no-open-quote | no-close-quote introduces no content, but increments (decrements) the level of nesting for quotes. accessibility concerns css-generated content is not included in the dom. because of this, it wil...
<display-box> - CSS: Cascading Style Sheets
elements" — elements that aren’t rendered purely by css box concepts such as replaced elements. see appendix b: effects of display: contents on unusual elements for more details. due to a bug in browsers this will currently remove the element from the accessibility tree — screen readers will not look at what's inside. see the accessibility concerns section below for more details. none
turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). all descendant elements also have their display
turned off. to have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead. accessibility concerns current implementations in most browse...
display - CSS: Cascading Style Sheets
elements" — elements that aren’t rendered purely by css box concepts such as replaced elements. see appendix b: effects of display: contents on unusual elements for more details. due to a bug in browsers this will currently remove the element from the accessibility tree — screen readers will not look at what's inside. see the accessibility concerns section below for more details. none
turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). all descendant elements also have their display
turned off. to have an element take up the space that it would normally take, but without actually rendering anything, use the visibility property instead. legacy <display-legacy> css 2 used a single-keyword syntax...
<easing-function> - CSS: Cascading Style Sheets
hey correlate a time ratio to an output ratio, both expressed as <number>s. for these values, 0.0 represents the initial state, and 1.0 represents the final state. depending on the specific function used, the calculated output can sometimes grow to be greater than 1.0 or smaller than 0.0 during the course of an animation. this causes the animation to go farther than the final state, and then re
turn. for some properties, such as left or right, this creates a kind of "bouncing" effect. however, certain properties will restrict the output if it goes outside an allowable range. for example, a color component greater than 255 or smaller than 0 will be clipped to the closest allowed value (255 and 0, respectively). some cubic-bezier() curves exhibit this property. syntax there are three types ...
hue-rotate() - CSS: Cascading Style Sheets
ves the input unchanged. a positive hue rotation increases the hue value, while a negative rotation decreases the hue value. the lacuna value for interpolation is 0. there is no minimum or maximum value; hue-rotate(ndeg) evaluates to n modulo 360. examples hue-rotate(-90deg) /* same as 270deg rotation */ hue-rotate(0deg) /* no effect */ hue-rotate(90deg) /* 90deg rotation */ hue-rotate(.5
turn) /* 180deg rotation */ hue-rotate(405deg) /* same as 45deg rotation */ specifications specification status filter effects module level 1the definition of 'hue-rotate()' in that specification. working draft ...
filter - CSS: Cascading Style Sheets
lter is none, it is replaced with the filter functions list of the other one using the filter function default values, then all filter functions are interpolated according to their specific rules. otherwise, discrete interpolation is used. functions the filter property is specified as none or one or more of the functions listed below. if the parameter for any function is invalid, the function re
turns none. except where noted, the functions that take a value expressed with a percent sign (as in 34%) also accept the value expressed as decimal (as in 0.34). when a single filter property has two or more functions it's results will be different from when two or more filter properties are separately applied with the same functions. svg filter url() takes an uri pointing to an svg filter, which...
font-size - CSS: Cascading Style Sheets
t browser settings */ } span { font-size: 1.6em; } <div> <span>outer <span>inner</span> outer</span> </div> the result is: assuming that the browser's default font-size is 16px, the words “outer” would be rendered at 16px, but the word “inner” would be rendered at 25.6px. this is because the inner <span>'s font-size is 1.6em which is relative to its parent's font-size, which is in
turn relative to its parent's font-size. this is often called compounding. rems rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. in other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding. the css below is nearly...
font - CSS: Cascading Style Sheets
rcss"), shorttext = "", getcheckedvalue, setcss, getproperties, injectcss; getproperties = function () { shorttext = getcheckedvalue("font_style") + " " + getcheckedvalue("font_variant") + " " + getcheckedvalue("font_weight") + " " + getcheckedvalue("font_size") + getcheckedvalue("line_height") + " " + getcheckedvalue("font_family"); re
turn shorttext; } getcheckedvalue = function(radio_name) { oradio = document.forms[0].elements[radio_name]; for (var i = 0; i < oradio.length; i++) { if(oradio[i].checked) { var propinput = "input_" + radio_name, curelemname = "input_" + radio_name, curelem = document.getelementbyid(curelemname); curelem.value = oradio[i].value; re
turn oradio[i].value; ...
grid-auto-flow - CSS: Cascading Style Sheets
ow: row; grid-auto-flow: column; grid-auto-flow: dense; grid-auto-flow: row dense; grid-auto-flow: column dense; /* global values */ grid-auto-flow: inherit; grid-auto-flow: initial; grid-auto-flow: unset; this property may take one of two forms: a single keyword: one of row, column, or dense. two keywords: row dense or column dense. values row items are placed by filling each row in
turn, adding new rows as necessary. if neither row nor column is provided, row is assumed. column items are placed by filling each column in
turn, adding new columns as necessary. dense "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later. this may cause items to appear out-of-order, when doing so would fill in holes left by larger items. if it...
<length> - CSS: Cascading Style Sheets
ng-point numbers. the interpolation happens on the calculated value. the speed of the interpolation is determined by the timing function associated with the animation. examples length unit comparison the following demo provides you with an input field in which you can enter a <length> value (e.g. 300px, 50%, 30vw) to set the width of a result bar that will appear below it once you've pressed re
turn. this allows you to compare and contrast the effect of different length units. html <div class="outer"> <div class="input-container"> <label>enter width:</label> <input type="text" id="length"> </div> <div class="inner"> </div> </div> <div class="results"> </div> css html { font-family: sans-serif; font-weight: bold; box-sizing: border-box; } .outer { width: 100%; ...
offset-rotate - CSS: Cascading Style Sheets
ote: early versions of the spec called this property motion-rotation. syntax /* follow the path direction, with optional additional angle */ offset-rotate: auto; offset-rotate: auto 45deg; /* follow the path direction but facing the opposite direction of `auto` */ offset-rotate: reverse; /* keep a constant rotation regardless the position on the path */ offset-rotate: 90deg; offset-rotate: .5
turn; auto the element is rotated by the angle of the direction of the offset-path, relative to the positive x-axis. this is the default value. <angle> the element has a constant clockwise rotation transformation applied to it by the specified rotation angle. auto <angle> if auto is followed by an <angle>, the computed value of the angle is added to the computed value of auto. rev...
overflow-anchor - CSS: Cascading Style Sheets
css property provides a way to opt out of the browser's scroll anchoring behavior, which adjusts scroll position to minimize content shifts. scroll anchoring behavior is enabled by default in any browser that supports it. therefore, changing the value of this property is typically only required if you are experiencing problems with scroll anchoring in a document or part of a document and need to
turn the behavior off. syntax /* keyword values */ overflow-anchor: auto; overflow-anchor: none; /* global values */ overflow-anchor: inherit; overflow-anchor: initial; overflow-anchor: unset; values auto the element becomes a potential anchor when adjusting scroll position. none the element won't be selected as a potential anchor. formal definition initial valueautoapplies toall element...
repeating-conic-gradient() - CSS: Cascading Style Sheets
ifferent between the largest and smallest color angle, then repeating. a repeating conic gradient is specified by indicating a rotation angle, the center of the gradient, and then specifying a list of color-stops. like non-repeating conic gradients, the color-stops of a repeating conic gradient are specified with an <angle>. units include deg for degrees, grad for gradients, rad for radians, and
turn for
turns. there are 360 degrees, 400 gradians, 2π radians, and 1
turn in a circle. browsers supporting repeating conic gradients also accept percent values, with 100% equaling 360 degrees, but this is not in the specification. radial and conic gradient syntax provides for positioning the center of the gradient anywhere within, or even outside, the image. the values for the position are similar...
repeating-linear-gradient() - CSS: Cascading Style Sheets
/* a repeating gradient tilted 45 degrees, starting blue and finishing red, repeating 3 times */ repeating-linear-gradient(45deg, blue, red 33.3%); /* a repeating gradient going from the bottom right to the top left, starting blue and finishing red, repeating every 20px */ repeating-linear-gradient(to left top, blue, red 20px); /* a gradient going from the bottom to top, starting blue,
turning green after 40%, and finishing red. this gradient doesn't repeat because the last color stop defaults to 100% */ repeating-linear-gradient(0deg, blue, green 40%, red); /* a gradient repeating five times, going from the left to right, starting red,
turning green, and back to red */ repeating-linear-gradient(to right, red 0%, green 10%, red 20%); values <side-or-corner> the posit...
Resolved value - CSS: Cascading Style Sheets
for most properties, it is the computed value, but for a few legacy properties (including width and height), it is instead the used value. see the specification link below for more per-property details. ...
rotate - CSS: Cascading Style Sheets
the rotate css property allows you to specify rotation transforms individually and independently of the transform property. this maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform property. syntax /* keyword values */ rotate: none; /* angle value */ rotate: 90deg; rotate: 0.25
turn; rotate: 1.57rad; /* x, y, or z axis name plus angle */ rotate: x 90deg; rotate: y 0.25
turn; rotate: z 1.57rad; /* vector plus angle value */ rotate: 1 1 1 90deg; values angle value an <angle> specifying the angle to rotate the affected element through, around the z axis. equivalent to a rotate() (2d rotation) function. x, y, or z axis name plus angle value the name of the axis you want to rotate the affected elemen...
symbols() - CSS: Cascading Style Sheets
roperty such as list-style. unlike @counter-style, symbols() is anonymous (i.e., it can only be used once). although less powerful, it is shorter and easier to write than @counter-style. syntax symbols() = symbols( <symbols-type>? [ <string> | <image> ]+ ); <symbols-type> can be one of the following: cyclic: the system cycles through the given values in the order of their definition, and re
turns to the start when it reaches the end. numeric: the system interprets the given values as the successive units of a place-value numbering system. alphabetic: the system interprets the given values as the digits of an alphabetic numbering system, like a place-value numbering system but without 0. symbolic: the system cycles through the values, printing them an additional time at each cycle (one...
text-justify - CSS: Cascading Style Sheets
s what type of justification should be applied to text when text-align: justify; is set on an element. text-justify: none; text-justify: auto; text-justify: inter-word; text-justify: inter-character; text-justify: distribute; /* deprecated value */ syntax the text-justify property is specified as a single keyword chosen from the list of values below. values none the text justification is
turned off. this has the same effect as not setting text-align at all, although it is useful if you need to
turn justification on and off for some reason. auto the browser chooses the best type of justification for the current situation based on a balance between performance and quality, but also on what is most appropriate for the language of the text (e.g., english, cjk languages, etc.). this is t...
scale() - CSS: Cascading Style Sheets
eneous coordinates on ℝℙ3 sx0 0sy sx000sy0001 sx000sy0001 sx0000sy0000100001 [sx 0 0 sy 0 0] accessibility concerns scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. if you need to include such animations on your website, you should provide a control to allow users to
turn off animations, preferrably site-wide. also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will
turn off animations if the user has reduced animation specified in their system preferences. find out more: mdn understanding wcag, guideline 2.3 explanations understanding success criterion 2.3.3 | w3c understanding wcag 2.1 examples sc...
url() - CSS: Cascading Style Sheets
ue for background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-image-source, mask, mask-image, src as part of a @font-face block, and @counter-style/symbol in css level 1, the url() functional notation described only true urls. in css level 2, the definition of url() was extended to describe any uri, including urns. css values and units level 3 re
turned to the narrower, initial definition. now, url() denotes only true <url>s. syntax values <string> <url> a url, which is a relative or absolute address, or pointer, to the web resource to be included, or a data uri, optionally in single or double quotes. quotes are required if the url includes parentheses, whitespace, or quotes, unless these characters are escaped, or if the address ...
<url> - CSS: Cascading Style Sheets
ss level 1, the url() functional notation described only true urls. in css level 2, the definition of url() was extended to describe any uri, whether a url or a urn. confusingly, this meant that url() could be used to create a <uri> css data type. this change was not only awkward but, debatably, unnecessary, since urns are almost never used in actual css. to alleviate the confusion, css level 3 re
turned to the narrower, initial definition. now, url() denotes only true <url>s. syntax the <url> data type is specified using the url() functional notation. it may be written without quotes, or surrounded by single or double quotes. relative urls are allowed, and are relative to the url of the stylesheet (not to the url of the web page). if you choose to write the url without quotes, use a backsl...
Used value - CSS: Cascading Style Sheets
d value. after the user agent has finished its calculations, every css property has a used value. the used values of dimensions (e.g., width, line-height) are in pixels. the used values of shorthand properties (e.g., background) are consistent with those of their component properties (e.g., background-color or background-size) and with position and float. note: the getcomputedstyle() dom api re
turns the resolved value, which may either be the computed value or the used value, depending on the property. example this example computes and displays the used width value of three elements (updates on resize): html <div id="no-width"> <p>no explicit width.</p> <p class="show-used-width">..</p> <div id="width-50"> <p>explicit width: 50%.</p> <p class="show-used-width">..</p> ...
exsl:node-set() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes exsl:node-set() re
turns a node-set from a result tree fragment, which is what you get when you look at the xsl:variable instead of its select attribute to fetch a variable's value. this lets you process the xml created within a variable to process it in multiple steps. you can also use exsl:node-set() to
turn strings into text nodes. syntax exsl:node-set(object) parameters object the object for which to re
turn the corresponding node-set. re
turns the node-set corresponding to the specified object. specifications exslt - exsl:node-set ...
Common (exsl) - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt common package provides basic functions that expand upon the capabilities of xslt. the namespace for the common package is http://exslt.org/common. exsl:node-set()exsl:node-set() re
turns a node-set from a result tree fragment, which is what you get when you look at the xsl:variable instead of its select attribute to fetch a variable's value. this lets you process the xml created within a variable to process it in multiple steps.exsl:object-type()exsl:object-type() re
turns a string that indicates the type of the specified object. ...
math:highest() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:highest() re
turns the node in the specified node-set with the highest value (where the highest value calculated using math:max()). a node has this maximum value if converting its string value to a number equals the maximum value. note: ??? syntax math:highest(nodeset) parameters nodeset the node-set whose highest value is to be re
turned. re
turns a result tree fragment consisting of copies of the nodes re
turned by math:max(). specifications exslt - math:highest ...
math:lowest() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:lowest() re
turns the node in the specified node-set with the lowest value (where the lowest value calculated using math:min()). a node has this minimum value if converting its string value to a number equals the minimum value. syntax math:lowest(nodeset) parameters nodeset the node-set whose lowest value is to be re
turned. re
turns a result tree fragment consisting of copies of the nodes re
turned by math:min(). specifications exslt - math:lowest ...
math:max() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:max() re
turns the maximum value of a node-set. to compute the maximum value of the node-set, the node set is sorted into descending order as it would be using xsl:sort() with a data type of number. the maximum value is then the first node in the sorted list, converted into a number. syntax math:max(nodeset) parameters nodeset the node-set whose highest value is to be re
turned. re
turns a result tree fragment representing the highest valued node's numeric value as a string. specifications exslt - math:max ...
math:min() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:min() re
turns the minimum value of a node-set. to compute the minimum value of the node-set, the node set is sorted into ascending order as it would be using xsl:sort() with a data type of number. the minimum value is then the first node in the sorted list, converted into a number. note: syntax math:min(nodeset) parameters nodeset the node-set whose lowest value is to be re
turned. re
turns a result tree fragment representing the lowest valued node's numeric value as a string. specifications exslt - math:min browser compatibility supported in gecko 1.9 and later. ...
Math (math) - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt math package provides functions for working with numeric values and comparing nodes. the namespace for the math package is http://exslt.org/math. math:highest()math:highest() re
turns the node in the specified node-set with the highest value (where the highest value calculated using math:max()).math:lowest()math:lowest() re
turns the node in the specified node-set with the lowest value (where the lowest value calculated using math:min()).math:max()math:max() re
turns the maximum value of a node-set.math:min()math:min() re
turns the minimum value of a node-set. ...
regexp:replace() - EXSLT
placestring the string with which the matched substrings are to be replaced. the character flags are: g - global replace if this flag is specified, all occurrences of the regular expression within the originalstring are replaced. otherwise only the first occurrence is replaced. i - case insensitive match if this flag is specified, the match is performed in a case insensitive fashion. re
turns the revised version of the string. specifications exslt - regexp:replace ...
regexp:test() - EXSLT
g to test.. regexpstring the javascript style regular expression to evaluate. flagsstringoptional an optional string containing character flags. the character flags are: g global match has no effect for this function; it's allowed for consistency with other regexp functions. i case insensitive match if this flag is specified, the match is performed in a case insensitive fashion. re
turns true if the specified regexp matches the test string. specifications exslt - regexp:test ...
Regular expressions (regexp) - EXSLT
ath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions. the namespace for the regular expressions package is http://exslt.org/regular-expressions. regexp:match()regexp:match() performs regular expression matching on a string, re
turning the submatches found as a result.regexp:replace()regexp:replace() replaces the portions of a string that match a given regular expression with the contents of another string.regexp:test()regexp:test() tests to see whether a string matches a specified regular expression. ...
set:difference() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:difference() re
turns the difference between two node-sets. in other words, it re
turns a node-set whose nodes are in one node-set but not in the other. the template version of set:difference applies templates to these nodes in set:difference mode, copying the nodes so that a result tree fragment consisting of the nodes is re
turned. syntax set:difference(nodeset1, nodeset2) parameters nodeset1 the node-set from which to subtract nodes. nodeset2 the set of nodes to subtract from nodeset1. re
turns a node-set containing the nodes that are in nodeset1 but not in nodeset2. specifications exslt - set:difference ...
set:distinct() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:distinct() re
turns a subset of the nodes in the specified node-set, re
turning only nodes with unique string values. syntax set:distinct(nodeset) parameters nodeset the node-set in which to find unique nodes. re
turns a node-set containing the nodes that have unique string values. specifications exslt - set:distinct ...
set:intersection() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:intersection() re
turns the intersection of two node-sets. in other words, it re
turns a node-set containing all the nodes that exits in both nodeset1 and nodeset2. syntax set:intersection(nodeset1, nodeset2) arguments nodeset1 the first node-set. nodeset2 the second node-set. re
turns a node-set containing the nodes that existed in both nodeset1 and in nodeset2. specifications exslt - set:intersection ...
set:leading() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:leading() re
turns the nodes in one node-set that come before the first node in the other node-set. syntax set:leading(nodeset1, nodeset2) parameters nodeset1 the node set to find nodes in that precede the first node in the second node set. nodeset2 the node set to compare against. re
turns a node-set containing the nodes from nodeset1 whose values precede the first node in nodeset2. note: if the first node in nodeset2 isn't contained in nodeset1, an empty set is re
turned. if nodeset2 is empty, then the result is nodeset1. specifications exslt - set:leading ...
set:trailing() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:trailing() re
turns the nodes in one node-set that come after the first node in the other node-set. syntax set:trailing(nodeset1, nodeset2) parameters nodeset1 the node set to find nodes in that follow the first node in the second node set. nodeset2 the node set to compare against. re
turns a node-set containing the nodes from nodeset1 whose values follow the first node in nodeset2. note: if the first node in nodeset2 isn't contained in nodeset1, an empty set is re
turned. if nodeset2 is empty, then the result is nodeset1. specifications exslt - set:trailing ...
str:concat() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:concat() re
turns a string containing all the string values in a node-set concatenated together. syntax str:concat(nodeset) parameters nodeset the node-set whose nodes' string values should be concatenated into one string. re
turns a string whose value is all the string values of the nodes in nodeset concatenated together. if nodeset is empty, an empty string is re
turned. specifications exslt - str:concat ...
Strings (str) - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt strings package provides functions that allow the manipulation of strings. the namespace for the strings package is http://exslt.org/strings. str:concat()str:concat() re
turns a string containing all the string values in a node-set concatenated together.str:split()str:split() splits a string using a pattern string to determine where the splits should occur, re
turning a node-set containing the resulting strings.str:tokenize()str:tokenize() splits a string using a set of characters as delimiters that determine where the splits should occur, re
turning a node-set containing the resulting strings. ...
Ajax - Developer guides
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 re
turned 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 xmlhttprequest the xmlhttprequest specification adds html parsing support to xmlhttprequest, which originally supported only xml parsing. this feature allows web apps to obtain an html resource as a parsed dom us...
Mutation events - Developer guides
ist of all mutation events, as defined in dom level 3 events specification: domattrmodified domattributenamechanged domcharacterdatamodified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives examples domnoderemovedfromdocument var isdescendant = function (desc, root) { re
turn !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); ...
Overview of events and handlers - Developer guides
de has no visible effect until a user interacts with the button either by placing the mouse pointer over the html button and clicking on the left mouse button or by placing a finger or stylus of some kind on the screen above the html button; when that happens, the buttondomelement javascript object would call the example_click_handler function with an event object as an argument. the function, in
turn, would perform whatever action was chosen by the programmer, in this case to open an html alert dialog. note that the handler has access to the ev object since it is passed as an argument; the object has information about the event, notably the time at which the event occurred. as a second example, much modern javascript integrated into web pages is wrapped into an event function call to ensure ...
Using device orientation with 3D transforms - Developer guides
to_deg = 180 / math.pi, ea = [], n = math.sqrt( rm22 * rm22 + rm20 * rm20 ); // rotation matrix to euler angles ea[1] = math.atan2( -rm21, n ); if ( n > 0.001 ) { ea[0] = math.atan2( rm01, rm11 ); ea[2] = math.atan2( rm20, rm22 ); } else { ea[0] = 0; ea[2] = ( rm21 > 0 ? 1 : -1 ) * math.atan2( -rm10, rm00 ); } re
turn { alpha: -ea[0] * to_deg - 180, beta: -ea[1] * to_deg, gamma: ea[2] * to_deg }; } ...
Using HTML sections and outlines - Developer guides
this isn't a really bad thing neccessarily — sites will often have a few validation errors — but it's something to be aware of still. conclusion the new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way. they bring a big advantage for people having html5 browsers and needing the structure to help them understand th...
Localizations and character encodings - Developer guides
page's character encoding. it must be used within a <head> block. to specify that a page is using, for example, the utf-8 character encoding (as per the recommendation), simply place the following line in the <head> block: <meta charset="utf-8"> details and browser internals when the encoding is declared by web content like the html specification requires, firefox will use that encoding for
turning the bytes into the internal representation. unfortunately, using utf-8 and declaring that utf-8 was used was not always the prevalent way of offering web content. in the 1990s, it was common to leave the encoding undeclared and to use a region-specific encoding that wasn't able to represent all of unicode. firefox needs a fallback encoding that it uses for non-conforming legacy content that d...
Writing forward-compatible websites - Developer guides
it extremely probable that your code won't break in the future. sometimes browsers implement a given feature slightly differently. if you have a single code path that works in all the top engines, it means that you are either using features where browser behavior has already converged or, if the behavior hasn't quite converged yet, your code works regardless of which engine's behavior standards
turn out to uphold. browser-specific features and prefixes don't target hacks at current or future versions of browsers this is also a common instance of assuming that present correlation between bugs implies future correlation between bugs. targeting hacks at old versions of browsers whose current versions no longer have the bug you're relying on for your hack is ok; once a browser has fixed bug x...
HTML attribute: minlength - HTML: Hypertext Markup Language
ngth is specified, or an invalid value is specified, the input has no minimum length. this value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria. the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort re
turning true. constraint validation is only applied when the value is changed by the user. once submission fails, some browsers will display an error message indicating the minimum length required and the current length. examples by adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">enter a fruit name that is at least 5 letters long</la...
Date and time formats used in HTML - HTML: Hypertext Markup Language
e strings that specify these values are described in this article. elements that use such formats include certain forms of the <input> element that let the user choose or specify a date, time, or both, as well as the <ins> and <del> elements, whose datetime attribute specifies the date or date and time at which the insertion or deletion of content occurred. for <input>, the values of type that re
turn a value which contains a string representing a date and/or time are: date datetime datetime-local month time week examples before getting into the intricacies of how date and time strings are written and parsed in html, here are some examples that should give you a good idea what the more commonly-used date and time string formats look like. example html date and time strings ...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
expansion or definition outside the flow of the document's content, use <abbr> with an appropriate title. to define an abbreviation which may be unfamiliar to the reader, present the term using <abbr> and either a title attribute or inline text providing the definition. when an abbreviation's presence in the text needs to be semantically noted, the <abbr> element is useful. this can be used, in
turn, for styling or scripting purposes. you can use <abbr> in concert with <dfn> to establish definitions for terms which are abbreviations or acronyms. see the example defining an abbreviation below. grammar considerations in languages with grammatical number (that is, languages where the number of items affects the grammar of a sentence), use the same grammatical number in your title attribute ...
<br>: The Line Break element - HTML: Hypertext Markup Language
it is useful for writing a poem or an address, where the division of lines is significant. 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. as you can see from the above example, a <br> element is included at each point where we want the text to break. the text after the <br> begins again at the start of the next line of the text block. note: do not use <br> to create margins between paragraphs; wrap them in <p> elements and use the css margin property to control their size. ...
<dfn>: The Definition element - HTML: Hypertext Markup Language
eviations and definitions together in some cases, you may wish to use an abbreviation for a term when defining it. this can be done by using the <dfn> and <abbr> elements in tandem, like this: html <p>the <dfn><abbr title="hubble space telescope">hst</abbr></dfn> is among the most productive scientific instruments ever constructed. it has been in orbit for over 20 years, scanning the sky and re
turning data and photographs of unprecedented quality and detail.</p> <p>indeed, the <abbr title="hubble space telescope">hst</abbr> has arguably done more to advance science than any device ever built.</p> note the <abbr> element nested inside the <dfn>. the former establishes that the term is an abbreviation ("hst") and specifies the full term ("hubble space telescope") in its title attribute. the...
<input type="checkbox"> - HTML: Hypertext Markup Language
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. note: radio buttons are similar to checkboxes, but with an important distinction — radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to
turn single values on and off. where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. value a domstring representing the value of the checkbox. events change and input supported common attributes checked idl attributes checked, indeterminate and value meth...
<input type="date"> - HTML: Hypertext Markup Language
; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">. we create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will re
turn text, because the date type falls back to type text. if <input type="date"> isn't supported, we hide the native picker and show the fallback (<select>) instead. // define variables var nativepicker = document.queryselector('.nativedatepicker'); var fallbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = docum...
<input type="datetime-local"> - HTML: Hypertext Markup Language
+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="datetime-local">, we create a new <input> element, try setting its type to datetime-local, then immediately check what its type is set to. browsers that don't support datetime-local re
turn text, since that's what datetime-local falls back to. if <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker ui (<select>) instead. // define variables var nativepicker = document.queryselector('.nativedatetimepicker'); var fallbackpicker = document.queryselector('.fallbackdatetimepicker'); var fallbacklabel = document.queryselector('.fallbackla...
<input type="hidden"> - HTML: Hypertext Markup Language
no scripting is needed in the content to handle this. the output looks like this: note: you can also find the example on github (see the source code, and also see it running live). when submitted, the form data sent to the server will look something like this: title=my+excellent+blog+post&content=this+is+the+content+of+m...
<input type="month"> - HTML: Hypertext Markup Language
se and to set up the list of years to include in the non-native year <select> follows. the part of the example that may be of most interest is the feature detection code. in order to detect whether the browser supports <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to. browsers that don't support type month will re
turn text, since that's what month falls back to when not supported. if <input type="month"> is not supported, we hide the native picker and show the fallback picker ui instead. // define variables var nativepicker = document.queryselector('.nativedatepicker'); var fallbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearse...
<input type="radio"> - HTML: Hypertext Markup Language
/github.com/mdn/interactive-examples and send us a pull request. they are called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below. note: checkboxes are similar to radio buttons, but with an important distinction: radio buttons are designed for selecting one value out of a set, whereas checkboxes let you
turn individual values on and off. where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. value a domstring representing the value of the radio button. events change and input supported common attributes checked and value idl attributes checked and value m...
<input type="submit"> - HTML: Hypertext Markup Language
e a string specifying the encoding type to use for the form data formmethod the http method (get or post) to use when submitting the form. formnovalidate a boolean which, if present, means the form's fields will not be subjected to constraint validation before submitting the data to the server formtarget the browsing context into which to load the response re
turned by the server after submitting the form formaction a string indicating the url to which to submit the data. this takes precedence over the action attribute on the <form> element that owns the <input>. this attribute is also available on <input type="image"> and <button> elements. formenctype a string that identifies the encoding method to use when submitting the form data to the serv...
<input type="time"> - HTML: Hypertext Markup Language
if <input type="time"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. // define variables var nativepicker = document.queryselector('.nativetimepicker'); var fallbackpicker = document.queryselector('.fallbacktimepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var hourse...
<input type="week"> - HTML: Hypertext Markup Language
; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code. to detect whether the browser supports <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to. non-supporting browsers will re
turn text, because the week type falls back to type text. if <input type="week"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. // define variables var nativepicker = document.queryselector('.nativeweekpicker'); var fallbackpicker = document.queryselector('.fallbackweekpicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearse...
<isindex> - HTML: Hypertext Markup Language
its support depended on both the browser and the server to react to the query. <isindex> is removed html standard. it was deprecated in html 4.01. the same behaviour can be achieved with an html form. all major browsers have now removed <isindex>. attributes like all other html elements, this element accepted the global attributes. ...
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
><a name="z18">ninth section heading</a></h1><p> ... whatever ... </p> <h2><a name="z19">tenth section heading</a></h1><p> ... whatever ... </p> </body> </html> they then forward a copy of this document to someone with a next editor, and they delete sections z7 and z19, add ten more, z20 through z29, and then delete paragraphs z24 and z29. so then the nextid value is z30 when it's re
turned modified: <html> <head> <title> ... whatever ... </title> <link, meta, base, etc. as applicable for the head of this document> <nextid n="z30"> </head> <body> <a name="z0" href="#z4">first section heading</a> <a name="z1" href="#z5">second section heading</a> <a name="z8" href="#z14">newly inserted third section heading</a> <...
<noscript> - HTML: Hypertext Markup Language
content categories metadata content, flow content, phrasing content. permitted content when scripting is disabled and when it is a descendant of the <head> element: in any order, zero or more <link> elements, zero or more <style> elements, and zero or more <meta> elements. when scripting is disabled and when it isn't a descendant of the <head> element: any transparent content, but no <noscript> element must be among its descendants. ...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
property instead. usage notes typically, ordered list items display with a preceding marker, such as a number or letter. the <ol> and <ul> elements may nest as deeply as desired, alternating between <ol> and <ul> however you like. the <ol> and <ul> elements both represent a list of items. the difference is with the <ol> element, the order is meaningful. for example: steps in a recipe
turn-by-
turn directions the list of ingredients in decreasing proportion on nutrition information labels to determine which list to use, try changing the order of the list items; if the meaning changes, use the <ol> element — otherwise you can use <ul>. examples simple example <ol> <li>fee</li> <li>fi</li> <li>fo</li> <li>fum</li> </ol> the above html will output: using roman nume...
<textarea> - HTML: Hypertext Markup Language
ements. maxlength the maximum number of characters (utf-16 code units) that the user can enter. if this value isn't specified, the user can enter an unlimited number of characters. minlength the minimum number of characters (utf-16 code units) required that the user should enter. name the name of the control. placeholder a hint to the user of what can be entered in the control. carriage re
turns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint. note: placeholders should only be used to show an example of the type of data that should be entered into a form; they are not a substitute for a proper <label> element tied to the input. see labels and placeholders in <input>: the input (form input) element for a full explanation. readonly thi...
inputmode - HTML: Hypertext Markup Language
ot show a minus key (-). numeric numeric input keyboard, but only requires the digits 0–9. devices may or may not show a minus key. tel a telephone keypad input, including the digits 0–9, the asterisk (*), and the pound (#) key. inputs that require a telephone number should typically use <input type="tel">instead. search a virtual keyboard optimized for search input. for instance, the re
turn/submit key may be labeled "search", along with possible other optimizations. inputs that require a search query should typically use <input type="search"> instead. email a virtual keyboard optimized for entering email addresses. typically includes the @ character as well as other optimizations. inputs that require email addresses should typically use <input type="email"> instead. url a keypad...
title - HTML: Hypertext Markup Language
0a line feed (lf) character represents a line break. some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in
turn may inherit it from its parent, and so on. if this attribute is set to the empty string, it means its ancestors' titles are irrelevant and shouldn't be used in the tooltip for this element. html <div title="cooltip"> <p>hovering here will show “cooltip”.</p> <p title="">hovering here will show nothing.</p> </div> result accessibility concerns use of the title attribute is highly p...
x-ms-format-detection - HTML: Hypertext Markup Language
rs, are automatically converted to followable links. existing links, such as ones with the tel: scheme, are unaffected. links created through format detection do not appear in the dom. this proprietary property is specific to internet explorer and microsoft edge. syntax <html x-ms-format-detection="none"> value all all supported data formats are detected. none format detection is
turned off. phone phone number patterns are autolinked. ...
Link types: noopener - HTML: Hypertext Markup Language
the noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it re
turns null). this is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the window.opener property (see about rel=noopener for more details), while still providing the referer http header (unless noreferrer is used as well). note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab. specifications specifi...
Link types - HTML: Hypertext Markup Language
re is commercial relationship between the two (sold link). this link type may be used by some search engines that use popularity ranking techniques. <a>, <area>, <form> <link> noopener instructs the browser to open the link without granting the new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it re
turns null). this is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the window.opener property (see about rel=noopener for more details), while still providing the referer http header (unless noreferrer is used as well). note that when noopener is used, nonempty target names other than _top, _self, and _parent are...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
ering machinery kicks in. this ensures they are available earlier and are less likely to block the page's render, improving performance. this article provides a basic guide to how <link rel="preload"> works. the basics you most commonly use <link> to load a css file to style your page with: <link rel="stylesheet" href="styles/main.css"> here however, we will use a rel value of preload, which
turns <link> into a preloader for any resource we want. you will also need to specify: the path to the resource in the href attribute. the type of resource in the as attribute. a simple example might look like this (see our js and css example source, and also live): <head> <meta charset="utf-8"> <title>js and css preload example</title> <link rel="preload" href="style.css" as="style"> ...
Using the application cache - HTML: Hypertext Markup Language
shed). structure of a cache manifest file cache manifest files must be served with the text/cache-manifest mime type. all resources served using this mime type must follow the syntax for an application cache manifest, as defined in this section. cache manifests are utf-8 format text files, and may optionally include a bom character. newlines may be represented by line feed (u+000a), carriage re
turn (u+000d), or carriage re
turn and line feed both. the first line of the cache manifest must consist of the string cache manifest (with a single u+0020 space between the two words), followed by zero or more space or tab characters. any other text on the line is ignored. the remainder of the cache manifest must be comprised of zero or more of the following lines: blank line you may use blank l...
Identifying resources on the Web - HTTP
web, a path like this represented a physical file location on the web server. nowadays, it is mostly an abstraction handled by web servers without any physical reality. query ?key1=value1&key2=value2 are extra parameters provided to the web server. those parameters are a list of key/value pairs separated with the & symbol. the web server can use those parameters to do extra stuff before re
turning the resource to the user. each web server has its own rules regarding parameters, and the only reliable way to know how a specific web server is handling parameters is by asking the web server owner. fragment #somewhereinthedocument is an anchor to another part of the resource itself. an anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to sho...
MIME types (IANA media types) - HTTP
reaking a large message into smaller ones automatically to be reassembled by the recipient. multipart list at iana data that is comprised of multiple components which may individually have different mime types. examples include multipart/form-data (for data produced using the formdata api) and multipart/byteranges (defined in rfc 7233: 5.4.1 and used with http's 206 "partial content" response re
turned when the fetched data is only part of the content, such as is delivered using the range header). important mime types for web developers application/octet-stream this is the default for binary files. as it means unknown binary file, browsers usually don't execute it, or even ask if it should be executed. they treat it as if the content-disposition header was set to attachment, and propose a...
Reason: CORS request did not succeed - HTTP
ror. trying to access an http resource from a page with an https origin will also cause this error. as of firefox 68, https pages are not permitted to access http://localhost, although this may be changed by bug 1488740. the server did not respond to the actual request (even if it responded to the preflight request). one scenario might be an http service being developed that panicked without re
turning any data. ...
Reason: CORS disabled - HTTP
reason reason: cors disabled what went wrong? a request that needs to use cors was attempted, but cors is disabled in the user's browser. when this happens, the user needs to
turn cors back on in their browser. in firefox, the preference that disables cors is content.cors.disable. setting this to true disables cors, so whenever that's the case, cors requests will always fail with this error. ...
Content Security Policy (CSP) - HTTP
here section 1.1). browsers that don't support it still work with servers that implement it, and vice-versa: browsers that don't support csp simply ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. if the site doesn't offer the csp header, browsers likewise use the standard same-origin policy. to enable csp, you need to configure your web server to re
turn the content-security-policy http header. (sometimes you may see mentions of the x-content-security-policy header, but that's an older version and you don't need to specify it anymore.) alternatively, the <meta> element can be used to configure a policy, for example: <meta http-equiv="content-security-policy" content="default-src 'self'; img-src https://*; child-src 'none';"> threats mitigating...
HTTP conditional requests - HTTP
ere is one potential problem: if the downloaded resource has been modified between both downloads, the obtained ranges will correspond to two different versions of the resource, and the final document will be corrupted. to prevent this, conditional requests are used. for ranges, there are two ways of doing this. the more flexible one makes use of if-unmodified-since and if-match and the server re
turns an error if the precondition fails; the client then restarts the download from the beginning: even if this method works, it adds an extra response/request exchange when the document has been changed. this impairs performance, and http has a specific header to avoid this scenario: if-range: this solution is more efficient, but slightly less flexible, as only one etag can be used in the cond...
Configuring servers for Ogg media - HTTP
aren't yet downloaded, gecko uses http 1.1 byte-range requests to retrieve the media from the seek target position. in addition, gecko uses byte-range requests to seek to the end of the media (assuming you serve the content-length header) in order to determine the duration of the media. your server should accept the accept-ranges: bytes http header if it can accept byte-range requests. it must re
turn 206: partial content to all byte range requests; otherwise, browsers can't be sure you actually support byte range requests. your server must also re
turn 206: partial content for the request range: bytes=0- as well. include regular key frames when the browser seeks through ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode th...
Content negotiation - HTTP
a wiki page from whatwg. html5 provides alternatives to content negotiation via, for example, the <source> element. principles of content negotiation a specific document is called a resource. when a client wants to obtain a resource, the client requests it using its url. the server uses this url to choose one of the variants it provides – each variant being called a representation – and re
turns a specific representation to the client. the overall resource, as well as each of the representations, have a specific url. how a specific representation is chosen when the resource is called is determined by content negotiation and there are several ways of negotiating between the client and the server. the determination of the best suited representation is made through one of two mechanisms...
Using Feature Policy - HTTP
olicy that disables the features. for new content, you can start developing with a policy that disables all the features. this approach ensures that none of the functionality is introduced. when applying a policy to existing content, testing is likely required to verify it continues to work as expected. this is especially important for embedded or third-party content that you do not control. to
turn on the enforcement of all the best practices, specify the policy as below. send the following the http header: feature-policy: layout-animations 'none'; unoptimized-images 'none'; oversized-images 'none'; sync-script 'none'; sync-xhr 'none'; unsized-media 'none'; using the <iframe> allow attribute: <iframe src="https://example.com..." allow="layout-animations 'none'; unoptimized-images 'none'...
Feature Policy - HTTP
s varies and depends on several factors. the general principle is that there should be an intuitive or non-breaking way for web developers to detect or handle the case when the feature is disabled. newly introduced features may have an explicit api to signal the state. existing features that later integrate with feature policy will typically use existing mechanisms. some approaches include: re
turn "permission denied" for javascript apis that require user permission grants. re
turn false or error from an existing javascript api that provides access to feature. change the default values or options that control the feature behavior. the current set of policy-controlled features fall into two broad categories: enforcing best practices for good user experiences. providing granular contro...
Access-Control-Allow-Credentials - HTTP
he access-control-allow-credentials value is true. credentials are cookies, authorization headers or tls client certificates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. note that simple get requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not re
turned with the resource, the response is ignored by the browser and not re
turned to web content. the access-control-allow-credentials header works in conjunction with the xmlhttprequest.withcredentials property or with the credentials option in the request() constructor of the fetch api. for a cors request with credentials, in order for browsers to expose the response to frontend javascript code, bo...
Access-Control-Allow-Origin - HTTP
ctives * for requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. if the server supports clients from multiple origins, it must re
turn the origin for the specific client making the request. null specifies the origin "null". note: null should not be used: "it may seem safe to re
turn access-control-allow-origin: "null", but the serialization of the origin of any resource that uses a non-hierarchical scheme (such as data: or file:) and sandboxed documents is defined to be "null". many user agents will grant such documents access...
Content-Disposition - HTTP
data format that makes use of the content-disposition header: post /test.html http/1.1 host: example.org content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-data; name="field1" value1 --boundary content-disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- specifications specification title rfc 7578 re
turning values from forms: multipart/form-data rfc 6266 use of the content-disposition header field in the hypertext transfer protocol (http) rfc 2183 communicating presentation information in internet messages: the content-disposition header field ...
CSP: prefetch-src - HTTP
ing leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. example prefetch resources do not match header given a page with the following content security policy: content-security-policy: prefetch-src https://example.com/ fetches for the following code will re
turn network errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment content security policy level 3the definition of 'prefetch-src' in that specification. working draft initial definition. ...
Content-Type - HTTP
browsers will do mime sniffing in some cases and will not necessarily follow the value of this header; to prevent this behavior, the header x-content-type-options can be set to nosniff. in requests, (such as post or put), the client tells the server what type of data is actually sent. ...
Feature-Policy: autoplay - HTTP
the autoplay attribute on <audio> and <video> elements will be ignored. for more details on autoplay and autoplay blocking, see the article autoplay guide for media and web audio apis. ...
Feature-Policy: camera - HTTP
syntax feature-policy: camera <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Feature-Policy: encrypted-media - HTTP
syntax feature-policy: encrypted-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Feature-Policy: fullscreen - HTTP
by default, top-level documents and their same-origin child frames can request and enter fullscreen mode. this directive allows or prevents cross-origin frames from using fullscreen mode. this includes same-origin frames. if both this directive (i.e. via the allow attribute) and the allowfullscreen attribute are present on an <iframe> element, this directive takes precedence. ...
Feature-Policy: microphone - HTTP
syntax feature-policy: microphone <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Feature-Policy: midi - HTTP
syntax feature-policy: midi <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. ...
Feature-Policy: xr-spatial-tracking - HTTP
the http feature-policy header xr-spatial-tracking directive controls whether the current document is allowed to use the webxr device api. this policy controls whether navigator.xr.requestsession() can re
turn xrsession that requires spatial tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.issessionsupported() and devicechange event on navigator.xr object. syntax feature-policy: xr-spatial-tracking <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsin...
If-Match - HTTP
yte only. if a listed etag has the w/ prefix indicating a weak entity tag, it will never match under this comparison algorithm. there are two common use cases: for get and head methods, used in combination with a range header, it can guarantee that the new ranges requested comes from the same resource than the previous one. if it doesn't match, then a 416 (range not satisfiable) response is re
turned. for other methods, and in particular for put, if-match can be used to prevent the lost update problem. it can check if the modification of a resource that the user wants to upload will not override another change that has been done since the original resource was fetched. if the request cannot be fulfilled, the 412 (precondition failed) response is re
turned. header type request ...
If-None-Match - HTTP
ader makes the request conditional. for get and head methods, the server will send back the requested resource, with a 200 status, only if it doesn't have an etag matching the given ones. for other methods, the request will be processed only if the eventually existing resource's etag doesn't match any of the values listed. when the condition fails for get and head methods, then the server must re
turn http status code 304 (not modified). for methods that apply server-side changes, the status code 412 (precondition failed) is used. note that the server generating a 304 response must generate any of the following header fields that would have been sent in a 200 (ok) response to the same request: cache-control, content-location, date, etag, expires, and vary. the comparison with the stored etag ...
Location - HTTP
cation and content-location are different: location indicates the target of a redirection (or the url of a newly created resource), while content-location indicates the direct url to use to access the resource when content negotiation happened, without the need of further content negotiation. location is a header associated with the response, while content-location is associated with the entity re
turned. header type response header forbidden header name no syntax location: <url> directives <url> a relative (to the request url) or absolute url. examples location: /index.html specifications specification title rfc 7231, section 7.1.2: location hypertext transfer protocol (http/1.1): semantics and content ...
Server-Timing - HTTP
tion and value server-timing: cache;desc="cache read";dur=23.2 // two metrics with value server-timing: db;dur=53, app;dur=47.2 // server-timing as trailer trailer: server-timing --- response body --- server-timing: total;dur=123.4 privacy and security the server-timing header may expose potentially sensitive application and infrastructure information. consider to control which metrics are re
turned when and to whom on the server side. for example, you could only show metrics to authenticated users and nothing to the public. performanceservertiming interface in addition to having server-timing header metrics appear in the developer tools of the browser, the performanceservertiming interface enables tools to automatically collect and process metrics from javascript. this interface is rest...
Strict-Transport-Security - HTTP
acker. strict transport security resolves this problem; as long as you've accessed your bank's web site once using https, and the bank's web site uses strict transport security, your browser will know to automatically use only https, which prevents hackers from performing this sort of man-in-the-middle attack. how the browser handles it the first time your site is accessed using https and it re
turns the strict-transport-security header, the browser records this information, so that future attempts to load the site using http will automatically use https instead. when the expiration time specified by the strict-transport-security header elapses, the next attempt to load the site via http will proceed as normal instead of automatically using https. whenever the strict-transport-security hea...
X-DNS-Prefetch-Control - HTTP
o anything to manage prefetching. however, the user may wish to disable prefetching. on firefox, this can be done by setting the network.dns.disableprefetch preference to true. also, by default, prefetching of embedded link hostnames is not performed on documents loaded over https. on firefox, this can be changed by setting the network.dns.disableprefetchfromhttps preference to false. examples
turning on and off prefetching you can either send the x-dns-prefetch-control header server-side, or from individual documents, using the http-equiv attribute on the <meta> element, like this: <meta http-equiv="x-dns-prefetch-control" content="off"> you can reverse this setting by setting content to "on". forcing lookup of specific hostnames you can force the lookup of specific hostnames without...
HEAD - HTTP
for example, if a url might produce a large download, a head request could read its content-length header to check the filesize without actually downloading the file. a response to a head method should not have a body. if it has one anyway, that body must be ignored: any entity headers that might describe the erroneous body are instead assumed to describe the response which a similar get request would have received. if the response to a head request shows that a cached url response is now outdated, the cached copy is invalidated even if no get request was made. ...
Protocol upgrade mechanism - HTTP
the client will validate before delivering the upgrade response to you. the server's response's sec-websocket-accept header will have a value computed based upon the specified key. sec-websocket-protocol the sec-websocket-protocol header specifies one or more websocket protocols that you wish to use, in order of preference. the first one that is supported by the server will be selected and re
turned by the server in a sec-websocket-protocol header included in the response. you can use this more than once in the header, as well; the result is the same as if you used a comma-delineated list of subprotocol identifiers in a single header. sec-websocket-protocol: subprotocols subprotocols a comma-separated list of subprotocol names, in the order of preference. the subprotocols may be selec...
Proxy servers and tunneling - HTTP
.pac and the mime type set to: application/x-ns-proxy-autoconfig the file consists of a function called findproxyforurl. the example below will work in an environment where the internal dns server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable: function findproxyforurl(url, host) { if (isresolvable(host)) re
turn "direct"; else re
turn "proxy proxy.mydomain.com:8080"; } see proxy auto-configuration (pac) for more examples. ...
HTTP Public Key Pinning (HPKP) - HTTP
ic key, the client should present a warning to the user. firefox and chrome disable pin validation for pinned hosts whose validated certificate chain terminates at a user-defined trust anchor (rather than a built-in trust anchor). this means that for users who imported custom root certificates all pinning violations are ignored. enabling hpkp to enable this feature for your site, you need to re
turn the public-key-pins http header when your site is accessed over https: public-key-pins: pin-sha256="base64=="; max-age=expiretime [; includesubdomains][; report-uri="reporturi"] pin-sha256 the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorit...
HTTP range requests - HTTP
lue, indicating no support. in some apps, download managers disable their pause buttons in that case. curl -i https://www.youtube.com/watch?v=ewtz2xpqwpa http/1.1 200 ok ... accept-ranges: none requesting a specific range from a server if the server supports range requests, you can issue such a request by using the range header. it indicates the part(s) of a document that the server should re
turn. single part ranges we can request a single range from a resource. again, we can test a request by using curl. the "-h" option will append a header line to the request, which in this case is the range header requesting the first 1024 bytes. curl http://i.imgur.com/z4d4kwk.jpg -i -h "range: bytes=0-1023" the issued request looks like this: get /z4d4kwk.jpg http/1.1 host: i.imgur.com range: by...
Redirections in HTTP - HTTP
keyword) can be used to set up a different redirect: redirect permanent / https://www.example.com # …acts the same as: redirect 301 / https://www.example.com the mod_rewrite module can also create redirects. it is more flexible, but a bit more complex. nginx in nginx, you create a specific server block for the content you want to redirect: server { listen 80; server_name example.com; re
turn 301 $scheme://www.example.com$request_uri; } to apply a redirect to a directory or only certain pages, use the rewrite directive: rewrite ^/images/(.*)$ https://images.example.com/$1 redirect; rewrite ^/images/(.*)$ https://images.example.com/$1 permanent; iis in iis, you use the <httpredirect> element to configure redirections. redirection loops redirection loops happen when additional re...
HTTP resources and specifications - HTTP
data" url scheme proposed standard rfc 3986 uniform resource identifier (uri): generic syntax internet standard rfc 5988 web linking defines the link header proposed standard experimental spec hypertext transfer protocol (http) keep-alive header informational (expired) draft spec http client hints ietf draft rfc 7578 re
turning values from forms: multipart/form-data proposed standard rfc 6266 use of the content-disposition header field in the hypertext transfer protocol (http) proposed standard rfc 2183 communicating presentation information in internet messages: the content-disposition header field only a subset of syntax of the content-disposition header can be used in the context ...
201 Created - HTTP
the http 201 created success status response code indicates that the request has succeeded and has led to the creation of a resource. the new resource is effectively created before this response is sent back and the new resource is re
turned in the body of the message, its location being either the url of the request, or the content of the location header. the common use case of this status code is as the result of a post request. status 201 created specifications specification title rfc 7231, section 6.3.2: 201 created hypertext transfer protocol (http/1.1): semantics and content ...
204 No Content - HTTP
the http 204 no content success status response code indicates that the request has succeeded, but that the client doesn't need to go away from its current page. a 204 response is cacheable by default. an etag header is included in such a response. the common use case is to re
turn 204 as a result of a put request, updating a resource, without changing the current content of the page displayed to the user. if the resource is created, 201 created is re
turned instead. if the page should be changed to the newly updated page, the 200 should be used instead. status 204 no content specifications specification title rfc 7231, section 6.3.5: 204 no content hypertext transfer protocol (http/1.1): semantics and content ...
406 Not Acceptable - HTTP
cept accept-charset accept-encoding accept-language in practice, this error is very rarely used. instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. it is assumed that even if the user won't be completely happy, they will prefer this to an error code. if a server re
turns such an error status, the body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. status 406 not acceptable specifications specification title rfc 7231, section 6.5.6: 406 not acceptable hypertext transfer protocol (http/1.1): semantics and content ...
413 Payload Too Large - HTTP
the http 413 payload too large response status code indicates that the request entity is larger than limits defined by server; the server might close the connection or re
turn a retry-after header field. status 413 payload too large specifications specification title rfc 7231, section 6.5.11: 413 payload too large hypertext transfer protocol (http/1.1): semantics and content ...
418 I'm a teapot - HTTP
this error is a reference to hyper text coffee pot control protocol defined in april fools' jokes in 1998 and 2014. ...
501 Not Implemented - HTTP
ty required to fulfill the request. this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not re
turn 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. a 501 error is not something you can fix, but requires a fix by the web server you are trying to access. a 501 response is cacheable by default; that is, unless caching headers instruct otherwise. status 501 not implemented specifica...
HTTP
features of the client-server protocol: what it can do and its intended uses. http cache caching is very important for fast web sites. this article describes different methods of caching and how to use http headers to control them. http cookies how cookies work is defined by rfc 6265. when serving an http request, a server can send a set-cookie http header with the response. the client then re
turns the cookie's value with every request to the same server in the form of a cookie request header. the cookie can also be set to expire on a certain date, or restricted to a specific domain and path. cross-origin resource sharing (cors) cross-site http requests are http requests for resources from a different domain than the domain of the resource making the request. for instance, an html page f...
JavaScript data types and data structures - JavaScript
t for numbers. a bigint is created by appending n to the end of an integer or by calling the constructor. you can obtain the safest value that can be incremented with numbers by using the constant number.max_safe_integer. with the introduction of bigints, you can operate with numbers beyond the number.max_safe_integer. this example demonstrates, where incrementing the number.max_safe_integer re
turns the expected result: > const x = 2n ** 53n; 9007199254740992n > const y = x + 1n; 9007199254740993n you can use the operators +, *, -, **, and % with bigints—just like with numbers. a bigint is not strictly equal to a number, but it is loosely so. a bigint behaves like a number in cases where it is converted to boolean: if, ||, &&, boolean, !. bigints cannot be operated on interchangeably...
Keyed collections - JavaScript
elements which are iterable in the order of insertion. maps map object ecmascript 2015 introduces a new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. you can use a for...of loop to re
turn an array of [key, value] for each iteration. let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' + value); }...
Character classes - JavaScript
80\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches " bar" in "foo bar". \s matches a single character other than white space. equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches "foo" in "foo bar". \t matches a horizontal tab. \r matches a carriage re
turn. \n matches a linefeed. \v matches a vertical tab. \f matches a form-feed. [\b] matches a backspace. if you're looking for the word-boundary character (\b), see boundaries. \0 matches a nul character. do not follow this with another digit. \cx matches a control character using caret notation, where "x" is a letter from a...
Deprecated and obsolete features - JavaScript
he ecma-262 standard, whose introduction states: "… programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code. …" obsolete features these obsolete features have been entirely removed from javascript and can no longer be used as of the indicated version of javascript. object property description __count__ re
turns 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. object.observe() asynchronously observing the changes to an object. object.unobserve() remove observers. object.getnotifier() ...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
of #<object> (chrome) error type typeerror in strict mode only. what went wrong? it was attempted to delete a property, but that property is non-configurable. the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. this error happens only in strict mode code. in non-strict code, the operation re
turns false. examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze(). 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // typeerror 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete ob...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
object. object properties are "qualified" if they are configurable. unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details. this error only happens in strict mode code. in non-strict code, the operation just re
turns false. examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an error in strict mode: 'use strict'; var x; // ... delete x; // syntaxerror: applying the 'delete' operator to an unqualified name // is deprecated to free the contents of a variable, you can set it to null: 'use strict'; var x; // ... x = null; // x...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
a deprecated source map syntax in a javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. the source map specification changed the syntax due to a conflict with ie whenever it was found in the page after //@cc_on was interpreted to
turn on conditional compilation in the ie jscript engine. the conditional compilation comment in ie is a little known feature, but it broke source maps with jquery and other libraries. examples deprecated syntax syntax with the "@" sign is deprecated. //@ sourcemappingurl=http://example.com/path/to/your/sourcemap.map standard syntax use the "#" sign instead. //# sourcemappingurl=http://example...
RangeError: invalid date - JavaScript
valid date (edge) rangeerror: invalid date (firefox) rangeerror: invalid time value (chrome) rangeerror: provided date is not in valid range (chrome) error type rangeerror what went wrong? a string leading to an invalid date has been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually re
turn nan. however, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar 2014').tostring(); this, however, re
turns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation. va...
SyntaxError: missing } after function body - JavaScript
ode: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); }; correct would be: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); } }; it can be more obscure when using iife, closures, or other constructs that use a lot of different parenthesis and curly brackets, for example. (function() { if (true) { re
turn false; } ); oftentimes, indenting differently or double checking indentation helps to spot these errors. (function() { if (true) { re
turn false; } }); ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
went wrong? the instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. examples instanceof vs typeof "test" instanceof ""; // typeerror: invalid 'instanceof' operand "" 42 instanceof 0; // typeerror: invalid 'instanceof' operand 0 function foo() {} var f = foo(); // foo() is called and re
turns undefined var x = new foo(); x instanceof f; // typeerror: invalid 'instanceof' operand f x instanceof x; // typeerror: x is not a function to fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number...
arguments.length - JavaScript
number of arguments actually passed to a function. this can be more or less than the defined parameter's count (see function.length). examples using arguments.length in this example we define a function that can add two or more numbers together. function adder(base /*, n2, ... */) { base = number(base); for (var i = 1; i < arguments.length; i++) { base += number(arguments[i]); } re
turn base; } note the difference between function.length and arguments.length specifications specification ecmascript (ecma-262)the definition of 'arguments exotic objects' in that specification. ...
Array() constructor - JavaScript
where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below). note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax. arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this re
turns a new javascript array with its length property set to that number (note: this implies an array of arraylength empty slots, not slots with actual undefined values). if the argument is any other number, a rangeerror exception is thrown. examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console...
Array.prototype.entries() - JavaScript
the entries() method re
turns a new array iterator object that contains the key/value pairs for each index in the array. 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 array.entries() re
turn value a new array iterator object. examples iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ...
Array.prototype.keys() - JavaScript
the keys() method re
turns a new array iterator object that contains the keys for each index in the array. 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 arr.keys() re
turn value a new array iterator object. examples key iterator doesn't ignore holes var arr = ['a', , 'c']; var sparsekeys = object.keys(arr); var densekeys = [...arr.keys()]; console.log(sparsekeys); // ['0', '2'] console.log(densekeys); // [0, 1, 2] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.keys' in that specification. ...
Array.prototype.length - JavaScript
the value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. 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 value of the length property is an integer with a positive sign and a value less than 2 to the 32nd power (232). ...
Array.prototype.shift() - JavaScript
the shift() method removes the first element from an array and re
turns that removed element. this method changes the length of the array. 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 arr.shift() re
turn value the removed element from the array; undefined if the array is empty. description the shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then re
turns the removed value. if the length property is 0, undefined is re
turned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. objects which do not conta...
Array.prototype.splice() - JavaScript
rray will be deleted. note: in ie8, it won't delete all when deletecount is omitted. if deletecount is 0 or negative, no elements are removed. in this case, you should specify at least one new element (see below). item1, item2, ... optional the elements to add to the array, beginning from start. if you do not specify any elements, splice() will only remove elements from the array. re
turn value an array containing the deleted elements. if only one element is removed, an array of one element is re
turned. if no elements are removed, an empty array is re
turned. description if the specified number of elements to insert differs from the number of elements being removed, the array's length will be changed. examples remove 0 (zero) elements before index 2, and insert "drum" let m...
Array.prototype.unshift() - JavaScript
description the unshift method inserts the given values to the beginning of an array-like object. unshift is intentionally generic. this method can be called or applied to objects resembling arrays. objects which do not contain a length property—reflecting the last in a series of consecutive, zero-based numerical properties—may not behave in any meaningful manner. ...
Array.prototype.values() - JavaScript
examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. ...
ArrayBuffer() constructor - JavaScript
ybuffer() constructor is used to create arraybuffer objects. 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 new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create. re
turn value a new arraybuffer object of the specified size. its contents are initialized to 0. exceptions a rangeerror is thrown if the length is larger than number.max_safe_integer (>= 2 ** 53) or negative. compatibility notes starting with ecmascript 2015, arraybuffer constructors require to be constructed with a new operator. calling an arraybuffer constructor as a function without new, will th...
ArrayBuffer.prototype.byteLength - JavaScript
tory. 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 bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when the array is constructed and cannot be changed. this property re
turns 0 if this arraybuffer has been detached. examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification. ...
ArrayBuffer.isView() - JavaScript
ssed value is one of the arraybuffer views, such as typed array objects or a dataview. 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 arraybuffer.isview(value) parameters value the value to be checked. re
turn value true if the given argument is one of the arraybuffer views; otherwise, false. examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10))...
ArrayBuffer.prototype.slice() - JavaScript
the slice() method re
turns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive. 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 arraybuffer.slice(begin[, end]) parameters begin zero-based byte index at which to begin slicing. end optional byte index before which to end slicing. if end is unspecified, the new arraybuffer contains all bytes from begin to the end of this arraybuffer. re
turn value a new arraybuffer object. description the slice() method copies up to, but not including, the byte indicated by the end parameter. if eithe...
Atomics.isLockFree() - JavaScript
the static atomics.islockfree() method is used to determine whether to use locks or atomic operations. it re
turns true, if the given size is one of the bytes_per_element property of integer typedarray types. 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 atomics.islockfree(size) parameters size the size in bytes to check. re
turn value a boolean indicating whether the operation is lock free. examples using islockfree atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.islockfree(3); // false atomics.islockfree(4); // true atomics.islockfree(5); // false atomics.islockfree(6); //...
Atomics.store() - JavaScript
the static atomics.store() method stores a given value at the given position in the array and re
turns that value. 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 atomics.store(typedarray, index, value) parameters typedarray an integer typed array. one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array. index the position in the typedarray to store a value in. value the number to store. re
turn value the value that has been stored. exceptions throws a typeerror, if typedarray is not one of the allowed integer types. throws a rangeerror...
BigInt() constructor - JavaScript
syntax bigint(value); parameters value the numeric value of the object being created. may be a string or an integer. note: bigint() is not used with the new operator. ...
BigInt.asIntN() - JavaScript
he 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 bigint.asintn(width, bigint); parameters width the amount of bits available for the integer size. bigint the integer to clamp to fit into the supplied bits. re
turns the value of bigint modulo 2width as a signed integer. examples staying in 64-bit ranges the bigint.asintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** (64n - 1n) - 1n; bigint.asintn(64, max); // ↪ 9223372036854775807n bigint.asintn(64, max + 1n); // ↪ -9223372036854775807n // negative because of overflow specifications specification ...
BigInt.asUintN() - JavaScript
e 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 bigint.asuintn(width, bigint); parameters width the amount of bits available for the integer size. bigint the integer to clamp to fit into the supplied bits. re
turns the value of bigint modulo 2width as an unsigned integer. examples staying in 64-bit ranges the bigint.asuintn() method can be useful to stay in the range of 64-bit arithmetic. const max = 2n ** 64n - 1n; bigint.asuintn(64, max); // ↪ 18446744073709551615n bigint.asuintn(64, max + 1n); // ↪ 0n // zero because of overflow specifications specification ecmascript ...
BigInt.prototype.valueOf() - JavaScript
the valueof() method re
turns the wrapped primitive value of a bigint object. 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 bigintobj.valueof() re
turn value a bigint representing the primitive value of the specified bigint object. examples using valueof typeof object(1n); // object typeof object(1n).valueof(); // bigint specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.valueof()' in that specification. ...
Boolean.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object. syntax booleanobj.tosource() boolean.tosource() re
turn value a string representing the source code of the object. examples native function for the built-in boolean object, tosource re
turns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard. ...
Boolean - JavaScript
e of true do not use a boolean object in place of a boolean primitive. note: when the non-standard property document.all is used as an argument for this constructor, the result is a boolean object with the value false. this property is legacy and non-standard and should not be used. constructor boolean() creates a new boolean object. instance methods boolean.prototype.tostring() re
turns a string of either true or false depending upon the value of the object. overrides the object.prototype.tostring() method. boolean.prototype.valueof() re
turns the primitive value of the boolean object. overrides the object.prototype.valueof() method. examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new bo...
DataView() constructor - JavaScript
ting arraybuffer or sharedarraybuffer to use as the storage backing the new dataview object. byteoffset optional the offset, in bytes, to the first byte in the above buffer for the new view to reference. if unspecified, the buffer view starts with the first byte. bytelength optional the number of elements in the byte array. if unspecified, the view's length will match the buffer's length. re
turn value a new dataview object representing the specified data buffer. (that probably wasn't a very helpful description.) you can think of the re
turned object as an "interpreter" of the array buffer of bytes — it knows how to convert numbers to fit within the buffer correctly, both when reading and writing to it. this means handling integer and float conversion, endianness, and other details of ...
DataView.prototype.byteLength - JavaScript
ples and send us a pull request. description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when an dataview is constructed and cannot be changed. if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be re
turned. examples using the bytelength property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constr...
DataView.prototype.getBigInt64() - JavaScript
, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getbigint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications ...
DataView.prototype.getBigUint64() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getbiguint64(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications ...
DataView.prototype.getFloat32() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getfloat32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a signed 32-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specificat...
DataView.prototype.getFloat64() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getfloat64(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a signed 64-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specificat...
DataView.prototype.getInt16() - JavaScript
ect, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a signed 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specificatio...
DataView.prototype.getInt32() - JavaScript
ct, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getint32(byteoffset [, littleendian]) parameters byteoffset the offset, in bytes, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value a signed 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specificatio...
DataView.prototype.getInt8() - JavaScript
from the start of the dataview. 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 dataview.getint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. re
turn value a signed 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications ...
DataView.prototype.getUint16() - JavaScript
ct, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getuint16(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value an unsigned 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifi...
DataView.prototype.getUint32() - JavaScript
ct, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dataview.getuint32(byteoffset [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to read the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. re
turn value an unsigned 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifi...
DataView.prototype.getUint8() - JavaScript
rom the start of the dataview. 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 dataview.getuint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. re
turn value an unsigned 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specificat...
DataView.prototype.setBigInt64() - JavaScript
he view to store the data from. value the value to set as a bigint. the highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). upon overflow, it will be negative (-9223372036854775808n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'data...
DataView.prototype.setBigUint64() - JavaScript
ytes, from the start of the view to store the data from. value the value to set as a bigint. the highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). upon overflow, it will be zero (0n). littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such that it would store beyond the end of the view. examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'd...
DataView.prototype.setFloat32() - JavaScript
interactive-examples and send us a pull request. syntax dataview.setfloat32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.pr...
DataView.prototype.setFloat64() - JavaScript
interactive-examples and send us a pull request. syntax dataview.setfloat64(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.pr...
DataView.prototype.setInt16() - JavaScript
mdn/interactive-examples and send us a pull request. syntax dataview.setint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototyp...
DataView.prototype.setInt32() - JavaScript
mdn/interactive-examples and send us a pull request. syntax dataview.setint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototyp...
DataView.prototype.setInt8() - JavaScript
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 dataview.setint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.s...
DataView.prototype.setUint16() - JavaScript
dn/interactive-examples and send us a pull request. syntax dataview.setuint16(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.proto...
DataView.prototype.setUint32() - JavaScript
dn/interactive-examples and send us a pull request. syntax dataview.setuint32(byteoffset, value [, littleendian]) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is written. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.proto...
DataView.prototype.setUint8() - JavaScript
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 dataview.setuint8(byteoffset, value) parameters byteoffset the offset, in byte, from the start of the view where to store the data. value the value to set. re
turn value undefined. errors thrown rangeerror thrown if the byteoffset is set such as it would store beyond the end of the view. examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototyp...
Date.prototype.getMilliseconds() - JavaScript
the getmilliseconds() method re
turns the milliseconds in the specified date according to local time. 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 dateobj.getmilliseconds() re
turn value a number, between 0 and 999, representing the milliseconds for the given date according to local time. examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmill...
Date.prototype.getUTCMilliseconds() - JavaScript
this method is a companion to the other utc based methods that give hour portion, minute portion, etc.; this method gives milliseconds portion. not to be confused with unix epoch time. to get total milliseconds since 1970/01/01, use the method ".gettime()". examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds. ...
Date.now() - JavaScript
the static date.now() method re
turns the number of milliseconds elapsed since january 1, 1970 00:00:00 utc. syntax var timeinms = date.now(); re
turn value a number representing the milliseconds elapsed since the unix epoch. polyfill this method was standardized in ecma-262 5th edition. engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { re
turn new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59...
Date.prototype.setDate() - JavaScript
e object relative to the beginning of the currently set month. 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 dateobj.setdate(dayvalue) parameters dayvalue an integer representing the day of the month. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the given date (the date object is also changed in place). description if the dayvalue is outside of the range of date values for the month, setdate() will update the date object accordingly. for example, if 0 is provided for dayvalue, the date will be set to the last day of the previous month. if a negative number is p...
Date.prototype.setMilliseconds() - JavaScript
ccording to local time. 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 dateobj.setmilliseconds(millisecondsvalue) parameters millisecondsvalue a number between 0 and 999, representing the milliseconds. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you specify a number outside the expected range, the date information in the date object is updated accordingly. for example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds. examples using setmilliseconds() var thebigday = new date(); ...
Date.prototype.setMinutes() - JavaScript
ue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values re
turned from getseconds() and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setminutes() attempts to update the date information in the date object accordingly. for e...
Date.prototype.setSeconds() - JavaScript
eractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.setseconds(secondsvalue[, msvalue]) versions prior to javascript 1.3 dateobj.setseconds(secondsvalue) parameters secondsvalue an integer between 0 and 59, representing the seconds. msvalue optional. a number between 0 and 999, representing the milliseconds. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the msvalue parameter, the value re
turned from the getmilliseconds() method is used. if a parameter you specify is outside of the expected range, setseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for seconds...
Date.prototype.setTime() - JavaScript
1970, 00:00:00 utc. 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 dateobj.settime(timevalue) parameters timevalue an integer representing the number of milliseconds since 1 january 1970, 00:00:00 utc. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date (effectively, the value of the argument). description use the settime() method to help assign a date and time to another date object. examples using settime() var thebigday = new date('july 1, 1999'); var sameasbigday = new date(); sameasbigday.settime(thebigday.gettime()); specifications s...
Date.prototype.setUTCDate() - JavaScript
a specified date according to universal time. 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 dateobj.setutcdate(dayvalue) parameters dayvalue an integer from 1 to 31, representing the day of the month. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if a parameter you specify is outside of the expected range, setutcdate() attempts to update the date information in the date object accordingly. for example, if you use 40 for dayvalue, and the month stored in the date object is june, the day will be changed to 10 and the month will be incre...
Date.prototype.setUTCFullYear() - JavaScript
earvalue[, monthvalue[, dayvalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995. monthvalue optional. an integer between 0 and 11 representing the months january through december. dayvalue optional. an integer between 1 and 31 representing the day of the month. if you specify the dayvalue parameter, you must also specify the monthvalue. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the monthvalue and dayvalue parameters, the values re
turned from the getutcmonth() and getutcdate() methods are used. if a parameter you specify is outside of the expected range, setutcfullyear() attempts to update the other parameters and the date information in the da...
Date.prototype.setUTCMilliseconds() - JavaScript
g to universal time. 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 dateobj.setutcmilliseconds(millisecondsvalue) parameters millisecondsvalue a number between 0 and 999, representing the milliseconds. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if a parameter you specify is outside of the expected range, setutcmilliseconds() attempts to update the date information in the date object accordingly. for example, if you use 1100 for millisecondsvalue, the seconds stored in the date object will be incremented by 1, and 100 will be used fo...
Date.prototype.setUTCMinutes() - JavaScript
ue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values re
turned from getutcseconds() and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutcminutes() attempts to update the date information in the date object according...
Date.prototype.setUTCMonth() - JavaScript
tory. 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 dateobj.setutcmonth(monthvalue[, dayvalue]) parameters monthvalue an integer between 0 and 11, representing the months january through december. dayvalue optional. an integer from 1 to 31, representing the day of the month. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the dayvalue parameter, the value re
turned from the getutcdate() method is used. if a parameter you specify is outside of the expected range, setutcmonth() attempts to update the date information in the date object accordingly. for example, if you use 15 for monthvalue,...
Date.prototype.setUTCSeconds() - JavaScript
ed 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 dateobj.setutcseconds(secondsvalue[, msvalue]) parameters secondsvalue an integer between 0 and 59, representing the seconds. msvalue optional. a number between 0 and 999, representing the milliseconds. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the msvalue parameter, the value re
turned from the getutcmilliseconds() method is used. if a parameter you specify is outside of the expected range, setutcseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for s...
Date.prototype.setYear() - JavaScript
the setyear() method sets the year for a specified date according to local time. because setyear() does not set full years ("year 2000 problem"), it is no longer used and has been replaced by the setfullyear() method. syntax dateobj.setyear(yearvalue) parameters yearvalue an integer. re
turn value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if yearvalue is a number between 0 and 99 (inclusive), then the year for dateobj is set to 1900 + yearvalue. otherwise, the year for dateobj is set to yearvalue. examples using setyear() the first two lines set the year to 1996. the third sets the year to 2000. var thebigday = new date(); thebigday.setyear(96); thebigday.setyear(1996); thebigday.setyear(2000); specifications ...
Date.prototype.toGMTString() - JavaScript
the togmtstring() method converts a date to a string, using internet greenwich mean time (gmt) conventions. the exact format of the value re
turned by togmtstring() varies according to the platform and browser, in general it should represent a human readable date string. note: togmtstring() is deprecated and should no longer be used. it remains implemented only for backward compatibility; please use toutcstring() instead. syntax dateobj.togmtstring() re
turn value a string representing the given date following the internet greenwich mean time (gmt) convention. examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and re
turns a string value that is similar to the following form. the exact format ...
Date.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object. syntax dateobj.tosource() date.tosource() re
turn value a string representing the source code of the given date object. examples native function for the built-in date object, tosource() re
turns the following string indicating that the source code is not available: function date() { [native code] } specifications not part of any standard. ...
Date.prototype.toTimeString() - JavaScript
the totimestring() method re
turns the time portion of a date object in human readable form in american english. 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 dateobj.totimestring() re
turn value a string representing the time portion of the given date in human readable form in american english. description date instances refer to a specific point in time. calling tostring() will re
turn the date formatted in a human readable form in american english. in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). sometimes i...
Error() constructor - JavaScript
roperty on the created error object. defaults to the name of the file containing the code that called the error() constructor. linenumber optional the value for the linenumber property on the created error object. defaults to the line number containing the error() constructor invocation. examples function call or new construction when error is used like a function -- without new, it will re
turn an error object. therefore, a mere call to error will produce the same output that constructing an error object via the new keyword would. // this... const x = error('i was created using a function call!') // ...has the same functionality as this. const y = new error('i was constructed via the "new" keyword!') specifications specification ecmascript (ecma-262...
Error.prototype.fileName - JavaScript
the filename property contains the path to the file that raised this error. description this non-standard property contains the path to the file that raised this error. if called from a debugger context, the firefox developer tools for example, "debugger eval code" is re
turned. examples using filename var e = new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard. ...
Error.prototype.name - JavaScript
nitial value is "error". description by default, error instances are given the name "error". the name property, in addition to the message property, is used by the error.prototype.tostring() method to create a string representation of the error. examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would re
turn 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification. ...
Error.prototype.toSource() - JavaScript
this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance. ...
FinalizationRegistry.prototype.register() - JavaScript
egistertoken]); parameters target the target object to register. heldvalue the value to pass to the finalizer for this object. this cannot be the target object. unregistertoken optional a token that may be used with the unregister method later to unregister the target object. if provided (and not undefined), this must be an object. if not provided, the target cannot be unregistered. re
turn value undefined. notes see the avoid where possible and notes on cleanup callbacks sections of the finalizationregistry page for important caveats. examples using register the following registers the target object referenced by target, passing in the held value "some value" and passing the target object itself as the unregistration token: registry.register(target, "some value", target); ...
FinalizationRegistry.prototype.unregister() - JavaScript
notes when a target object has been reclaimed, it is no longer registered in the registry. there is no need to all unregister in your cleanup callback. only call unregister if you haven't received a cleanup callback and no longer need to receive one. ...
Function() constructor - JavaScript
being undefined. invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples specifying arguments with the function constructor the following code creates a function object that takes two arguments. // example can be run directly in your javascript console // create a function that takes two arguments, and re
turns the sum of those arguments const adder = new function('a', 'b', 're
turn a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "re
turn a + b". specifications specification ecmascript (ecma-262)the definition of 'function constructor' in that specification. ...
Function.arguments - JavaScript
the variable arguments. in the case of recursion, i.e. if function f appears several times on the call stack, the value of f.arguments represents the arguments corresponding to the most recent invocation of the function. the value of the arguments property is normally null if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet re
turned. examples using the arguments object function f(n) { g(n - 1) } function g(n) { console.log('before: ' + g.arguments[0]) if (n > 0) { f(n) } console.log('after: ' + g.arguments[0]) } f(2) console.log('re
turned: ' + g.arguments) // output // before: 1 // before: 0 // after: 0 // after: 1 // re
turned: null specifications not part of any standard. deprecated in favor of arguments ...
Function.prototype.call() - JavaScript
gn]]) parameters thisarg optional the value to use as this when calling func. caution: in certain cases, thisarg may not be the actual value seen by the method. if the method is a function in non-strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argn optional arguments for the function. re
turn value the result of calling the function with the specified this value and arguments. description the call() allows for a function/method belonging to one object to be assigned and called for a different object. call() provides a new value of this to the function/method. with call(), you can write a method once and then inherit it in another object, without having to rewrite the method for th...
Function.name - JavaScript
he program runs into the truthy-branch and logs "'foo' is an instance of 'foo'". whereas, in the compressed version it behaves differently, and runs into the else-branch. if you rely on function.name, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function to have a particular name. examples function statement name the name property re
turns the name of a function statement. function dosomething() {} dosomething.name; // "dosomething" function constructor name functions created with the syntax new function(...) or just function(...) create function objects and their name is "anonymous". (new function).name; // "anonymous" anonymous function expression anonymous function expressions that were created using the keyword function...
Function.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object. this method is usually called internally by javascript and not explicitly in code. you can call tosource() while debugging to examine the contents of an object. syntax function.tosource(); re
turn value a string representing the source code of the object. examples native functions for the built-in function object, tosource() re
turns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() re
turns the javascript source that defines the object as a string. // for example: function hello() { console.log("hello, world!"); } hello.tosource(); // results in: "function hello() { consol...
Generator.prototype.throw() - JavaScript
the throw() method resumes the execution of a generator by throwing an error into it and re
turns an object with two properties done and value. syntax gen.throw(exception) parameters exception the exception to throw. for debugging purposes, it is useful to make it an instanceof error. re
turn value an object with two properties: done (boolean) has the value true if the iterator is past the end of the iterated sequence. in this case value optionally specifies the re
turn value of the iterator. has the value false if the iterator was able to produce the next value in the sequence. this is equivalent of not specifying the done property altogether. value any javascript value re
turned by the iterator. can be omitted when done is true. examples using throw() the followin...
InternalError - JavaScript
file that raised this error. inherited from error. internalerror.prototype.columnnumber column number in line that raised this error. inherited from error. internalerror.prototype.stack stack trace. inherited from error. examples too much recursion this recursive function runs 10 times, as per the exit condition. function loop(x) { if (x >= 10) // "x >= 10" is the exit condition re
turn; // do stuff loop(x + 1); // the recursive call } loop(0); setting this condition to an extremely high value, won't work: function loop(x) { if (x >= 1000000000000) re
turn; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion for more information, see internalerror: too much recursion. specifications not part of any standard. ...
Intl.Collator.prototype.compare() - JavaScript
object. 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 collator.compare(string1, string2) parameters string1 string2 the strings to compare against each other. description the compare getter function re
turns a number indicating how string1 and string2 compare to each other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. examples using compare for array sort use the compare getter function for sorting arrays. note that the function is bound to the collator from wh...
Intl.DateTimeFormat.prototype.format() - JavaScript
however, this might change in the future and isn't guaranteed for all the languages — output variations are by design and allowed by the specification. most notably, the ie and edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. for this reason you cannot expect to be able to c...
Intl.DisplayNames() constructor - JavaScript
ault is "long". "narrow" "short" "long" type the type to use, the default is "language". "language" "region" "script" "currency" fallback the fallback to use, the default is "code". "code" "none" examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is re
turned. console.log((new intl.displaynames()).of('us')); // expected output: 'us' specifications specification intl.displaynamesthe definition of 'the intl.displaynames constructor' in that specification. ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
the intl.displaynames.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and style formatting options computed during the construction of the current displaynames object. syntax displaynames.resolvedoptions() re
turn value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object re
turned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style the value provided for this propert...
Intl.ListFormat.prototype.resolvedOptions() - JavaScript
the intl.listformat.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and style formatting options computed during the construction of the current listformat object. syntax listformat.resolvedoptions() re
turn value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object re
turned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style the value provided for this property in the...
Intl.Locale.prototype.baseName - JavaScript
the intl.locale.prototype.basename property re
turns a substring of the locale's string representation, containing core information about the locale. description an intl.locale object represents a parsed local and options for that locale. the basename property re
turns basic, core information about the locale in the form of a substring of the complete data string. specifically, the property re
turns the substring containing the language, and the script and region if available. basename re
turns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar. examples basic example let myloc = new intl.locale("fr-latn-ca"); // sets locale to canadian french console.log(myloc.tostring()); // prints out "fr-latn-ca-u-ca-gregory" console.log(myloc.basename);...
Intl.Locale.prototype.calendar - JavaScript
while most of the world uses the gregorian calendar, there are several regional calendar eras used around the world. the following table shows all the valid unicode calendar key strings, along with a description of the calendar era they represent. ...
Intl.Locale.prototype.caseFirst - JavaScript
description a locale's collation rules are used to determine how strings are ordered in that locale. certain locales use a character's case (uppercase or lowercase) in the collation process. this additional rule can be expressed in a locale's casefirst property. there are 3 values that the casefirst property can have, outlined in the table below. casefirst values value description upper upper case to be sorted before lower case. lower lower case to be sorted before upper case. false no special case ordering. ...
Intl.Locale.prototype.collation - JavaScript
description collation is the process of ordering strings of characters. it is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. while the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. the collation property helps to make it easier for javascript programmers to access the collation type used by a particular locale. ...
Intl.Locale.prototype.hourCycle - JavaScript
description there are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. the hourcycle property makes it easier for javascript programmers to access the clock type used by a particular locale. like other additional locale data, hour cycle type is an extension subtag, which extends the data contained in a locale string. the hour cycle type can have several different values, which are listed in the table below. ...
Intl.Locale.prototype.minimize() - JavaScript
the intl.locale.prototype.minimize() method attempts to remove information about the locale that would be added by calling locale.maximize(). 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 locale.minimize() re
turn value a locale instance whose basename property re
turns the result of the remove likely subtags algorithm executed against locale.basename. description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). this is useful when there are superfluous subtags in the language i...
Intl.Locale.prototype.numberingSystem - JavaScript
description a numeral system is a system for expressing numbers. the numberingsystem property helps to represent the different numeral systems used by various countries, regions, and cultures around the world. as with most internationalization schemas, the numeral systems that can be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. ...
Intl.Locale.prototype.numeric - JavaScript
description like intl.locale.casefirst, numeric represents a modification to the collation rules utilized by the locale. numeric is a boolean value, which means that it can be either true or false. if numeric is set to false, there will be no special handling of numeric values in strings. if numeric is set to true, then the locale will take numeric characters into account when collating strings. this special numeric handling means that sequences of decimal digits will be compared as numbers. for example, the string "a-21" will be considered less than "a-123". ...
Intl.Locale.prototype.region - JavaScript
description the region is an essential part of the locale identifier, as it places the locale in a specific area of the world. knowing the locale's region is vital to identifying differences between locales. for example, english is spoken in the united kingdom and the united states of america, but there are differences in spelling and other language conventions between those two countries. ...
Intl.Locale.prototype.script - JavaScript
description a script, sometimes called writing system, is one of the core attributes of a locale. it indicates the set of symbols, or glyphs, that are used to write a particular language. for instance, the script associated with english is latin, whereas the script typically associated with korean is hangul. in many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
the intl.numberformat.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and number formatting options computed during initialization of this numberformat object. 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 numberformat.resolvedoptions() re
turn value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values wer...
Intl.PluralRules() constructor - JavaScript
inimumsignificantdigits the minimum number of significant digits to use. possible values are from 1 to 21; the default is 1. maximumsignificantdigits the maximum number of significant digits to use. possible values are from 1 to 21; the default is 21. examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is re
turned. this is useful to distinguish between singular and plural forms, e.g. "dog" and "dogs". var pr = new intl.pluralrules(); pr.select(0); // → 'other' if in us english locale pr.select(1); // → 'one' if in us english locale pr.select(2); // → 'other' if in us english locale using options the results can be customized using the options argument, which has one property called type whic...
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. ...
Intl.PluralRules - JavaScript
the intl.pluralrules object enables plural-sensitive formatting and plural-related language rules. constructor intl.pluralrules.pluralrules() creates a new intl.pluralrules object. static methods intl.pluralrules.supportedlocalesof() re
turns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. instance methods intl.pluralrules.prototype.resolvedoptions() re
turns a new object with properties reflecting the locale and collation options computed during initialization of the object. intl.pluralrules.prototype.select() re
turns a string indicating which plural rule to use for locale-aware formatting. examples using locales this example shows some of the variations in localized plural rules. in order ...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
xamples and send us a pull request. syntax relativetimeformat.format(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. description the function re
turned by the format getter formats a value and a unit into a string according to the locale and formatting options of this intl.relativetimeformat object. examples basic format usage the following example shows how to create a relative time formatter using the english language. // create a relative time formatter in your locale // with default values explicitly passed in. const rtf = new intl.rel...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.relativetimeformat.prototype.resolvedoptions() method re
turns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this relativetimeformat object. 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 relativetimeformat.resolvedoptions() re
turn value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if a...
Intl.getCanonicalLocales() - JavaScript
the intl.getcanonicallocales() method re
turns an array containing the canonical locale names. duplicates will be omitted and elements will be validated as structurally valid language tags. 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 intl.getcanonicallocales(locales) parameters locales a list of string values for which to get the canonical locale names. re
turn value an array containing the canonical locale names. examples using getcanonicallocales intl.getcanonicallocales('en-us'); // ["en-us"] intl.getcanonicallocales(['en-us', 'fr']); // ["en-us", "fr"] intl.getcanonicallocales('en_us'); // ...
Intl - JavaScript
locale identifier. intl.numberformat() constructor for objects that enable language-sensitive number formatting. intl.pluralrules() constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals. intl.relativetimeformat() constructor for objects that enable language-sensitive relative time formatting. static methods intl.getcanonicallocales() re
turns canonical locale names. locale identification and negotiation the internationalization constructors as well as several language sensitive methods of other constructors (listed under see also) use a common pattern for identifying locales and determining the one they will actually use: they all accept locales and options arguments, and negotiate the requested locale(s) against the locales they ...
Map.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the entries method. 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 mymap[symbol.iterator] re
turn value the map iterator function, which is the entries() function by default. examples using [@@iterator]() const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') const mapiter = mymap[symbol.iterator]() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] using [@@iterator]() with...
Map.prototype.clear() - JavaScript
the clear() method removes all elements from a map object. 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 mymap.clear(); re
turn value undefined. examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification. ...
Map.prototype.delete() - JavaScript
e() method removes the specified element from a map object by key. 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 mymap.delete(key); parameters key the key of the element to remove from the map object. re
turn value true if an element in the map object existed and has been removed, or false if the element does not exist. examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // re
turns true. successfully removed. mymap.has('bar'); // re
turns false. the "bar" element is no longer present. specifications specification ecmascript (ecma...
Map.prototype.entries() - JavaScript
the entries() method re
turns a new iterator object that contains the [key, value] pairs for each element in the map object in insertion order. 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 mymap.entries() re
turn value a new map iterator object. examples using entries() let mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (e...
Map.prototype.keys() - JavaScript
the keys() method re
turns a new iterator object that contains the keys for each element in the map object in insertion order. 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 mymap.keys() re
turn value a new map iterator object. examples using keys() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in th...
Map.prototype.set() - JavaScript
p object. 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 mymap.set(key, value) parameters key the key of the element to add to the map object. value the value of the element to add to the map object. re
turn value the map object. examples using set() let mymap = new map() // add new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method re
turns back the same map object, you can chain the method call like below: // add new elements to the map with chaining. mymap.set('bar'...
Map.prototype.size - JavaScript
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 value of size is an integer representing how many entries the map object has. a set accessor function for size is undefined; you can not change this property. ...
Map.prototype.values() - JavaScript
the values() method re
turns a new iterator object that contains the values for each element in the map object in insertion order. 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 mymap.values() re
turn value a new map iterator object. examples using values() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototy...
Math.E - JavaScript
pull request. property attributes of math.e writable no enumerable no configurable no description because e is a static property of math, you always use it as math.e, rather than as a property of a math object you created (math is not a constructor). examples using math.e the following function re
turns e: function getnapier() { re
turn math.e; } getnapier(); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.e' in that specification. ...
Math.LN10 - JavaScript
. property attributes of math.ln10 writable no enumerable no configurable no description because ln10 is a static property of math, you always use it as math.ln10, rather than as a property of a math object you created (math is not a constructor). examples using math.ln10 the following function re
turns the natural log of 10: function getnatlog10() { re
turn math.ln10; } getnatlog10(); // 2.302585092994046 specifications specification ecmascript (ecma-262)the definition of 'math.ln10' in that specification. ...
Math.LN2 - JavaScript
uest. property attributes of math.ln2 writable no enumerable no configurable no description because ln2 is a static property of math, you always use it as math.ln2, rather than as a property of a math object you created (math is not a constructor). examples using math.ln2 the following function re
turns the natural log of 2: function getnatlog2() { re
turn math.ln2; } getnatlog2(); // 0.6931471805599453 specifications specification ecmascript (ecma-262)the definition of 'math.ln2' in that specification. ...
Math.atan() - JavaScript
the math.atan() function re
turns the arctangent (in radians) of a number, that is math.atan(x)=arctan(x)= the unique y∊[-π2;π2]such thattan(y)=x\mathtt{\operatorname{math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x 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 math.atan(x) parameters x a number. re
turn value the arctangent (in radians) of the given number. description the math.atan() method re
turns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians. because atan() is a static method ...
Math.atan2() - JavaScript
the math.atan2() function re
turns the angle in the plane (in radians) between the positive x-axis and the ray from (0,0) to the point (x,y), for math.atan2(y,x). 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 math.atan2(y, x) parameters y the y coordinate of the point. x the x coordinate of the point re
turn value the angle in radians (in [-π,π][-\pi, \pi]) between the positive x-axis and the ray from (0,0) to the point (x,y). description the math.atan2() method re
turns a numeric value between -π and π representing the angle theta of an (x, y) point. this is the counterclockwise angle, measur...
Math.cos() - JavaScript
the math.cos() static function re
turns the cosine of the specified angle, which must be specified in radians. this value is length adjacent length hypotenuse . 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 math.cos(x) parameters x the angle in radians for which to re
turn the cosine. re
turn value the cosine of the given number. description the math.cos() method re
turns a numeric value between -1 and 1, which represents the cosine of the angle. because cos() is a static method of math, you always use it as math.cos(), rather than as a method of a math object you created (mat...
Math.sqrt() - JavaScript
the math.sqrt() function re
turns the square root of a number, that is ∀x≥0,math.sqrt(x)=x=the uniquey≥0such thaty2=x\forall x \geq 0, \mathtt{math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x 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 math.sqrt(x) parameters x a number. re
turn value the square root of the given number. if the number is negative, nan is re
turned. description if the value of x is negative, math.sqrt() re
turns nan. because sqrt() is a static method of math, you always use it as math.sqrt(), rather than as a method of a math object you...
Number.MAX_SAFE_INTEGER - JavaScript
ing its existence, such as math.max(number.max_safe_integer, 2), will yield undesired results such as nan. because max_safe_integer is a static property of number, you always use it as number.max_safe_integer, rather than as a property of a number object you created. polyfill if (!number.max_safe_integer) { number.max_safe_integer = 9007199254740991; // math.pow(2, 53) - 1; } examples re
turn value of max_safe_integer number.max_safe_integer; // 9007199254740991 numbers higher than safe integer this re
turns 2 because in floating points, the value is actually the decimal trailing "1" except for in subnormal precision cases such as zero. number.max_safe_integer * number.epsilon; // 2 specifications specification ecmascript (ecma-262)the definition of 'numbe...
Number.NaN - JavaScript
ents not-a-number. equivalent of nan. you do not have to create a number object to access this static property (use number.nan). property attributes of number.nan writable no enumerable no configurable no examples checking whether values are numeric function sanitise(x) { if (isnan(x)) { re
turn number.nan; } re
turn x; } testing against nan see testing against nan on the nan page. specifications specification ecmascript (ecma-262)the definition of 'number.nan' in that specification. ...
Number.parseFloat() - JavaScript
the number.parsefloat() method parses an argument and re
turns a floating point number. if a number cannot be parsed from the argument, it re
turns nan. 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 number.parsefloat(string) parameters string the value to parse. if this argument is not a string, then it is converted to one using the tostring abstract operation. leading whitespace in this argument is ignored. re
turn value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. polyfill if (number.parsefloat === undefined)...
Number.prototype.toExponential() - JavaScript
the toexponential() method re
turns a string representing the number object in exponential notation. 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 numobj.toexponential([fractiondigits]) parameters fractiondigits optional. an integer specifying the number of digits after the decimal point. defaults to as many digits as necessary to specify the number. re
turn value a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point. exceptions rangeerror if fractiondigits is too small or too large.
Object.prototype.__defineSetter__() - JavaScript
et that property. syntax obj.__definesetter__(prop, fun) parameters prop a string containing the name of the property to be bound to the given function. fun a function to be called when there is an attempt to set the specified property. this function takes the form function(val) { . . . } val an alias for the variable that holds the value attempted to be assigned to prop. re
turn value undefined. description the __definesetter__ method allows a setter to be defined on a pre-existing object. examples non-standard and deprecated way var o = {}; o.__definesetter__('value', function(val) { this.anothervalue = val; }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 standard-compliant ways // using the set operator var o = { set value...
Object.getOwnPropertyDescriptors() - JavaScript
might be an empty object, if there are no properties. description this method permits examination of the precise description of all own properties of an object. a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). ...
Object.getPrototypeOf() - JavaScript
the object.getprototypeof() method re
turns the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. 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 object.getprototypeof(obj) parameters obj the object whose prototype is to be re
turned. re
turn value the prototype of the given object. if there are no inherited properties, null is re
turned. examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an objec...
Object.prototype.isPrototypeOf() - JavaScript
ne https://github.com/mdn/interactive-examples and send us a pull request. isprototypeof() differs from the instanceof operator. in the expression "object instanceof afunction", the object prototype chain is checked against afunction.prototype, not against afunction itself. syntax prototypeobj.isprototypeof(object) parameters object the object whose prototype chain will be searched. re
turn value a boolean indicating whether the calling object lies in the prototype chain of the specified object. errors thrown typeerror a typeerror is thrown if prototypeobj is undefined or null. description the isprototypeof() method allows you to check whether or not an object exists within another object's prototype chain. examples using isprototypeof this example demonstrates that baz.
Object.prototype.__proto__ - JavaScript
ew fun, where fun is one of the built-in constructor functions provided by javascript (array, boolean, date, number, object, string, and so on — including new constructors added as javascript evolves), this value is always fun.prototype. for objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (that is, if the constructor didn't re
turn an other object explicitly, or the fun.prototype has been reassigned since the instance was created.) the __proto__ setter allows the [[prototype]] of an object to be mutated. the object must be extensible according to object.isextensible(): if it is not, a typeerror is thrown. the value provided must be an object or null. providing any other value will do nothing. to understand how prototypes ...
Reflect.apply() - JavaScript
the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.apply(target, thisargument, argumentslist) parameters target the target function to call. thisargument the value of this provided for the call to target. argumentslist an array-like object specifying the arguments with which target should be called. re
turn value the result of calling the given target function with the specified this value and arguments. exceptions a typeerror, if the target is not callable. description in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75...
Reflect.construct() - JavaScript
us a pull request. syntax reflect.construct(target, argumentslist[, newtarget]) parameters target the target function to call. argumentslist an array-like object specifying the arguments with which target should be called. newtarget optional the constructor whose prototype should be used. see also the new.target operator. if newtarget is not present, its value defaults to target. re
turn value a new instance of target (or newtarget, if present), initialized by target as a constructor with the given argumentslist. exceptions a typeerror, if target or newtarget are not constructors. description reflect.construct() allows you to invoke a constructor with a variable number of arguments. (this would also be possible by using the spread syntax combined with the new operator.) let...
Reflect.getPrototypeOf() - JavaScript
the static reflect.getprototypeof() method is almost the same method as object.getprototypeof(). it re
turns the prototype (i.e. the value of the internal [[prototype]] property) of the specified object. 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 reflect.getprototypeof(target) parameters target the target object of which to get the prototype. re
turn value the prototype of the given object. if there are no inherited properties, null is re
turned. exceptions a typeerror, if target is not an object. description the reflect.getprototypeof method re
turns the prototype (i.e. the value of the intern...
Reflect.isExtensible() - JavaScript
to object.isextensible(), but with some differences. 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 reflect.isextensible(target) parameters target the target object which to check if it is extensible. re
turn value a boolean indicating whether or not the target is extensible. exceptions a typeerror, if target is not an object. description the reflect.isextensible method allows you determine if an object is extensible (whether it can have new properties added to it). it is the same method as object.isextensible(). examples using reflect.isextensible() see also object.isextensible(). // new obj...
Reflect.ownKeys() - JavaScript
the static reflect.ownkeys() method re
turns an array of the target object's own property keys. 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 reflect.ownkeys(target) parameters target the target object from which to get the own keys. re
turn value an array of the target object's own property keys. exceptions a typeerror, if target is not an object. description the reflect.ownkeys method re
turns an array of the target object's own property keys. its re
turn value is equivalent to object.getownpropertynames(target).concat(object.getownpropertysymbols(target)). examples using reflect.ownkeys() r...
Reflect.preventExtensions() - JavaScript
ect.preventextensions(), but with some differences. 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 reflect.preventextensions(target) parameters target the target object on which to prevent extensions. re
turn value a boolean indicating whether or not the target was successfully set to prevent extensions. exceptions a typeerror, if target is not an object. description the reflect.preventextensions() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object). it is similar to object.preventextensions(). examples using reflect.pr...
Reflect.set() - JavaScript
oject, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.set(target, propertykey, value[, receiver]) parameters target the target object on which to set the property. propertykey the name of the property to set. value the value to set. receiver optional the value of this provided for the call to target if a setter is encountered. re
turn value a boolean indicating whether or not setting the property was successful. exceptions a typeerror, if target is not an object. description the reflect.set method allows you to set a property on an object. it does property assignment and is like the property accessor syntax as a function. examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj...
RegExp.prototype.dotAll - JavaScript
ble no configurable yes description the value of dotall is a boolean and true if the "s" flag was used; otherwise, false. the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage re
turn (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp). to allow it to match astral characters, the "u" (unicode) flag should be used. using both flags in conjunction allows the dot to match any unicode character, without exceptions. you cannot change this property directly. examples ...
RegExpInstance.lastIndex - JavaScript
f the regular expression does not match the empty string, then the regular expression mismatches input, and lastindex is reset to 0. otherwise, lastindex is set to the next position following the most recent match. examples using lastindex consider the following sequence of statements: var re = /(hi)?/g; matches the empty string. console.log(re.exec('hi')); console.log(re.lastindex); re
turns ["hi", "hi"] with lastindex equal to 2. console.log(re.exec('hi')); console.log(re.lastindex); re
turns ["", undefined], an empty array whose zeroth element is the match string. in this case, the empty string because lastindex was 2 (and still is 2) and hi has length 2. specifications specification ecmascript (ecma-262)the definition of 'regexp.lastindex' in that specif...
RegExp.$1-$9 - JavaScript
c, they are not a property of an individual regular expression object. instead, you always use them as regexp.$1, ..., regexp.$9. the values of these properties are read-only and modified whenever successful matches are made. the number of possible parenthesized substrings is unlimited, but the regexp object can only hold the first nine. you can access all parenthesized substrings through the re
turned array's indexes. these properties can be used in the replacement text for the string.replace method. when used this way, do not prepend them with regexp. the example below illustrates this. when parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer). examples using $n with string.replace the following script uses the repl...
Set.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the values property. 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 myset[symbol.iterator] re
turn value the set iterator function, which is the values() function by default. examples using [@@iterator]() const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); const setiter = myset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset = new set(); myset...
Set() constructor - JavaScript
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 new set([iterable]) parameters iterable optional if an iterable object is passed, all of its elements will be added to the new set. if you don't specify this parameter, or its value is null, the new set is empty. re
turn value a new set object. examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) specifications specification ecmascript (ecma-262)the definition of 'set constructor' in that ...
Set.prototype.add() - JavaScript
nds a new element with a specified value to the end of a set object. 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 myset.add(value); parameters value the value of the element to add to the set object. re
turn value the set object. examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification. ...
Set.prototype.clear() - JavaScript
the clear() method removes all elements from a set object. 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 myset.clear(); re
turn value undefined. examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification. ...
Set.prototype.delete() - JavaScript
the delete() method removes the specified element from a set object. 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 myset.delete(value); parameters value the value to remove from myset. re
turn value re
turns true if value was successfully removed from myset; otherwise false. examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // re
turns false. no "bar" element found to be deleted. myset.delete('foo'); // re
turns true. successfully removed. myset.has('foo'); // re
turns false. the "foo" element is no longer present. let's checkout below how to d...
Set.prototype.entries() - JavaScript
the entries() method re
turns a new iterator object that contains an array of [value, value] for each element in the set object, in insertion order. for set objects there is no key like in map objects. however, to keep the api similar to the map object, each entry has the same value for its key and value here, so that an array [value, value] is re
turned. 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 myset.entries() re
turn value a new iterator object that contains an array of [value, value] for each element in the given set, in insertion order. examples using entries() var myset = new set(); myset.add('...
Set.prototype.size - JavaScript
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 value of size is an integer representing how many entries the set object has. a set accessor function for size is undefined; you cannot change this property. ...
Set.prototype.values() - JavaScript
the values() method re
turns a new iterator object that contains the values for each element in the set object in insertion order. the keys() method is an alias for this method (for similarity with map objects); it behaves exactly the same and re
turns values of set elements. 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 myset.values(); re
turn value a new iterator object containing the values for each element in the given set, in insertion order. examples using values() var myset = new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next...
Planned changes to shared memory - JavaScript
mory can still be used to get an instance. unless the two headers mentioned above are set, the various postmessage() apis will throw for sharedarraybuffer objects. if they are set, postmessage() on window objects and dedicated workers will function and allow for memory sharing. to avoid having to check whether postmessage() throws, self.crossoriginisolated is being standardized (a getter that re
turns a boolean; true if the headers are set), available in window and worker contexts. webassembly shared memory the webassembly threads proposal allows webassembly.memory objects to be created with a new shared constructor flag. when this flag is set to true, the constructed memory object can be shared between workers via postmessage(), just like sharedarraybuffer, and the backing buffer of the m...
SharedArrayBuffer() constructor - JavaScript
nary data buffer, similar to the arraybuffer object. 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 new sharedarraybuffer([length]) parameters length the size, in bytes, of the array buffer to create. re
turn value a new sharedarraybuffer object of the specified size. its contents are initialized to 0. examples always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator. calling a sharedarraybuffer constructor as a function without new will throw a typeerror. var sab = sharedarraybuffer(1024); // typeerror: calling a ...
SharedArrayBuffer - JavaScript
// without new is forbidden var sab = new sharedarraybuffer(1024); constructor sharedarraybuffer() creates a new sharedarraybuffer object. instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array. this is established when the array is constructed and cannot be changed. read only. instance methods sharedarraybuffer.prototype.slice(begin, end) re
turns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive. if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. examples creating a new sharedarraybuffer var sab = new sharedarraybuffer(1024); slicing the sharedarraybuffer sab.slice(); // sharedarraybuf...
String.prototype[@@iterator]() - JavaScript
the [@@iterator]() method re
turns a new iterator object that iterates over the code points of a string value, re
turning each code point as a string value. 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 str[symbol.iterator] re
turn value a new iterator object. examples using [@@iterator]() var str = 'a\ud835\udc68'; var striter = str[symbol.iterator](); console.log(striter.next().value); // "a" console.log(striter.next().value); // "\ud835\udc68" using [@@iterator]() with for..of var str = 'a\ud835\udc68b\ud835\udc69c\ud835\udc6a'; for (var v of str) { console.log(v); } // "a" // "\ud835\udc68" /...
String.prototype.anchor() - JavaScript
with an <a name="..."> start tag, then some text, and then an </a> end tag. don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. syntax str.anchor(name) parameters name a string representing a name value to put into the generated <a name="..."> start tag. re
turn value a string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag description don't use this method. use dom apis instead. also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. examples using anchor() var mystring = 'table of contents'; document.body.innerhtml = mystring...
String.prototype.trimEnd() - JavaScript
the trimend() method removes whitespace from the end of a string. trimright() is an alias of this method. 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 str.trimend(); str.trimright(); re
turn value a new string representing the calling string stripped of whitespace from its (right) end. description the trimend() / trimright() methods re
turn the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility rea...
Symbol.prototype[@@toPrimitive] - JavaScript
the hint argument is not used. javascript calls the [@@toprimitive]() method to convert an object to a primitive value. you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. ...
Symbol() constructor - JavaScript
it may be used as the value of an extends clause of a class definition but a super call to it will cause an exception. 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 symbol([description]) parameters description optional a string. a description of the symbol which can be used for debugging but not to access the symbol itself. ...
Symbol.prototype.description - JavaScript
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 symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself. the symbol.prototype.description property can be used to read that description. it is different to symbol.prototype.tostring() as it does not contain the enclosing "symbol()" string. see the examples. ...
Symbol.keyFor() - JavaScript
shared symbol key from the global symbol registry for the given symbol. 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 symbol.keyfor(sym); parameters sym symbol, required. the symbol to find a key for. re
turn value a string representing the key for the given symbol if one is found on the global registry; otherwise, undefined. examples using keyfor var globalsym = symbol.for('foo'); // create a new global symbol symbol.keyfor(globalsym); // "foo" var localsym = symbol(); symbol.keyfor(localsym); // undefined // well-known symbols are not symbols registered // in the global symbol registry symbol.
Symbol.matchAll - JavaScript
the symbol.matchall well-known symbol re
turns an iterator, that yields matches of the regular expression against a string. this function is called by the string.prototype.matchall() method. 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 this symbol is used for string.prototype.matchall() and specifically in regexp.prototype[@@matchall](). the following two examples re
turn same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses. property attributes of symbol.matchall writable ...
Symbol.replace - JavaScript
se clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of symbol.replace writable no enumerable no configurable no examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { re
turn string.replace(this.value, '#!@?'); } } console.log('football'.replace(new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification. ...
Symbol.split - JavaScript
amples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of symbol.split writable no enumerable no configurable no examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); re
turn array.reverse(); } } console.log('another one bites the dust'.split(new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification. ...
Symbol.toPrimitive - JavaScript
symbol.toprimitive property can modify the primitive value converted from an object. // an object without symbol.toprimitive property. var obj1 = {}; console.log(+obj1); // nan console.log(`${obj1}`); // "[object object]" console.log(obj1 + ''); // "[object object]" // an object with symbol.toprimitive property. var obj2 = { [symbol.toprimitive](hint) { if (hint == 'number') { re
turn 10; } if (hint == 'string') { re
turn 'hello'; } re
turn true; } }; console.log(+obj2); // 10 -- hint is "number" console.log(`${obj2}`); // "hello" -- hint is "string" console.log(obj2 + ''); // "true" -- hint is "default" specifications specification ecmascript (ecma-262)the definition of 'symbol.toprimitive' in that specification. ...
Symbol.prototype.toSource() - JavaScript
the tosource() method re
turns a string representing the source code of the object. this method is usually called internally by javascript. syntax symbol.tosource() var sym = symbol() sym.tosource() re
turn value a string representing the source code of the object. examples native function for the built-in symbol object, tosource re
turns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource re
turns a string representing the source code. "symbol()" specifications not part of any standard. ...
Symbol.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified symbol object. 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 symbol().tostring() re
turn value a string representing the specified symbol object. description the symbol object overrides the tostring method of the object object; it does not inherit object.prototype.tostring(). for symbol objects, the tostring method re
turns a string representation of the object. no string concatenation while you can call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // typeerror: can't convert symbol ...
Symbol.prototype.valueOf() - JavaScript
javascript calls the valueof method to convert an object to a primitive value. you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. ...
TypedArray.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() re
turn value the array iterator function, which is the values() function by default. examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecma...
TypedArray.prototype.byteLength - JavaScript
m/mdn/interactive-examples and send us a pull request. description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be re
turned. typedarray is one of the typedarray objects. examples using the bytelength property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.bytelength; // 6 ...
TypedArray.prototype.copyWithin() - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.copywithin(target, start[, end = this.length]) parameters target target start index position where to copy the elements to. start source start index position where to start copying elements from. end optional optional. source end index position where to end copying elements from. re
turn value the modified array. description see array.prototype.copywithin for more details. examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ...
TypedArray.prototype.entries() - JavaScript
the entries() method re
turns a new array iterator object that contains the key/value pairs for each index in the array. 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 arr.entries() re
turn value a new array iterator object. examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] co...
TypedArray.prototype.fill() - JavaScript
ository. 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 typedarray.fill(value[, start = 0[, end = this.length]]) parameters value value to fill the typed array with. start optional. start index. defaults to 0. end optional. end index (not included). defaults to this.length. re
turn value the modified array. description the elements interval to fill is [start, end). the fill method takes up to three arguments value, start and end. the start and end arguments are optional with default values of 0 and the length of the this object. if start is negative, it is treated as length+start where length is the length of the array. if end is negative, it is treated as length+end. ...
TypedArray.prototype.includes() - JavaScript
the includes() method determines whether a typed array includes a certain element, re
turning true or false as appropriate. this method has the same algorithm as array.prototype.includes(). typedarray is one of the typed array types here. 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 typedarray.includes(searchelement[, fromindex]); parameters searchelement the element to search for. fromindex optional. the position in this array at which to begin searching for searchelement; defaults to 0. re
turn value a boolean. examples using includes var uint8 = new uint8array([1,2,3]); uint8.includes(2); ...
TypedArray.prototype.join() - JavaScript
ou'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.join([separator = ',']); parameters separator optional. specifies a string to separate each element. the separator is converted to a string if necessary. if omitted, the typed array elements are separated with a comma (","). re
turn value a string with all array elements joined. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!uint8array.prototype.join) { object.defineproperty(uint8array.prototype, 'join', { value: array.prototype.join }); } if you need to support truly ob...
TypedArray.prototype.keys() - JavaScript
the keys() method re
turns a new array iterator object that contains the keys for each index in the array. 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 arr.keys() re
turn value a new array iterator object. examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value);...
TypedArray.prototype.length - JavaScript
b.com/mdn/interactive-examples and send us a pull request. description the length property is an accessor property whose set accessor function is undefined, meaning that you can only read this property. the value is established when a typedarray is constructed and cannot be changed. if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be re
turned. typedarray is one of the typedarray objects. examples using the length property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.length; // 6 (due to the offset o...
TypedArray.of() - JavaScript
ject, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.of(element0[, element1[, ...[, elementn]]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array. re
turn value a new typedarray instance. description some subtle distinctions between array.of() and typedarray.of(): if the this value passed to typedarray.of is not a constructor, typedarray.of will throw a typeerror, where array.of defaults to creating a new array. typedarray.of uses [[put]] where array.of uses [[defineproperty]]. hence, when working with proxy objects, it calls handler.set to ...
TypedArray.prototype.reverse() - JavaScript
last becomes the first. this method has the same algorithm as array.prototype.reverse(). typedarray is one of the typed array types here. 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 typedarray.reverse(); re
turn value the reversed array. examples using reverse var uint8 = new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification. ...
TypedArray.prototype.sort() - JavaScript
the sort() method sorts the elements of a typed array numerically in place and re
turns the typed array. this method has the same algorithm as array.prototype.sort(), except that sorts the values numerically instead of as strings. typedarray is one of the typed array types here. 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 typedarray.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. re
turn value the sorted typed array. examples using sort for more examples, see also the array.prototype.sort() method. let numbers = new uint8array([40, 1...
TypedArray.prototype.toString() - JavaScript
the tostring() method re
turns a string representing the specified array and its elements. this method has the same algorithm as array.prototype.tostring(). typedarray is one of the typed array types here. 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 typedarray.tostring() re
turn value a string representing the elements of the typed array. examples the typedarray objects override the tostring method of object. for typedarray objects, the tostring method joins the array and re
turns one string containing each typed array element separated by commas. for example, the following code creates a typed array an...
TypedArray.prototype.values() - JavaScript
the values() method re
turns a new array iterator object that contains the values for each index in the array. 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 arr.values() re
turn value a new array iterator object. examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.nex...
WeakMap.prototype.delete() - JavaScript
ete() method removes the specified element from a weakmap object. 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 wm.delete(key); parameters key the key of the element to remove from the weakmap object. re
turn value true if an element in the weakmap object has been removed successfully. false if the key is not found in the weakmap or if the key is not an object. examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // re
turns true. successfully removed. wm.has(window); // re
turns false. the window object is no longer in the weakmap. specifications...
WeakMap.prototype.get() - JavaScript
the get() method re
turns a specified element from a weakmap object. 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 wm.get(key); parameters key required. the key of the element to re
turn from the weakmap object. re
turn value the element associated with the specified key in the weakmap object. if the key can't be found, undefined is re
turned. examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // re
turns "foo". wm.get('baz'); // re
turns undefined. specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.ge...
WeakMap.prototype.set() - JavaScript
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 wm.set(key, value); parameters key required. must be object. the key of the element to add to the weakmap object. value required. any value. the value of the element to add to the weakmap object. re
turn value the weakmap object. examples using the set method var wm = new weakmap(); var obj = {}; // add new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification. ...
WeakRef.prototype.deref() - JavaScript
notes see the notes on weakrefs section of the weakref page for some important notes. examples using deref see the examples section of the weakref page for the complete example. ...
WebAssembly.Table.prototype.length - JavaScript
the number of elements in the table. syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification. ...
WebAssembly.compile() - JavaScript
into a webassembly.module object. this function is useful if it is necessary to a compile a module before it can be instantiated (otherwise, the webassembly.instantiate() function should be used). syntax promise<webassembly.module> webassembly.compile(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. re
turn value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker u...
WebAssembly.compileStreaming() - JavaScript
seful if it is necessary to a compile a module before it can be instantiated (otherwise, the webassembly.instantiatestreaming() function should be used). syntax promise<webassembly.module> webassembly.compilestreaming(source); parameters source a response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. re
turn value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm mo...
decodeURI() - JavaScript
i) previously created by encodeuri() or by a similar routine. 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 decodeuri(encodeduri) parameters encodeduri a complete, encoded uniform resource identifier. re
turn value a new string representing the unencoded version of the given encoded uniform resource identifier (uri). exceptions throws an urierror ("malformed uri sequence") exception when encodeduri contains invalid character sequences. description replaces each escape sequence in the encoded uri with the character that it represents, but does not decode escape sequences that could not have been i...
escape() - JavaScript
part of a url following ?)—not for escaping ordinary string literals, which use the format "\xhh". (hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. re
turn value a new string in which certain characters have been escaped. description the escape function is a property of the global object. special characters are encoded with the exception of: @*_+-./ the hexadecimal form for characters, whose code unit value is 0xff or less, is a two-digit escape sequence: %xx. for characters with a greater code unit, the four-digit format %uxxxx is used. exampl...
undefined - JavaScript
s, it is a variable in global scope. the initial value of undefined is the primitive value undefined. in modern browsers (javascript 1.8.5 / firefox 4+), undefined is a non-configurable, non-writable property, per the ecmascript 5 specification. (even when this is not the case, avoid overriding it.) a variable that has not been assigned a value is of type undefined. a method or statement also re
turns undefined if the variable that is being evaluated does not have an assigned value. a function re
turns undefined if a value was not re
turned. be careful. while it is possible to use it as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug. // don...
unescape() - JavaScript
e() function computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. the escape sequences might be introduced by a function like escape. usually, decodeuri or decodeuricomponent are preferred over unescape. note: do not use unescape to decode uris, use decodeuri instead. syntax unescape(str) parameters str a string to be decoded. re
turn value a new string in which certain characters have been unescaped. description the unescape function is a property of the global object. examples using unescape unescape('abc123'); // "abc123" unescape('%e4%f6%fc'); // "äöü" unescape('%u0107'); // "ć" specifications specification ecmascript (ecma-262)the definition of 'unescape' in that specification. ...
uneval() - JavaScript
the uneval() function creates a string representation of the source code of an object. syntax uneval(object) parameters object a javascript expression or statement. re
turn value a string representing the source code of object. note: this will not re
turn a json representation of object. description uneval() is a top-level function and is not associated with any object. examples using uneval var a = 1; uneval(a); // re
turns a string containing 1 var b = '1'; uneval(b); // re
turns a string containing "1" uneval(function foo() {}); // re
turns "(function foo(){})" var a = uneval(function foo() { re
turn 'hi'; }); var foo = eval(a); foo(); // re
turns "hi" specifications not part of any standard. ...
Standard built-in objects - JavaScript
es, if any. other objects in the global scope are either created by the user script or provided by the host application. the host objects available in browser contexts are documented in the api reference. for more information about the distinction between the dom and core javascript, see javascript technologies overview. standard objects by category value properties these global properties re
turn a simple value. they have no properties or methods. infinity nan undefined globalthis function properties these global functions—functions which are called globally, rather than on an object—directly re
turn their results to the caller. eval() uneval() isfinite() isnan() parsefloat() parseint() encodeuri() encodeuricomponent() decodeuri() decodeuricomponent() deprecat...
Bitwise AND (&) - JavaScript
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 a & b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. ...
Bitwise OR (|) - JavaScript
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 a | b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. ...
Bitwise XOR (^) - JavaScript
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 a ^ b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. ...
Decrement (--) - JavaScript
the decrement operator (--) decrements (subtracts one from) its operand and re
turns a value. 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 operator: x-- or --x description if used postfix, with operator after operand (for example, x--), the decrement operator decrements and re
turns the value before decrementing. if used prefix, with operator before operand (for example, --x), the decrement operator decrements and re
turns the value after decrementing. examples postfix decrement let x = 3; y = x--; // y = 3 // x = 2 prefix decrement let a = 2; b = --a; // a = 1 // b = 1 specifications ...
Exponentiation (**) - JavaScript
it is equivalent to math.pow, except it also accepts bigints as operands. 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 operator: var1 ** var2 description the exponentiation operator is right-associative: a ** b ** c is equal to a ** (b ** c). ...
Greater than (>) - JavaScript
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 x > y description the operands are compared using the abstract relational comparison algorithm. see the documentation for the less than operator for a summary of this algorithm. ...
Greater than or equal (>=) - JavaScript
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 x >= y description the operands are compared using the abstract relational comparison algorithm. see the documentation for the less than operator for a summary of this algorithm. ...
Increment (++) - JavaScript
the increment operator (++) increments (adds one to) its operand and re
turns a value. 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 operator: x++ or ++x description if used postfix, with operator after operand (for example, x++), the increment operator increments and re
turns the value before incrementing. if used prefix, with operator before operand (for example, ++x), the increment operator increments and re
turns the value after incrementing. examples postfix increment let x = 3; y = x++; // y = 3 // x = 4 prefix increment let a = 2; b = ++a; // a = 3 // b = 3 specifications specif...
Inequality (!=) - JavaScript
unlike the strict inequality operator, it attempts to convert and compare operands that are of different types. 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 x != y description the inequality operator checks whether its operands are not equal. ...
Less than or equal (<=) - JavaScript
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 x <= y description the operands are compared using the abstract relational comparison algorithm. see the documentation for the less than operator for a summary of this algorithm. ...
Logical nullish assignment (??=) - JavaScript
effect (e.g., if expr is a function call, the calling never takes place). logical nullish assignment short-circuits as well meaning that x ??= y is equivalent to: x ?? (x = y); and not equivalent to the following which would always perform an assignment: x = x ?? y; examples using logical nullish assignment function config(options) { options.duration ??= 100; options.speed ??= 25; re
turn options; } config({ duration: 125 }); // { duration: 125, speed: 25 } config({}); // { duration: 100, speed: 25 } specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification. ...
Remainder (%) - JavaScript
it always takes the sign of the dividend. 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. ...
Strict inequality (!==) - JavaScript
unlike the inequality operator, the strict inequality operator always considers operands of different types to be different. 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 x !== y description the strict inequality operator checks whether its operands are not equal. ...
Unary plus (+) - JavaScript
ecimal (0x-prefixed) formats are supported. negative numbers are supported (though not for hex). using the operator on bigint values throws a typeerror. if it cannot parse a particular value, it will evaluate to nan. examples usage with numbers const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 usage with non-numbers +true // 1 +false // 0 +null // 0 +function(val){ re
turn val } // nan +1n // throws typeerror: cannot convert bigint value to number specifications specification ecmascript (ecma-262)the definition of 'unary plus operator' in that specification. ...
new.target - JavaScript
in normal function calls, new.target is undefined. 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. ...
continue - JavaScript
1, 3, 7, and 12. var i = 0; var n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; } using continue with a label in the following example, a statement labeled checkiandj contains a statement labeled checkj. if continue is encountered, the program continues at the top of the checkj statement. each time continue is encountered, checkj reiterates until its condition re
turns false. when false is re
turned, the remainder of the checkiandj statement is completed. if continue had a label of checkiandj, the program would continue at the top of the checkiandj statement. see also label. var i = 0; var j = 8; checkiandj: while (i < 4) { console.log('i: ' + i); i += 1; checkj: while (j > 4) { console.log('j: ' + j); j -= 1; if ((j % 2) == 0) con...
for...in - JavaScript
sited before or after it is modified, or whether a deleted property will be visited before it is deleted. array iteration and for...in note: for...in should not be used to iterate over an array where the index order is important. array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. there is no guarantee that for...in will re
turn the indexes in any particular order. the for...in loop statement will re
turn all enumerable properties, including those with non–integer names and those that are inherited. because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. therefore, it is better to use a for loop with a numeric index (or array.prototype.foreach() ...
import.meta - JavaScript
pt implementation, with a null prototype. the object is extensible, and its properties are writable, configurable, and enumerable. examples using import.meta given a module my-module.js <script type="module" src="my-module.js"></script> you can access meta information about the module using the import.meta object. console.log(import.meta); // { url: "file:///home/user/my-module.js" } it re
turns an object with a url property indicating the base url of the module. this will either be the url from which the script was obtained, for external scripts, or the document base url of the containing document, for inline scripts. note that this will include query parameters and/or hash (i.e., following the ? or #). for example, with the following html: <script type="module"> import './index.mjs...
let - JavaScript
emulating private members in dealing with constructors it is possible to use the let bindings to share one or more private members without using closures: var thing; { let privatescope = new weakmap(); let counter = 0; thing = function() { this.someproperty = 'foo'; privatescope.set(this, { hidden: ++counter, }); }; thing.prototype.showpublic = function() { re
turn this.someproperty; }; thing.prototype.showprivate = function() { re
turn privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but thos...
Statements and declarations - JavaScript
onally 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. re
turn specifies the value to be re
turned 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. for creates a loop that consists of three optional expressions, enclosed in ...
JavaScript reference - JavaScript
primary expressionsthis function class function* yield yield* async function await [] {} /ab+c/i ( ) null left-hand-side expressions pro...
JavaScript
r programming. the complete modules available there are as follows: javascript first steps answers some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", along with discussing key javascript features such as variables, strings, numbers, and arrays. javascript building blocks continues our coverage of javascript's 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 discu...
Web app manifests
browsers generally support manifests with other appropriate extensions like .json (content-type: application/json). note: if the manifest requires credentials to fetch - the crossorigin attribute must be set to use-credentials, even if the manifest file is in the same origin as the current page. splash screens in chrome 47 and later, a splash screen...
Authoring MathML - MathML
note that ua string sniffing is not the most reliable method and might break from version to version: var ua = navigator.useragent; var isgecko = ua.indexof("gecko") > -1 && ua.indexof("khtml...
MathML
to force mathjax to use native mathml, try this mozilla add-on, this safari extension or this greasemonkey script. related topics css html svg ...
Media container formats (file types) - Web media technologies
6.10 no lpcm (linear pulse code modulation) yes mpeg-1 audio layer iii (mp3) no µ-law (u-law) no webm webm (web media) is a format based on matroska which is designed specifically for use in modern web environments. it's based entirely on free and open technologies and primarily uses codecs that are in
turn free and open, although some products support other codecs in webm containers as well. webm was first introduced in 2010 and is now widely supported. compliant implementations of webm are required to support the vp8 and vp8 video codecs and the theora and opus audio codecs. the webm container format and its required codecs are all available under open licenses. any other codecs may require a lic...
Optimizing startup performance - Web Performance
startup process to be as asynchronous as possible (whether it's a new app or a port): use the defer or async attribute on script tags needed by the web application. this allows html parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. if you need to decode asset files (for example, decoding jpeg files and
turning them into raw texture data for later use by webgl), that's great to do in workers. when dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase. the provided one is almost certainly significantly faster, and will reduce your app size to boot. in additio...
Performance budgets - Web Performance
inform file specific budgets (e.g. font size), and their optimizations. (e.g. using font-display to improve perceived performance). the ultimate value of a performance budget is to correlate the impact of performance on business or product goals. when defining metrics, you should focus on user experience, which will dictate not only the bounce or conversion rate but how likely is that user to re
turn. how do i implement a performance budget? during development, there are a few tools to run checks against new or modified assets: a module bundler (e.g. webpack), has performance features that will notify you when assets exceed specified limits. bundlesize, allows you to define and run file size checks in your ci pipeline. file size checks are the first line of defense against regressions...
Introduction to progressive web apps - Progressive web apps (PWAs)
ther major browsers support all these features. above all you should follow the progressive enhancement rule: use technologies that enhance the appearance and utility of your app when they're available, but still offer the basic functionality of your app when those features are unavailable. presenting a trusted website with a good performance is a consequence of using these enhancements; this in
turn means building web apps which follow better practices. this way everybody will be able to use the app, but those with modern browsers will benefit from pwa features even more. an example application in this series of articles we will examine the source code of a super simple website that lists information about games submitted to the a-frame category in the js13kgames 2017 competition. you don'...
Media - Progressive web apps (PWAs)
his is the second section... page: 2 challenges move the print-specific style rules to a separate css file. read the @import reference page to find details of how to import the new print-specific css file into your style4.css stylesheet. make the headings
turn blue when the mouse pointer is over them. see solutions to these challenges. what next? so far, all the style rules in this tutorial have been specified in files. the rules and their values are fixed. the next page describes how you can change rules dynamically by using a programming language: javascript. ...
class - SVG: Scalable Vector Graphics
pe.) a list consists of a separated sequence of values. unless explicitly described differently, lists within svg's xml attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage re
turn" (u+000d), and "form-feed" (u+000c). the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg dom, values of a <list-of-ts> type are represented by an interface specific for the particular type t. for example, a <list-of-lengths> is represented in the svg dom using an svglengthlist or svganimatedlength...
d - SVG: Scalable Vector Graphics
y are the two radii of the ellipse; angle represents a rotation (in degrees) of the ellipse relative to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters. large-arc-flag allows to chose one of the large arc (1) or small arc (0), sweep-flag allows to chose one of the clockwise
turning arc (1) or anticlockwise
turning arc (0) the coordinate x,y becomes the new current point for the next command. all subsequent sets of parameters are considered implicit absolute arc curve (a) commands. a (rx ry angle large-arc-flag sweep-flag dx dy)+ draw an arc curve from the current point to a point for which coordinates are those of the current poi...
rotate - SVG: Scalable Vector Graphics
ecifies how the animated element rotates as it travels along a path specified in an <animatemotion> element. usage notes value auto | auto-reverse | <number> default value 0 animatable no the auto and auto-reverse values allow the animated element's rotation to change dynamically as it travels along the path. if the value of rotate is auto, the element
turns to align its right-hand side in the current direction of motion. if the value is auto-reverse, it
turns its left-hand side in the current direction of motion. setting rotate's value to a number specifies a constant rotation, in degrees, that does not change with the animation. the default value of 0 keeps the animated element in its original orientation. examples svg <svg width="400" height=...
shape-rendering - SVG: Scalable Vector Graphics
auto this value indicates that the user agent shall make appropriate tradeoffs to balance speed, crisp edges and geometric precision, but with geometric precision given more importance than speed and crisp edges. optimizespeed this value indicates that the user agent shall emphasize rendering speed over geometric precision and crisp edges. this option will sometimes cause the user agent to
turn off shape anti-aliasing. crispedges this value indicates that the user agent shall attempt to emphasize the contrast between clean edges of artwork over rendering speed and geometric precision. to achieve crisp edges, the user agent might
turn off anti-aliasing for all lines and curves or possibly just for straight lines which are close to vertical or horizontal. also, the user agent might adju...
text-decoration - SVG: Scalable Vector Graphics
le level 3the definition of 'text-decoration' in that specification. candidate recommendation defines the property as a shorthand for text-decoration-line, text-decoration-style, and text-decoration-color. scalable vector graphics (svg) 2the definition of 'text-decoration' in that specification. candidate recommendation mainly refers to the definition in css text decoration 3
turning the property into a shorthand for text-decoration-line and text-decoration-style. scalable vector graphics (svg) 1.1 (second edition)the definition of 'text-decoration' in that specification. recommendation initial definition ...
text-rendering - SVG: Scalable Vector Graphics
auto this value indicates that the user agent shall make appropriate tradeoffs to balance speed, legibility and geometric precision, but with legibility given more importance than speed and geometric precision. optimizespeed this value indicates that the user agent shall emphasize rendering speed over legibility and geometric precision. this option will sometimes cause some user agents to
turn off text anti-aliasing. optimizelegibility this value indicates that the user agent shall emphasize legibility over rendering speed and geometric precision. the user agent will often choose whether to apply anti-aliasing techniques, built-in font hinting or both to produce the most legible text. geometricprecision this value indicates that the user agent shall emphasize geometric precision ov...
Content type - SVG: Scalable Vector Graphics
pe.) a list consists of a separated sequence of values. unless explicitly described differently, lists within svg's xml attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage re
turn" (u+000d), and "form-feed" (u+000c). the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg dom, values of a <list-of-ts> type are represented by an interface specific for the particular type t. for example, a <list-of-lengths> is represented in the svg dom using an svglengthlist or svganimatedlength...
<feComponentTransfer> - SVG: Scalable Vector Graphics
filter primitive performs color-component-wise remapping of data for each pixel. it allows operations like brightness adjustment, contrast adjustment, color balance or thresholding. the calculations are performed on non-premultiplied color values. the colors are modified by changing each channel (r, g, b, and a) to the result of what the children <fefuncr>, <fefuncb>, <fefuncg>, and <fefunca> re
turn. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<fefunca>, <fefuncr>, <fefuncb>, <fefuncg> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in dom interface this element implements the svgfecomponenttransferelement interface. exam...
Scripting - SVG: Scalable Vector Graphics
you can also use document.getelementbyid("svg_elem_name").getsvgdocument(), which gives the same result. you may find documentation referring to an svgdocument interface. prior to svg 2, svg documents were represented using that interface. however, svg documents are now represente...
SVG and CSS - SVG: Scalable Vector Graphics
stroke: green; } open the document in your svg-enabled browser. move your mouse pointer over the graphic to see what happens. result notes about this demonstration: the svg document links the stylesheet in the usual way. svg has its own css properties and values. some of them are similar to css properties for html. challenge change the stylesheet so that the inner petals all
turn pink when the mouse pointer is over any one of them, without changing the way the outer petals work. see a solution to this challenge. simplified structure the svg structure shown above could be written much more concise by referencing the individual parts of the flower via <use> elements. this behavior is standardized, though only a few browsers support the :hover pseudo-class and other...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
imply delete the new profile and go about cleaning your old profile using the steps in the section below. if the new profile doesn't work, clean your os file associations, then your mimetypes.rdf. create and remove a bogus file association this solution should work for mimetypes.rdf corruption, and requires little technical knowledge. it's adapted from jp fiset's comment in bug 303581 which in
turn was adapted from jeff schiller's comment in bug 303581. 1. try and open a local .svg file using mozilla and when the "opening ..." dialog comes up, select the "open with" radio button and choose any .exe except firefox.exe/mozilla.exe. 2. make sure the "do this automatically for files like this from now on" checkbox is checked. 3. click ok, and when the program you chose tries to open the file, j...
Certificate Transparency - Web security
icate transparency initially came about in 2013 against a backdrop of ca compromises (diginotar breach in 2011), questionable decisions (trustwave subordinate root incident in 2012) and technical issuance issues (weak, 512 bit certificate issuance by digicert sdn bhd of malaysia). implementation when certificates are submitted to a ct log, a signed certificate timestamp (sct) is generated and re
turned. this serves as a proof that the certificate has been submitted and will be added to the log. the specification states that compliant servers must provide a number of these scts to tls clients when they connect. this can be accomplished via a number of different mechanisms: x.509v3 certificate extension which embeds signed certificate timestamps directly into the leaf certificate a tls ext...
Securing your site - Web security
there are a number of things you can do to help secure your site. this article offers an assortment of suggestions, as well as links to other articles providing more useful information. note: this article is a work in progress, and is neither complete nor does following its suggestions guarantee your site will be fully secure. user information security how to
turn off form autocompletion form fields support autocompletion in gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. for certain types of data, you may wish to disable this feature. privacy and the :visited selector this article discusses changes made to the getcomputedstyle() method that eliminates the ability for malicious sites to figure out the use...
Subresource Integrity - Web security
in other than the document in which it’s embedded, browsers additionally check the resource using cross-origin resource sharing (cors), to ensure the origin serving the resource allows it to be shared with the requesting origin. if the script or stylesheet doesn’t match its associated integrity value, the browser must refuse to execute the script or apply the stylesheet, and must instead re
turn a network error indicating that fetching of that script or stylesheet failed. specifications specification status comment subresource integrity recommendation fetch living standard ...
Transport Layer Security - Web security
widely implemented. alternative mechanisms are in the process of being developed, which will also support http/2. retiring old tls versions to help with working towards a more modern, more secure web, tls 1.0 and 1.1 support will be removed from all major browsers in q1 2020. you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, firefox will re
turn a secure connection failed error when connecting to servers using the older tls versions (bug 1606734). tls handshake timeout values if the tls handshake starts to become slow or unresponsive for some reason, the user's experience can be affected significantly. to mitigate this problem, modern browsers have implemented handshake timeouts: since version 58, firefox implements a tls handshake ...
Tutorials
ch as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features,
turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. getting started with javascript what is javascript and how can it help you? codecademy codecademy is an easy way to learn how to code javascript. it's interac...
Using shadow DOM - Web Components
this is the case with built in elements that contain shadow doms, such as <video>. note: as this blog post shows, it is actually fairly easy to work around closed shadow doms, and the hassle to completely hide them is often more than it's worth. if you are attaching a shadow dom to a custom element as part of its constructor (by far the most useful application of the shadow dom), you w...
ceiling - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the ceiling function evaluates a decimal number and re
turns the smallest integer greater than or equal to the decimal number. syntax ceiling(number ) arguments number the number to be evaluated. re
turns the nearest integer greater than or equal to number. for example: ceiling (5.2) = 6 ceiling (-5.2) = -5 defined xpath 1.0 4.4 gecko support supported. ...
choose - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the choose function re
turns one of the specified objects based on a boolean parameter. note: this method should be used instead of if(), which has been deprecated. syntax choose( boolean , object1, object2 ) arguments boolean the boolean operation to use when determining which object to re
turn. object1 the first object to consider re
turning. object2 the second object to consider re
turning. re
turns if the boolean parameter is true, the first object is re
turned; otherwise, the second object is re
turned. note: all parameters are evaluated, even the one that's not re
turned. defined xforms 1.1 gecko support supported. ...
concat - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the concat function concatenates two or more strings and re
turns the resulting string. syntax concat(string1 ,string2 [,stringn]* ) arguments stringn this function accepts two or more arguments. each of these arguments is a string. re
turns a single string that is the concatenation of all the strings passed to the function as arguments. defined xpath 1.0 4.2 gecko support supported. ...
contains - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the contains function determines whether the first argument string contains the second argument string and re
turns boolean true or false. syntax contains(haystack, needle) arguments haystack the string to be searched needle the string to look for as a substring of haystack re
turns true if haystack contains needle. otherwise, false. defined xpath 1.0 4.2 gecko support supported. ...
count - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the count function counts the number of nodes in a node-set and re
turns an integer. syntax count(node-set ) arguments node-set the node set to be counted. re
turns an integer representing the number of nodes in a node-set. defined xpath 1.0 4.1 gecko support supported. ...
element-available - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the element-available function determines if an element is available and re
turns true or false. syntax element-available(qname ) arguments qname must evaluate to a valid qname. the qname is expanded into an expanded-name using the namespace declarations in scope for the expression. re
turns re
turns true if and only if the expanded-name is the name of an instruction. if the expanded-name has a namespace uri equal to the xslt namespace uri, then it refers to an element defined by xslt. otherwise, it refers to an extension element. if the expanded-name has a null namespace uri, the element-available function will re
turn false. defined xslt 1.0 15 gecko support supported. ...
false - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the false function re
turns boolean false. syntax false() re
turns boolean false. notes this function is useful part of a comparison: <xsl:if test="boolean((1 > 2) = false())"> the expression evaluates as true </xsl:if> defined xpath 1.0 4.3 gecko support supported. ...
floor - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the floor function evaluates a decimal number and re
turns the largest integer less than or equal to the decimal number. syntax floor( number ) arguments number the decimal number to be evaluated. re
turns the nearest integer less than or equal to number. defined xpath 1.0 4.4 gecko support supported. ...
format-number - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the format-number function evaluates a number and re
turns a string representing the number in a given format. syntax format-number(number ,pattern [,decimal-format] ) arguments number the number to be formatted pattern a string in the format of the jdk 1.1 decimalformat class. (the documentation for jdk 1.1 is not available online. here is the java se 6 decimalformat.) decimal-format (optional) the name of an xsl:decimal-format element that defines the number format to be used. if omitted, the default decimal-format will be used. re
turns a string representing the number in the new format. notes this function is an xslt-specific addition to xpath. it is not a part of the co...
function-available - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the function-available function determines if a given function is available and re
turns boolean true or false. syntax function-available(name ) arguments name the name of the function to test. re
turns boolean true or false. defined xpath 1.0 15 gecko support supported. ...
id - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the id function finds nodes matching the given ids and re
turns a node-set containing the identified nodes. syntax id(expression ) arguments expression if expression is a node-set, then the string value of each node in the node-set is treated as an individual id. the re
turned node set is the nodes corresponding to those ids. if expression is a string, or anything other than a node-set, then expression is treated as a space-separated list of ids. the re
turned node set is the nodes corresponding to those ids. re
turns a node-set containing the node or nodes identified by the given id or ids. notes the dtd of the xml document determines what attribute is an id. see xpath 1.0 5.2.1 ...
lang - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the lang function determines whether the context node matches the given language and re
turns boolean true or false. syntax lang(string ) arguments string the language code or localization (language and country) code to be matched. re
turns true if the context node matches the given languages. otherwise, false. notes a node's language is determined by its xml:lang attribute. if the current node does not have an xml:lang attribute, then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language. if the language cannot be determined (no ancestor has an xml:lang attribute), this function will re
turn false. if...
last - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the last function re
turns a number equal to the context size from the expression evaluation context. syntax last() re
turns an integer equal to the context size from the expression evaluation context. notes this is often used with the position() function to determine if a particular node is the last in a node-set. defined xpath 1.0 4.1 gecko support supported. ...
local-name - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the local-name function re
turns a string representing the local name of the first node in a given node-set. syntax local-name( [node-set] ) arguments node-set (optional) the local name of the first node in this node-set will be re
turned. if this argument is omitted, the current context node will be used. re
turns a string. notes the local name is the local part of an expanded-name. defined xpath 1.0 4.1 gecko support supported. ...
name - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the name function re
turns a string representing the qname of the first node in a given node-set. syntax name( [node-set] ) arguments node-set (optional) the qname of the first node in this node-set will be re
turned. if this argument is omitted, the current context node will be used. re
turns a string representing the qname of a node. notes the qname is the node's qualified name, including its namespace prefix and its local name. defined xpath 1.0 4.1 gecko support supported. ...
namespace-uri - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the namespace-uri function re
turns a string representing the namespace uri of the first node in a given node-set. syntax namespace-uri( [node-set] ) arguments node-set (optional) the namespace uri of the first node in this node-set will be re
turned. if this argument is omitted, the current context node will be used. re
turns a string representing uri of the namespace in which the given node resides. notes if the given node does not have a specified namespace, the re
turned string will be an empty string. for nodes other than element and attribute nodes, the re
turned string will always be an empty string. defined xpath 1.0 4.1 gecko support supported. ...
normalize-space - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the normalize-space function strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and re
turns the resulting string. syntax normalize-space( [string] ) arguments string (optional) the string to be normalized. if omitted, string used will be the same as the context node converted to a string. re
turns the normalized string. defined xpath 1.0 4.2 gecko support supported. ...
position - XPath
notes note that a node's position in a context is not zero-based. the first node has a position of 1. the context is determined by the rest of the path. <xsl:template match="//a[position() = 5]"> <!-- this template matches the fifth a element anywhere in the document. ...
round - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the round function re
turns a number that is the nearest integer to the given number. syntax round(decimal ) arguments decimal the decimal number to be rounded. re
turns the nearest integer less then, greater than, or equal todecimal. notes -0.5 rounds to negative zero. 0.4 rounds to postive zero. defined xpath 1.0 4.4 gecko support supported. ...
starts-with - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the starts-with checks whether the first string starts with the second string and re
turns true or false. syntax starts-with(haystack, needle) arguments haystack the string to look in. needle the string to look for. re
turns true if haystack starts with needle. otherwise, false. defined xpath 1.0 4.2 gecko support supported. ...
string-length - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the string-length function re
turns a number equal to the number of characters in a given string. syntax string-length( [string] ) arguments string(optional) the string to evaluate. if omitted, string used will be the same as the context node converted to a string. re
turns an integer equal to the number of characters in the string. defined xpath 1.0 4.2 gecko support supported. ...
substring-after - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring-after function re
turns a string that is the rest of a given string after a given substring. syntax substring-after(haystack ,needle ) arguments haystack the string to be evaluated. part of this string will be re
turned. needle the substring to search for. everything after the first occurrence ofneedle inhaystack will be re
turned. re
turns a string. examples xpath example output substring-after('aa-bb','-') bb substring-after('aa-bb','a') a-bb substring-after('aa-bb','b') b substring-after('aa-bb','q') (empty string) defined xpath 1.0 4.2 gecko support supported. ...
substring-before - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring-before function re
turns a string that is the part of a given string before a given substring. syntax substring-before(haystack ,needle ) arguments haystack the string to be evaluated. part of this string will be re
turned. needle the substring to search for. everything before the first occurrence ofneedle inhaystack will be re
turned. re
turns a string. examples xpath example output substring-before('aa-bb','-') aa substring-before('aa-bb','a') (empty string) substring-before('aa-bb','b') aa- substring-before('aa-bb','q') (empty string) defined xpath 1.0 4.2 gecko support supported. ...
sum - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the sum function re
turns a number that is the sum of the numeric values of each node in a given node-set. syntax sum(node-set ) arguments node-set the node-set to be evaluated. each node in this node-set is evaluated as if it were passed to the number() function, and a sum of the resulting numbers is re
turned. re
turns a number. notes (none) defined xpath 1.0 4.3 gecko support supported. ...
system-property - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the system-property function re
turns an object representing the given system-property. syntax system-property(name) arguments name (optional) the name of the system property. the argument must evaluate to a string that is a qname. the qname is expanded into a name using the namespace declarations in scope for the expression. the system-property function re
turns an object representing the value of the system property identified by the name. if there is no such system property, the empty string should be re
turned. re
turns an object representing the given system-property. notes xsl:version, a number giving the version of xslt implemented by the processor; for xslt processors implementin...
translate - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the translate function evaluates a string and a set of characters to translate and re
turns the translated string. syntax translate(string, abc, xyz) arguments string the string to evaluate. abc the string of characters that will be replaced. xyz the string of characters used for replacement. the first character in xyz will replace every occurrence of the first character in abc that appears in string. re
turns the translated string. notes xpath notes that the translate function is not a sufficient solution for case conversion in all languages. a future version of xpath may provide additional functions for case conversion. however, this is the closest we have at present to a ...
true - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the true function re
turns a boolean value of true. syntax true() re
turns boolean true. defined xpath 1.0 4.3 gecko support supported. ...
unparsed-entity-url - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the unparsed-entity-url() function re
turns the uri of the unparsed entity with the given name. this is non-xml data referenced in the dtd of the source document. syntax string unparsed-entity-url(string) arguments the name of the unparsed entity. if the argument is not a string, it is converted using the rules of the string() function. the name should be an xml name. re
turns the uri of the unparsed entity retrieved from the dtd, if it exists. otherwise an empty string. defined xslt 1.0 12.4 gecko support not supported. ...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
ment.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // add the cloned dom into the xml document xmlref.appendchild(clonednode); once the stylesheet has been imported, xsltprocessor has to perform two methods for the actual transformation, namely xsltprocessor.transformtodocument() and xsltprocessor.transformtofragment(). xsltprocessor.transformtodocument() re
turns a full xml document while xsltprocessor.transformtofragment() re
turns a document fragment that can be easily added to an existing document. both take in the xml document as the first parameter that will be transformed. xsltprocessor.transformtofragment() requires a second parameter, namely the document object that will own the generated fragment. if the generated fragment will be inserted into t...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
first opening <script type='text/javascript'> tag. <button class="mybutton">run myfunction</button> now add the following code at the end of the first <script> element: document.queryselector('.mybutton') .addeventlistener('click', function() { alert('check console'); var result = module.ccall( 'myfunction', // name of c function null, // re
turn type null, // argument types null // arguments ); }); this illustrates how ccall() is used to call the exported function. ...
WebAssembly Concepts - WebAssembly
e. the glue code also contains the logic for calling the above-mentioned webassembly javascript apis to fetch, load and run the .wasm file. the generated html document loads the javascript glue file and writes stdout to a <textarea>. if the application uses opengl, the html also contains a <canvas> element that is used as the rendering target. it’s very easy to modify the emscripten output and
turn it into whatever web app you require. you can find full documentation on emscripten at emscripten.org, and a guide to implementing the toolchain and compiling your own c/c++ app across to wasm at compiling from c/c++ to webassembly. writing webassembly directly do you want to build your own compiler, or your own tools, or make a javascript library that generates webassembly at runtime? in the...
Compiling from Rust to WebAssembly - WebAssembly
we won't use this test code at all, so go ahead and delete it. let's write some rust let's put this code into src/lib.rs instead: use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { pub fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("hello, {}!", name)); } this is the contents of our rust project. it has three main parts; let's talk about them in
turn. we give a high-level explanation here, and gloss over some details; to learn more about rust, please check the free online book the rust programming language. using wasm-bindgen to communicate between rust and javascript the first part looks like this: use wasm_bindgen::prelude::*; libraries are called "crates" in rust. get it? cargo ships crates. the third line contains a use command, whi...
WebAssembly
d multiple times. webassembly.instance() a webassembly.instance object is a stateful, executable instance of a module. instance objects contain all the exported webassembly functions that allow calling into webassembly code from javascript. webassembly.instantiatestreaming() the webassembly.instantiatestreaming() function is the primary api for compiling and instantiating webassembly code, re
turning both a module and its first instance. webassembly.memory() a webassembly.memory object is a resizable arraybuffer that holds the raw bytes of memory accessed by an instance. webassembly.table() a webassembly.table object is a resizable typed array of opaque values, like function references, that are accessed by an instance. webassembly.compileerror() creates a new webassembly compileerro...